What is a Wrapper Class in Apex?

1:27 PM

A wrapper class is simply put a class which wraps variables of different data types into one single type.

We use List(account), List(string), List(integer) etc. But, what do you do when you want to create a list of all these three data types into one single list? That is when a wrapper class comes into help. Below is a simple code snippet to help understand this concept.

VF Page: 

Apex Class: 


Analyzing the code:


 The Wrapper Class in our example is named 'sampleWrapperClass'. Every wrapper class has two parts. One part to declare the variables, and the other part to define the constructor for the class. In our example, we have only one constructor. However, you can have multiple constructors by altering the parameters based upon your needs. Note that we have created a list which holds Integer,String,Boolean,Account,Contact datatypes together into one single custom data type called 'sampleWrapperClass'. You can then process this List as any other normal list. In our Visualforce page we display the list using a pageBlockTable.

Practical Examples: 


A common application is to use wrapperClass to display a table with a List of Sobject records and a check box or radio button next to each record and enable the user to select records from the table and process. 



2 comments

  1. Could you add to your post the distinction between primitive data in wrapper classes e.g. wc.sampleInteger and SObjectFields e.g. wc.sampleAccount.Name? While the former are necessary to add additional data such as a checkbox, exposing access to the latter allows Visualforce to use the meta-data such as the label and detailed data type. I have seen a number of wrapper classes posted where SObject fields are being wrapped instead of supplemented.

    ReplyDelete
    Replies
    1. Thanks for your feedback, Keith. I will try to add your suggestions to the article sooner.

      Delete