How to Create Wrapper Class in Salesforce Apex

In Salesforce Apex, we store record data using different data types. When we often work with complex data structures or manage multiple objects in a single list, we are unsure whether the method output type will be a string, a number, or a boolean.

In this situation, we use the Apex Wrapper Classes, which store a group of variables of similar or different data types into a single object.

In this Salesforce tutorial, I will explain Wrapper Classes in Salesforce Apex and how to create a wrapper class.

What is a Wrapper Class in Salesforce?

A wrapper class in Salesforce is a custom Apex class that encapsulates standard or custom objects and other data types like strings, integers, or other custom classes.

Its primary purpose is to extend the functionality of existing objects or data types, allowing us to create more complex data structures, manage user interfaces, and implement business logic efficiently.

Essentially, a wrapper class functions as an object created in Apex. It exists only in code during a transaction without consuming database storage. It serves as a data structure or abstract data type containing various objects or collections as its members.

Create a Wrapper Class in Salesforce Apex

There are multiple steps involved in creating a wrapper class in Salesforce, starting with defining a custom class in Apex and utilizing it in your Apex controller, Visualforce page, or Lightning components. We are going to discuss the steps below.

1. Define a Wrapper Class in Apex

We first need to create a custom Apex class to define a wrapper class. Then, we will add properties or variables to the class to hold the required data. The properties can be of any type, such as standard or custom objects, strings, integers, or other data types.

public class ProductWrapper {
 
    public Product2 product { get; set; }
    public Boolean selected { get; set; }
}

2. Create Constructors to initialize the Class:

When we create an instance of the class, the constructor is called automatically. The constructor should initialize the class’s properties.

public class ProductWrapper {
    public Product2 product { get; set; }
    public Boolean selected { get; set; }

    // Constructor to initialize properties
    public ProductWrapper(Product2 product) {
        this.product = product;
        this.selected = false; 
    }
}
Wrapper class in Salesforce Apex

3. Create a List of Wrapper Class Instances APex:

Now, we will create a list of fields in the wrapper class in the main logic and a controller class that will be used in the visualforce page. For this, we will create a different Controller class, and it will call the wrapper class.

public class ProductController {
    public List<ProductWrapper> productWrappers { get; set; }

    public ProductController() {
        List<Product2> products = [SELECT Id, Name, Price__c FROM Product2];
        
        productWrappers = new List<ProductWrapper>();
        for (Product2 product : products) {
            productWrappers.add(new ProductWrapper(product));
        }
    }
}

4. Using the created Apex Class on the Visualforce page:

We will use the created wrapper class on the Visualforce page, or you can also use it in the Lightning component to display a list of products and allow users to select or interact with them.

<apex:page controller="ProductController">
    <apex:form>
        <apex:pageBlock title="Products">
            <apex:pageBlockTable value="{!productWrappers}" var="wrapper">
                <apex:column value="{!wrapper.product.Name}" />
                <apex:column value="{!wrapper.product.Price__c}" />
                <apex:column>
                    <apex:inputCheckbox value="{!wrapper.selected}" />
                </apex:column>
            </apex:pageBlockTable>
            <apex:commandButton value="Submit" action="{!submitSelection}" />
        </apex:pageBlock>
    </apex:form>
</apex:page>

5. Handle Logic Based on the Wrapper Class

In the controller, we can now handle the logic based on the user’s selections. For this, extend the controller class using the code below.

    public void submitSelection() {
        List<Product2> selectedProducts = new List<Product2>();

        for (ProductWrapper wrapper : productWrappers) {
            if (wrapper.selected) {
                selectedProducts.add(wrapper.product);
            }
        }

        if (!selectedProducts.isEmpty()) {
            
            for (Product2 product : selectedProducts) {
                product.Status__c = 'Selected';
            }
            update selectedProducts;
        }
    }

Output:

To view the visualforce page, navigate to the visualforce page from Setup > Quick find > Visualforce Page > Select the visualforce page > click the preview button.

Use of Wrapper class in Salesforce Visualforce pages

On the Visualforce page, when the user selects the product through the checkbox, the product2 field “Status_c” will be updated to Selected.

In the above steps, we created a wrapper class, ProductWrapper, which combines each Product2 object checkbox, allowing Products to be displayed with checkboxes on the Visualforce page. Then, in the controller, ProductController, we set up a list of these wrapper instances, pulling all Product records and wrapping each in a ProductWrapper object ( Wrapper class).

This way, we can combine and pull the different data from objects in a single wrapper class and use it by following the above steps in Salesforce Apex.

You may also like to read:

Agentforce in Salesforce

DOWNLOAD FREE AGENTFORCE EBOOK

Start with AgentForce in Salesforce. Create your first agent and deploy to your Salesforce Org.

Salesforce flows complete guide

FREE SALESFORCE FLOW EBOOK

Learn how to work with flows in Salesforce with 5 different real time examples.