A wrapper class is a class, a data structure, or an abstract data type which contains different objects or collection of objects as its members.
The main reason for using a wrapper class is it helps in displaying the records for the multiple types of objects.
The wrapper is class which we create to hold the data which are collectively maintained in predefined data types. The wrapper is a user-defined data type that is used to collect the data that could be a collection, boolean, sobject or could be a wrapper itself.
Below is the Requirement where we can use Wrapper class.
Requirement:
Create a table in which there is a list of contact name, email. when user select checkbox against any row of the contact list and after that click on the button then send the email to that particular email id.
VisualForce page Code :
<apex:page standardController="Contact" extensions="WrapperClsOnContact">
<apex:form >
<apex:pageMessages >
</apex:pageMessages>
<apex:pageBlock >
<apex:pageBlockTable value="{!wrapperObj}" var="x">
<apex:column value="{!x.conobj.name}"/>
<apex:column value="{!x.conobj.email}"/>
<apex:column >
<apex:inputcheckbox value="{!x.checkBox }"/>
</apex:column>
</apex:pageBlockTable>
<apex:pageBlockSection >
<apex:commandButton value="SendEmail" action="{!sendEmail}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex Class :
public with sharing class WrapperClsOnContact {
public List<WrapperClassEx> WrapperList{get;set;}
public WrapperClsOnContact(ApexPages.StandardController controller) {
}
public List<WrapperClassEx> getwrapperObj(){
List<Contact> conList =[select id, name, email from contact limit 5];
WrapperList = new List<WrapperClassEx>();
for(Contact con: conList){
WrapperList.add(New WrapperClassEx(con,false));
}
return WrapperList;
}
public class WrapperClassEx{
public Contact conObj{get;set;}
public Boolean checkBox{get;set;}
public WrapperClassEx(Contact conRec, boolean SelectedBox){
conObj= conRec;
checkBox = SelectedBox;
}
}
public void sendEmail(){
List<Messaging.SingleEmailMessage> lstEmailId=new List<Messaging.SingleEmailMessage>();
for(WrapperClassEx w: WrapperList){
if(w.checkBox == true){
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {w.conObj.Email});
mail.setReplyTo('sumit.shukla@magicsw.com');
mail.setplainTextBody('Hello');
mail.setSenderDisplayName('Your Company Name');
mail.setSubject('Test Email From Force.com Sites');
lstEmailId.add(mail);
}
}
if(lstEmailId.size()>0){
try{
Messaging.sendEmail(lstEmailId);
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.Confirm,'Sent!'));
}Catch(Exception ee){
ApexPages.AddMessage(new ApexPages.Message(ApexPages.Severity.Error,ee.getMessage()));
}
}
}
}
I hope you will find this useful.
Thanks 🙂