Wednesday, October 10, 2018

Wrapper class in salesforce

Today we will try to cover the topic Wrapper class in Salesforce.

Wrapper class in salesforce


In simple term wrapper class is a class whose instances are a collection of objects.




Why wrapper class is required?

In visualforce, we can operate on one object at a time and can display data related
to that particular object using page block table. What if we want data from a number of
objects? In this case, we can make use of the wrapper class.

Another most important use is when you want to display data with check-boxes and then
display selected data based on a checkbox.

Let say if I have two custom objects and these objects do not have any relationship in between them and I want to display data from both these objects in the table.




Object1:
Testobject1__c

Fields on object 1:
name,
testfield1__c.


Object2:
Testobject2__c

Fields on object 2:
name,
testfield1__c.


Below is the controller for the above requirement.

Controller:


public class WrapperClassTwoObject{


list<Testobject1__c> objList1=new list<Testobject1__c>();
list<Testobject2__c> objList2=new list<Testobject2__c>();

public list<wrapperClass> wrapperClassList=new list<wrapperclass>();
public list<wrapperClass> getListWrapperObjectMethod()
{
objList1=[Select name,testfield1__c from Testobject1__c limit 1];
objList2=[Select name,testfield1__c from Testobject2__c limit 1];
for(integer i=0;i<objList1.size();i++)
{
wrapperClassList.add(new wrapperCLass(objList1[i].name,objList1[i].testfield1__c,objList2[i].name,objList2[i].testfield1__c ));

}
return wrapperClassList;

}

public class wrapperClass
{

public string name{get;set;}
public string fieldDataOne{get;set;}
public string name1{get;set;}
public string fieldDataTwo{get;set;}

public wrapperCLass(string name,string fieldDataOne,string name1,string fieldDataTwo)
{
this.name=name;
this.fieldDataOne=fieldDataOne;
this.name1=name1;
this.fieldDataTwo=fieldDataTwo;

}

}


}


Below is the visualforce page for the above requirement.

Visualforce:



<apex:page controller="WrapperClassTwoObject">
  <apex:form >
  <apex:pageBlock >
  <apex:pageBlockSection >

  <apex:pageBlockTable value="{!ListWrapperObjectMethod}" var="a">
  <apex:column value="{!a.name}"/>
  <apex:column value="{!a.fieldDataOne}"/>
  <apex:column value="{!a.name1}"/>
  <apex:column value="{!a.fieldDataTwo}"/>
 
  </apex:pageBlockTable>
  </apex:pageBlockSection>
  </apex:pageBlock>
 
 
  </apex:form>
</apex:page>


Result Image:


wrapper class in salesforce
***********************************************************************************************************
Wrapper class in salesforce,what is a wrapper class in salesforce,wrapper class in salesforce example,wrapper class salesforce.
***********************************************************************************************************

No comments:

Post a Comment