Wrapper Class in Apex Salesforce

Wrapper class in Apex Salesforce

Wrapper Class in Apex Salesforce : A wrapper or container class is a class, a data structure, or an abstract data type which contains different objects or collection of objects as its members.

A wrapper class is a custom object defined by programmer wherein he defines the wrapper class properties. Consider a custom object in salesforce, what do you have in it? fields right? different fields of different data types. Similarly wrapper class is a custom class which has different data types or properties as per requirement. We can wrap different objects types or any other types in a wrapper class.

In the Visualforce most important use case is to display a table of records with a check box and then process only the records that are selected.

In the example below, we are displaying list of accounts with checkbox. End user can select account and then click on Show Selected accounts button. Then selected account will be displayed in table.

Click for Demo

Wrapper Class in Apex Salesforce

Visualforce Code:

<apex:page controller="AccountSelectClassController" sidebar="false">
    <script type="text/javascript">
        function selectAllCheckboxes(obj,receivedInputID){
            var inputCheckBox = document.getElementsByTagName("input");                  
            for(var i=0; i<inputCheckBox.length; i++){          
                if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){                                     
                    inputCheckBox[i].checked = obj.checked;
                }
            }
        }
    </script>
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Show Selected Accounts" action="{!processSelected}" rerender="table2"/>
            </apex:pageBlockButtons>
            
            <apex:pageblockSection title="All Accounts" collapsible="false" columns="2">
            
                <apex:pageBlockTable value="{!wrapAccountList}" var="accWrap" id="table" title="All Accounts">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!accWrap.acc.Name}" />
                    <apex:column value="{!accWrap.acc.BillingState}" />
                    <apex:column value="{!accWrap.acc.Phone}" />
                </apex:pageBlockTable>          
                      
                <apex:pageBlockTable value="{!selectedAccounts}" var="c" id="table2" title="Selected Accounts">
                    <apex:column value="{!c.Name}" headerValue="Account Name"/>
                    <apex:column value="{!c.BillingState}" headerValue="Billing State"/>
                    <apex:column value="{!c.Phone}" headerValue="Phone"/>
                </apex:pageBlockTable>
            
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
  
</apex:page>

Apex Class Controller:

public class AccountSelectClassController{

    //Our collection of the class/wrapper objects wrapAccount 
    public List<wrapAccount> wrapAccountList {get; set;}
    public List<Account> selectedAccounts{get;set;}
    
    public AccountSelectClassController(){
        if(wrapAccountList == null) {
            wrapAccountList = new List<wrapAccount>();
            for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 10]) {
                // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
                wrapAccountList.add(new wrapAccount(a));
            }
        }
    }

    public void processSelected() {
    selectedAccounts = new List<Account>();

        for(wrapAccount wrapAccountObj : wrapAccountList) {
            if(wrapAccountObj.selected == true) {
                selectedAccounts.add(wrapAccountObj.acc);
            }
        }
    }


    // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Account and a Boolean value
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}

        //This is the contructor method. When we create a new wrapAccount object we pass a Account that is set to the acc property. We also set the selected value to false
        public wrapAccount(Account a) {
            acc = a;
            selected = false;
        }
    }
}

Permanent link to this article: https://www.sfdcpoint.com/salesforce/wrapper-class-in-apex/

20 comments

Skip to comment form

    • Ashok on March 8, 2014 at 11:38 am
    • Reply

    Nice and useful post.Thanks

    • Pruthvi Raj on March 10, 2014 at 12:42 pm
    • Reply

    Nice post…

    • Bhanu on August 18, 2014 at 12:22 pm
    • Reply

    Informative……

    • Naresh on September 10, 2014 at 3:16 pm
    • Reply

    Thanks.. Nice and helpful post.

    • Kiran on November 10, 2014 at 2:54 pm
    • Reply

    Thanks…nice post….:)

    • Monika on February 23, 2015 at 12:49 pm
    • Reply

    Thank u alot.. very helpfull:)

    • cdc.nisha@gmail.com on April 2, 2015 at 12:45 pm
    • Reply

    but i want to add selected account to contacts or i want to add selected products to opportunity..
    By how i can do that??plz repl

    • Shekar Krish on April 22, 2015 at 10:45 pm
    • Reply

    Very good example

    • Shivam Gupta on June 29, 2017 at 4:56 pm
    • Reply

    good one..!

    • prema thakur on August 22, 2017 at 5:45 pm
    • Reply

    But when i click the checkbox which is just before the Account column,its not selecting the whole records also I want the record name should be a link ..can it be possible?

    1. I am able to check all records by clicking on checkbox. Check this demo: http://demopoint-developer-edition.ap1.force.com/apex/wrapperAccountSelect
      Also you can use apex:outputlink to show link of account.

    • Amit Singh on April 12, 2018 at 10:53 pm
    • Reply

    Hi please tell me how to insert selected record in child custom object. Child__c

    • Lakshmi Priya on April 6, 2020 at 12:51 pm
    • Reply

    Hi,
    Please help me to do the same procedure fre lead, when a checkbox is selected and convert button is clicked the lead should be converted.

    1. You can follow the same process to show lead instead of account. In process selected method in apex class you need to write code to convert lead. Here is sample code
      https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_dml_examples_convertlead.htm

  1. How should i write a test class for this i am not able to cover selected accounts

    • Ken on August 20, 2020 at 11:39 pm
    • Reply

    public class wrapAccount

    should be …

    public class WrapAccount

    Coding style is IMPORTANT. Class names always begin with upper cases. Members and instance variables always begin with lowercase.

    • Ram on September 17, 2020 at 2:07 am
    • Reply

    Very Helpful..Thnkyou

    • Euclides on February 18, 2021 at 4:03 am
    • Reply

    Hi.
    Could you please show me how to set up a test class for this block of code?
    Thank you.

    • subbu on February 4, 2022 at 10:07 pm
    • Reply

    Hi
    i want to display list o f parent records and checkboxs and two buttons (selected & delete) then i select the parent record click on selected button after display no of child records in vf page using wrapper class.

    • test on February 15, 2022 at 10:00 am
    • Reply

    this is helpfull

Leave a Reply

Your email address will not be published.