Wrapper Class Tutorial Learning Path - Be Productive with [Salesforce]
Wrapper Class in Salesforce Tutorial

Wrapper Class Tutorial Learning Path – Be Productive with [Salesforce]

Last updated on 08th Jul 2020, Blog, Tutorials

About author

Madhuri (C# Automation Tester )

Madhuri is a C# Automation Tester and she has tons of experience in the areas of HTTP, SOAP/REST, VisualStudio, TFS, etc., CI/CD, functional, regression, and.NET technology stack. She spends most of her time researching technology and startups.

(5.0) | 19616 Ratings 1911

Wrapper class

  • A Wrapper class is a class whose instances are collection of other objects. It is used to display different objects on a Visual Force page in same table. Wrapper class in salesforce is a class which contains collection of different objects as its members, we can wrap different types of objects and can bring it on visual force page.
  • Wrapper Class in Apex Salesforce : A wrapper or container class is a class, a data structure, or an abstract data type which contains different objects or collection of objects as its members.
  • A wrapper class is a custom object defined by programmer wherein he defines the wrapper class properties. Consider a custom object in salesforce, what do you have in it? fields right? different fields of different data types. Similarly wrapper class is a custom class which has different data types or properties as per requirement. We can wrap different objects types or any other types in a wrapper class.
  • In the Visualforce most important use case is to display a table of records with a check box and then process only the records that are selected.

When to use Wrapper Class?:

  • Suppose You have to store account corresponding to the primary contact. In that case, you have to use the wrapper class because in general what we have collections like List which can hold only one Object type-
  •  List acc = new List();  Using List we won’t be able to store Accounts and Contacts together, their wrapper class comes to rescue, we can declare Account and contact as wrapper class members and then use that class as a collection.
  • Class wrapperClass{
  • Public Account a;
  • Public Contact c;
  • }

And then use this wrapper class as a collection type.

    Subscribe For Free Demo

    [custom_views_post_title]

    • List wrap = new List();

    How to use the Wrapper Class?:

    • Here is an example, to show the accounts that are selected by the checkbox shown on the right side of the page.
    • Create a visualforce page which displays the accounts and checkbox.
    • Create an apex class which has a wrapper class with Account and checkbox selection as its properties.
    • public class WrapClass {
    • //list of wrapper class type
    • public List wrapaccountList{get;set;}
    • //Accounts which are selected will be stored in this list
    • public List selectedAccounts{get;set;}
    • //constructor
    • public WrapClass(){
    • //Initalize the list
    • wrapaccountList = new List();
    • //reterive Account records
    • for(Account a:[Select id, Name, Phone, BillingCity From Account limit 10]){
    • //Add the accounts to the wrapper class list
    • wrapaccountList.add(new wrapAccount(a));
    • }}
    • //When button is clicked this method will get executed
    • public void processSelected(){
    • selectedAccounts =new List();
    • //for every record in the wrapper class list add the records in selectedAccounts list //whose checkbox are selected
    • for(wrapAccount wrapObj: wrapaccountList){
    • if(wrapObj.isSelected == true){
    • selectedAccounts.add(wrapObj.accn);
    • }}}
    • //Define Wrapper Class
    • public class wrapAccount{
    • public Boolean isSelected {get;set;}
    • public Account accn {get;set;}
    • public wrapAccount(Account a ){
    • accn =a ;
    • isSelected =false;
    • }
    • wrap account}
    • Here wrap account is wrapper class which has checkbox isSelected and Account object as its properties. The table will iterate through the list of the wrapper class.

    Use of Wrapper Class within Salesforce:

    • Many times in the community boards, people have asked the questions on how they can display a table of records with a check box and then process only the records that are selected. You can do it using this below step by step instructions. You can use wrapper class to display records from multiple records within a single table based around the business needs.
    • Here is an example if you want to display account data in the table along with a checkbox on the right side of the table (checkbox with every row). You can bind an account checkbox field to this right column but below is an example for demonstrating wrapper with a custom checkbox column.

    Wrapper Class Salesforce Guide

    If you will compare then the general architecture of the Salesforce is almost similar to the database where objects are defined as the table, fields are taken as columns, and records are defined as rows here. With multiple sets of classes defined to ease the development work, Salesforce has its own MVC architecture to implement successfully.

    About MVC Architecture

    • Model-View-Controller – The model is defined through Salesforce UI where metadata is saved to view later as XML. The view layer is made up of Visualforce pages and you can use Lightning components as needed. The controller is an APEX class that is further extended to the MVC controller and data is passed to available models ahead to view elements.
    Course Curriculum

    Enroll in Salesforce Certification Course to UPGRADE Your Skills

    Weekday / Weekend BatchesSee Batch Details
    • If you want to check how to handle the basic data in the Salesforce then developers are mainly restricted to data structures of a single object type while the relationship among these data structures is also defined as necessary. With a simpler technique to manage multiple objects together, we need only one object for each field. This situation sounds a little confusing in beginning but little practice can make you a pro.

    Wrapper Classes are the Solution

    • As the name suggests, the wrapper classes are used here to wrap the data together from existing objects to the new one. This special type is named as the SObject here that it doesn’t contain any database or the related fields here, it doesn’t have any API pages too but they are valid objects for sure.In simple words, wrapper classes are the container classes, a data structure, an abstract data type etc that contains multiple objects and its members together. It can also be named as the custom object that is defined by the developer with a set of properties. Take an example of a custom class in the Salesforce that contains fields and each filed has a specific data type. In the same way, wrapper classes are also custom classes that have different data types and properties that can be defined as per the requirement. To wrap different data objects, there is nothing better option than wrapper class in the Salesforce.
    • For the Visualforce, the most important use case is displaying a set of records with a checkbox or define the process for the records that are selected.

    Wrapper Class – Everyday pattern in Salesforce

    1. Here, we will discuss why wrapper classes are defined as the everyday Salesforce pattern. The Salesforce has an excellent reference document, great training tool Trailhead, and excellent books or PDFs on enterprise patterns. By everyday Salesforce patterns here we mean the tools that are used by Salesforce developers almost daily.
    2. This is common in Visualforce performing some queries on data before it is actually displayed to the user. The activities may include as listed below –
    • Enriching one data object by taking data from another object.
    • Framing or presenting multiple threads of data together in a single list.
    • A mapping table to connect values together for different fields of an object.
    • An appending summary for the data calculated in the APEX.

    The best solution or a single reply to all these issues is Wrapper classes. Each wrapper class could have different specifications as it is designed based on user specifications but the overall structure is simpler and the same for all wrapper classes. Wrapper classes don’t have an inner class defined by default but the usage of inner classes could be extra effective and common in Salesforce. Wrapper classes are used in the same way as Structure, Unions, or Algebraic types for other classes. The usage is restricted with limited introspection and the dynamism available in APEX.To make any wrapper class more powerful, try using highly calculated properties within your wrapper class instead of opting highly complicated rendering. Keep in mind that there is a requirement to enforce permission manually so data restructuring comes with a requirement to enforce all these permissions appropriately.

    How to sort wrapper class collection in APEX?

    • There is a pre-defined functionality in APEX that can be used to sort primitive data types in the Salesforce. Most developers must have faced the situation where they need to sort the custom data types in terms of force.com. But the question comes how force.com will know about class sorting? How would they know about the data to be used within a class?
    • Before the Summer 12 release, there was not any direct technique for the same. But thanks to the Salesforce that has made things easier and introduced the wrapper class collection method for the same. It kept a long smile on the face of developers especially Java programmers because they had hands-on expertise on the same.

    Visualforce Code:

    • <apex:page controller=”AccountSelectClassController” sidebar=”false”>
    • <img src=”data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP ///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7″ data-wp-preserve=”%3Cscript%20type%3D%22text%2Fjavascript %3E%0A%20%20%20%20%20%20%20%20function%20 selectAllCheckboxes(obj%2CreceivedInputID) %7B%0A%20%20 %20%20%20%20%20%20%20inputCheckBox%20%3D%20 document.getElementsByTagName (%22input%22)%3B%20%20 %20%20%20%20%20%2020%20%20%20%20%0A%20 %20%20%20%20%20%20%20%20%20%20%20for (var%20i%3D0%3B%20i%3 CinputCheckBox.length%3B%20i%2B%2B)%7B%20%20%20%20 %20%20%20%20%20%20%0A%20 %20%20%20%20%20%20%20%20%20if(inputCheckBox%5Bi %5D.id.indexOf(receivedInputID) !%3D-1)%7B%20%20%20%20%20%20%20%20%20%20%20%20%20%20% 20%20%20%20%20%20%20%20 %20%20%20%20%20%20%20%20%20%20%0A%20%20%20%20%20 %20%20%20%20%20%20%20%20%20%20%20inputCheckBox%5Bi%5D.checked%20%3D %20obj.checked%3B%0A%20%20%20%20%20%20%20%20%20%20%20 %20%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%0A7D%0A%20%20%20%20%3C %2Fscript%3E” data-mce-resize=”false” data-mce-placeholder=”1″ class=”mce-object”  width=”20″ height=”20″ alt=”&lt;script&gt;” title=”&lt;script&gt;” />
    • <apex:form >
    •     <apex:pageBlock >
    •          <apex:pageBlockButtons >
    •              <apex:commandButton value=”Show Selected Accounts” action=”{!processSelected}” rerender=”table2″/>
    •          </apex:pageBlockButtons>
    •  <apex:pageblockSection title=”All Accounts” collapsible=”false” columns=”2″>
    • ; <apex:pageBlockTable value=”{!wrapAccountList}” var=”accWrap” id=”table” title=”All Accounts”>
    • <span style=”font-weight:

    Apex Class Controller:

    Course Curriculum

    Learn On-Demand Salesforce Training with Advanced Concepts By Industry Experts

    • Instructor-led Sessions
    • Real-life Case Studies
    • Assignments
    Explore Curriculum

     

    • public class AccountSelectClassController{
    • //Our collection of the class/wrapper objects wrapAccount
    • public List<wrapAccount wrapAccountList {get; set;}
    • public List<Account selectedAccounts{get;set;}
    •     public AccountSelectClassController(){
    • if(wrapAccountList == null) {
    •   wrapAccountList = new List<wrapAccount>();
    • for(Account a: [select Id, Name,BillingState, Website, Phone from Account limit 10]) {
    •              // As each Account is processed we create a new wrapAccount object and add it to the wrapAccountList
    •              wrapAccountList.add(new wrapAccount(a));
    •          }
    •      }
    • }
    •     public void processSelected() {
    • selectedAccounts = new List<Account>();
    •         for(wrapAccount wrapAccountObj : wrapAccountList) {
    •          if(wrapAccountObj.selected == true) {
    •              selectedAccounts.add(wrapAccountObj.acc);
    •          }
    •      }
    • }

     

        // This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Account and a Boolean value

            //This is the contructor method. When we create a new wrapAccount object we pass a Account that is set to the acc property. We also set the selected value to false

    • public class wrapAccount { public Account acc {get; set;}
    • public Boolean selected {get; set;} //This is the contructor method.
    • When we create a new wrapAccount object we pass a Account that is set to the acc property.
    • We also set the selected value to false public wrapAccount(Account a)
    • { acc = a; selected = false; } } }

    What are the Advantages?

    • Similar to the JSON structure, the structure of the wrapper class is also similar to the data visualization technique on the web page.
    • There is no need for passing MAP structure to browse elements or to maintain the relationship among objects.
    • Data can be organized beautifully when it is nested well on different levels.
    • There is no penalty in passing SObject and they are more extendable to the class constructors.
    • With a Transient view, you could maintain smaller view state especially when data is passed through the browser and accessed back.

    Salesforce Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

    You can keep container classes and wrapper classes together but this is good to store them separately. When kept independent, they are easy to maintain and reuse whenever needed and it prevents code duplication too.

    Use of Wrapper Class within Salesforce:

    Many times in the community boards, people have asked the questions on how they can display a table of records with a check box and then process only the records that are selected. You can do it using this below step by step instructions. You can use wrapper class to display records from multiple records within a single table based around the business needs.

    Conclusion

    In this way, wrapper classes were proven as a boom for Salesforce developers with a wider range of solutions and functionalities. It is used everywhere today and developers have realized their benefits too. Every time when you want to compare the custom objects or need to add more functionalities then try using wrapper classes in your own way.

    Are you looking training with Right Jobs?

    Contact Us
    Get Training Quote for Free