- Salesforce Blogs -

Wrapper Class Salesforce Tutorial Guide for Beginner

Salesforce is an object-oriented and strong typed platform. Salesforce Org back-office is a simple UI representation of the relational database system where APEX is used as the C# language to work on multiple data structures and SOQL is the query language that combines data queries and APIs together.

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 MVC controller and data is passed to available models ahead to view elements.

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 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 little confusing in beginning but little practice can make you a pro.

Here is the example of a nested structure in Salesforce –

Read: Top 7 Impactful Salesforce Data Loaders Tools: Import & Export Data

Wrapper Class Salesforce Guide

AS you can see that one contact could have multiple orders and each order could have multiple order lines ahead. This type of nested structure is represented through a NoSQL database or JSON.

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. salesforce Curriculum 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.

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.

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.

Hence, this is clear that wrapper classes are used to create a new object in the APEX code that can combine multiple fields from different objects or a set of fields that are majorly needed at the runtime only. It provides flexibility and extra control over data objects to view or control elements.

Read: What Is Interesting About Salesforce Internships?

From the frontend point of view, The APEX code on the main page will be more readable when using UI components within repeat statements. Within Apex, Lightning, or VisualForce, wrapper classes can always be helpful in managing complex business scenarios by expanding developer capability during application customization.

Wrapper Class – Everyday pattern in Salesforce

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.

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 specification as it is designed based on user specifications but the overall structure is simpler and same for all wrapper classes. Wrapper classes don’t have any 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. salesforce quiz 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 datatypes in the Salesforce. Most developers must have faced the situation where they need to sort the custom datatypes 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 the things easier and introduced 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 expertize on the same.

Read: Create Different Format Reports in Salesforce - Tabular, Summary, Matrix and Joined Report

Visualforce Code:


<apex:page controller="AccountSelectClassController" sidebar="false">
    <img src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7" data-wp-preserve="%3Cscript%20type%3D%22text%2Fjavascript%22%3E%0A%20%20%20%20%20%20%20%20function%20selectAllCheckboxes(obj%2CreceivedInputID)%7B%0A%20%20%20%20%20%20%20%20%20%20%20%20var%20inputCheckBox%20%3D%20document.getElementsByTagName(%22input%22)%3B%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%20for(var%20i%3D0%3B%20i%3CinputCheckBox.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%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%20%20%20%20%20%0A%20%20%20%20%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%20%20%20%20%7D%0A%20%20%20%20%20%20%20%20%7D%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">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox value="{!accWrap.selected}" id="inputId"/>
                    </apex:column>
                    <apex:column value="{!accWrap.acc.Name}" />
                    <apex:column value="{!accWrap.acc.BillingState}" />
                    <apex:column value="{!accWrap.acc.Phone}" />
                </apex:pageBlockTable>          
                       
                <apex:pageBlockTable value="{!selectedAccounts}" var="c" id="table2" title="Selected Accounts">
                    <apex:column value="{!c.Name}" headerValue="Account Name"/>
                    <apex:column value="{!c.BillingState}" headerValue="Billing State"/>
                    <apex:column value="{!c.Phone}" headerValue="Phone"/>
                </apex:pageBlockTable>
             
            </apex:pageblockSection>
        </apex:pageBlock>
    </apex:form>
   
</apex:page>

Apex Class Controller:


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
    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;
        }
    }
}

Verdict

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 wanted to compare the custom objects or need to add more functionalities then try using wrapper classes in your own way. free salesforce demo You are free to add multiple fields within an object as needed and maximize the usability of an application too. With this discussion, we come to an end to this blog. To know more, practice some program to learn how to use wrapper classes in Salesforce or join Salesforce certification training program to clear your doubts right away.

 

Read: Salesforce Architect Certification Study Guide

    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

1 day 22 Oct 2019

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing

Upcoming Class

5 days 26 Oct 2019

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning

Upcoming Class

5 days 26 Oct 2019

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation

Upcoming Class

6 days 27 Oct 2019

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

4 days 25 Oct 2019

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Setup Selenium for UI Automation

Upcoming Class

13 days 03 Nov 2019

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum

Upcoming Class

3 days 24 Oct 2019

SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design

Upcoming Class

8 days 29 Oct 2019

Comments

Search Posts

Reset

Receive Latest Materials and Offers on Salesforce Course

Interviews