A wrapper class is a class, a data structure, or an abstract data type which contains different primitive data types and objects as a class member variable. We can go for wrapper class when we need to perform some operation in the records using other then object fields in that case we can use it.
Here is an example, I want to display list of account data in a table along with a check box on the right side of the table for every row, and I want to show selected account records in another table.
I’ve created a wrapper class with Account object and a Boolean variable members. Retrieving list of account records and binding it to wrapper class. For every account and checkbox value(false) I’m storing a new wrapper class records in the wrapper class list, and in the Visualforce page the value of pageBlockTable
is wrapper class list.
Visualforce Page:
<apex:page controller="SampleController" tabStyle="Account" sidebar="false"> <apex:form > <apex:pageBlock > <apex:pageBlockButtons > <apex:commandButton value="Show Selected Accounts" action="{!getSelectedAccounts}" rerender="pbTable2"/> </apex:pageBlockButtons> <apex:pageblockSection title="All Accounts" collapsible="false" columns="2"> <apex:pageBlockTable value="{!accWrapList}" var="accWrap" id="pbTable1" title="All Accounts"> <apex:column> <apex:inputCheckbox value="{!accWrap.isSelected}"/> </apex:column> <apex:column value="{!accWrap.acc.Name}"/> <apex:column value="{!accWrap.acc.Industry}"/> <apex:column value="{!accWrap.acc.Phone}"/> </apex:pageBlockTable> <apex:pageBlockTable value="{!selectedAccountList}" var="acc" id="pbTable2" title="Selected Accounts"> <apex:column value="{!acc.Name}" headerValue="Account Name"/> <apex:column value="{!acc.Industry}" headerValue="Industry"/> <apex:column value="{!acc.Phone}" headerValue="Phone"/> </apex:pageBlockTable> </apex:pageblockSection> </apex:pageBlock> </apex:form> </apex:page>
Apex Controller:
public class SampleController{ //Account List and AccountWrapper Class List Variables public List<AccountWrapper> accWrapList {get; set;} public List<Account> selectedAccountList {get;set;} public SampleController(){ accWrapList = new List<AccountWrapper>(); List<Account> accList = new List<Account>(); accList = [SELECT Id, Name, Type, Industry, Phone FROM Account LIMIT 10]; for(Account a: accList) { //Add each Account record to AccountWrapperList accWrapList.add(new AccountWrapper(a)); } } public void getSelectedAccounts() { selectedAccountList = new List<Account>(); for(AccountWrapper obj : accWrapList) { if(obj.isSelected == true) { selectedAccountList.add(obj.acc); } } } //Account Wrapper Class. //This wrapper class contains both the standard salesforce object Account and a Boolean value. public class AccountWrapper { public Account acc {get; set;} public Boolean isSelected {get; set;} public AccountWrapper(Account a) { acc = a; isSelected = false; } } }