Tuesday, 9 August 2016

Wrapper Class In Salesforce


A wrapper class is a class,data structure whose instance are a collections of other objects. It is a custom object defined by Salesforce developer, where he defines the properties of the wrapper class. Within Apex and Visualforce this can be extremely helpful to achieve many business scenarious within the Salesforce.

Here is a most commonly asked scenario, how we can display data within a table with checkbox and then process only the record which are selected:


Apex Code:
public class WrapperController
{
  Public list<wrapperaccount> acctlist;
    
    public List<wrapperaccount> getAccount()
    {
        if(acctlist==null)
        {
          acctlist=new List<wrapperaccount>();
          list<account> aa=[Select name from account];
          for(Integer i=0;i<aa.size();i++)
          {
           acctlist.add(new wrapperaccount(aa[i]));
          }
        }
        return acctlist;
    }
    public pageReference deleteaccount()
    {
        List<Account> selectedaccount=new List<Account>();
        for(wrapperaccount aa:getAccount())
        {
            if(aa.checkbox==true)
            {
                selectedaccount.add(aa.act);
            }
        }
        for(account act:selectedaccount)
        {
            delete act;
        }
        acctList=null;
        return null;
    } 
   public class wrapperaccount
    {
        public account act{get;set;}
        public boolean checkbox{get;set;}
        public wrapperaccount(account a)
        {
            act=a;
            checkbox=false;
        }
    }
}
Visualforce page Code:
<apex:page controller="WrapperController">
<apex:form >
    <apex:pageblock >
    <apex:pageblockButtons >
    <apex:commandButton value="Delete" action="{!deleteaccount}" />
    </apex:pageblockButtons>
    
    <apex:pageblocktable value="{!Account}" var="a">
    <apex:column >
    <apex:inputCheckbox value="{!a.checkbox}"/>
    </apex:column>
    <apex:column value="{!a.act.Name}"/>
    
    </apex:pageblocktable> 
    </apex:pageblock>
</apex:form>
</apex:page>

Thank you friends...
I hope it will help you. If you have any query, you can ask me anytime.
So keep reading and love technology..:)

No comments:

Post a Comment