Wednesday, 31 May 2017

Wrapper class, as name suggests, is used for wrapping two types of data together and make them to work as single record.

For example, let's take a sample scenario to understand the wrapper class.
User wants to display account records along with checkboxes on VF page.
User should be able select more than one record and work on them.
In this scenario we will fetch account records and wrap them with checkbox.

In this example we will display list of accounts with checkboxes. select those records we want to update and click on update button. All selected record's name will be appended by 1.
//Sample Class for wrapper
Public class wrapperSample
{
 public list<Account> acc{get; set;}
 public list<wrapperAction> wrapper {get; set;}

 public wrapperSample()
 {
   acc = new list<account>();
   wrapper = new list<wrapperAction>();
   acc = [select id, name from account limit 10];
   for(account a : acc)
   {
     wrapper.add(new wrapperAction(a)); //Sending records to wrapper class
   }
 
 }

 // Creating wrapper records of accounts with a boolean variable flag
 public class wrapperAction
 {
   public boolean flag{get; set;}
   public account acc{get; set;}
   public wrapperAction(account a)
   {
     acc = a;
flag = false;
   }
 }
 //Updating the name of accounts selected on VF page
 public void recordUpdate()
 {
   list<account> updateAccounts = new list<Account>();
 
   for(wrapperAction wr: wrapper)
   {
     if(wr.flag)
{
  wr.acc.name = wr.acc.name+' 1';
  updateAccounts.add(wr.acc);
}
 
   }
 
   update updateAccounts;
 }

}



//Visualforce page to display the records with checkbox

<apex:page controller="wrapperSample">
  <apex:form id="form">
   <apex:pageBlock >
    <apex:pageBlockTable value="{!wrapper}" var="wr">
     <apex:column >
      <apex:inputcheckbox value="{!wr.flag}" />
     </apex:column>
     <apex:column value="{!wr.acc.id}"/>
     <apex:column value="{!wr.acc.name}"/>
    </apex:pageBlockTable>
    <apex:commandButton value="Update" action="{!recordUpdate}" rerender="form"/>
   </apex:pageBlock>

  </apex:form>
</apex:page>



Once the update is done all the selected records name will get appended by 1 As shown in figure.


The above is a simple scenario of wrapper class. Similarly in many complex scenario's also wrapper class is used to achieve functionality in less code.

No comments:

Post a Comment

Create record in lightning

With the advancement of lightning, we are getting introduced to new features of lightning that helps in creating a better functionality in ...