A quick search for Salesforce wrapper results in the following definition. A wrapper or container class is a class, a data structure, or an abstract data type whose instances are collections of other objects.
That’s fine but if you’re new to the concept then it is likely that the definition of a Salesforce wrapper class is not as useful as a practical example of the logic.
Let’s say that you want to build a simple Visualforce page that will display a list of Contacts. For the page you will require a controller similar to the following:
The Visualforce page corresponding to the above controller looks like:
The resulting page looks like:
Now let’s say that you want to add another column to the resulting page with an integer that corresponds to the row number for the record. This would be a great use for a Salesforce wrapper class.
Basically, we are looking to combine two different objects into one list within the page controller so that we can iterate over that list in the Visualforce page. In this case the two objects are a Contact object and an Integer. Altering our original controller to allow for the wrapper class results in the following controller.
To make use of that new wrapper being passed from the controller we need to modify our Visualforce page as follows.
Notice that we now have to use dot notation for accessing the details of the Contact record as we iterate over the list of wrapped data. Since we assign the wrapped data to the variable “w” we have to tell the page which object from that object that we want for each column. Our options as defined within the controller are the “contact” object, which holds the Contact fields from our SOQL query, and the “rowCounter” object, which is simply an Integer.
You will also notice that we need to define the column header for the “rowCounter” object from the wrapper using the <apex:facet> tag. Otherwise the column header will be blank.
The resulting visualforce page looks as follows:
“Explore – Techila Global Services, A Salesforce development company”