SaasGuru Logo

🎉Access Your AI-Powered Salesforce Co-Pilot! Get Started for Free 🎉

🎉Access Your AI-Powered Salesforce Co-Pilot! Get Started for Free 🎉

What is a Wrapper Class in Salesforce?

In the Salesforce ecosystem, developers often face challenges when working with complex data structures and user interfaces. One powerful tool that can help overcome these challenges is the wrapper class. In this article, we will explore the concept of wrapper classes, their importance in Salesforce, how to create them, their benefits, and common use cases.

What is a Wrapper Class?

A wrapper class is a custom class in Salesforce that wraps or encapsulates standard or custom objects, along with other data types like strings, integers, or even other custom classes. The purpose of a wrapper class is to extend the functionality of the existing objects or data types, allowing developers to create more complex data structures, manage user interfaces, and implement business logic with ease.

Wrapper classes play a crucial role in Salesforce development. They allow developers to:

  1. To merge various objects or data types into a single unit.
  2. Manipulate or process data from various sources.
  3. Design custom user interfaces in Visualforce or Lightning Web Components.
  4. Implement complex business logic.
  5. Enhance code reusability and maintainability.

saasguru Salesforce Labs: Real-time Projects for Practice

Example of a Wrapper Class in Salesforce

Here’s a simple example of a wrapper class in Salesforce:

public class AccountWrapper {

    public Boolean isSelected { get; set; }

    public Account account { get; set; }

    public List<Contact> relatedContacts { get; set; }

    public AccountWrapper(Account acc) {

        this.isSelected = false;

        this.account = acc;

        this.relatedContacts = new List<Contact>();

    }

}

This wrapper class encapsulates an Account object, a boolean isSelected property, and a list of related Contact objects.

How to Create a Wrapper Class in Salesforce?

Creating a wrapper class in Salesforce involves several steps, from defining a custom class in Apex to using the class in your Apex controller or Visualforce page or lightning components. Here’s a detailed look at the process:

1. Define a Custom Class in Apex

Firstly, you’ll need to define a custom class in Apex. Apex is a strongly-typed, object-oriented programming language used in Salesforce. The class name typically follows the object or functionality it encapsulates. For instance, if the class is meant to encapsulate the Account object, the class could be named AccountWrapper.

public class AccountWrapper {

}

2. Add Properties or Variables to Hold the Required Data

The next step is to add properties or variables to your 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. Each property should be declared with its data type and name, and you can also define getters and setters for these properties if required.

public class AccountWrapper {

    public Account account { get; set; }

    public Boolean isSelected { get; set; }

    public List<Contact> relatedContacts { get; set; }

}

In this example, account holds an Account object, isSelected is a Boolean value, and relatedContacts holds a list of Contact objects.

3. Create Constructors to Initialize the Class

Constructors are special methods used to initialize a class. When you create an instance of the class, the constructor is called automatically. The constructor should initialize the properties defined in the class. For the AccountWrapper class, the constructor could look like this:

public class AccountWrapper {

    public Account account { get; set; }

    public Boolean isSelected { get; set; }

    public List<Contact> relatedContacts { get; set; }

    public AccountWrapper(Account acc) {

        this.account = acc;

        this.isSelected = false;

        this.relatedContacts = new List<Contact>();

    }

}

This constructor takes an Account object as an argument and initializes the account property. It also initializes isSelected as false and relatedContacts as an empty list.

4. Implement Methods to Manipulate or Process the Data

You can also define methods in your wrapper class to manipulate or process the data. For instance, you might want a method to add a Contact to the relatedContacts list:

public class AccountWrapper {

    public Account account { get; set; }

    public Boolean isSelected { get; set; }

    public List<Contact> relatedContacts { get; set; }

    public AccountWrapper(Account acc) {

        this.account = acc;

        this.isSelected = false;

        this.relatedContacts = new List<Contact>();

    }

    public void addContact(Contact con) {

        this.relatedContacts.add(con);

    }

}

5. Use the Wrapper Class in Your Apex Controller or Visualforce Page

Finally, you can use the wrapper class in your Apex controller or Visualforce page. You can create instances of the wrapper class, call its methods, and access its properties. For example, in an Apex controller, you might create a list of AccountWrapper instances to display on a Visualforce page:

public class AccountController {

    public List<AccountWrapper> wrapperList { get; set; }

    public AccountController() {

        wrapperList = new List<AccountWrapper>();

        for (Account acc : [SELECT Id, Name FROM Account]) {

            wrapperList.add(new AccountWrapper(acc));

        }

Common Properties and Methods of Wrapper Classes

Wrapper classes can have a variety of properties and methods, depending on the intended use case. Some common properties include:

  1. ‘isSelected’ – A boolean property to determine if the record is selected.
  2. ‘object’ – A property to hold the standard or custom object.
  3. ‘relatedData’ – A property to hold related data, such as child records or related lists.

Common methods might include:

  1. ‘calculate()’ – A method to perform calculations on the data.
  2. ‘validate()’ – A method to validate the data before saving or processing.
  3. ‘sort()’ – A method to sort the records based on specific criteria.

What Are the Advantages of a Wrapper Class?

  1. Improved Code Maintainability: Wrapper classes enhance code maintainability by encapsulating related data and operations in one place. As a result, the code becomes more straightforward to comprehend and adjust when necessary.
  2. Enhanced User Interface Control: Wrapper classes allow developers to design custom user interfaces in Visualforce or Lightning Web Components by controlling the display and manipulation of data elements.
  3. Better Data Organization: By grouping related data together in a single entity, wrapper classes promote better data organization and reduce complexity in the application.
  4. Scalability and Reusability: Wrapper classes can be used across multiple components or projects, making them highly reusable and scalable.

Salesforce Training Program India

Common Use Cases of a Wrapper Class

1. Displaying Related Data in a Visualforce Page

Wrapper classes are particularly useful when displaying related data, such as parent and child records, in a single Visualforce page. By encapsulating the parent and child records within a wrapper class, developers can easily manage and display the data in a structured format.

For example, consider a scenario where you want to display an account’s details along with its related contacts and opportunities. You can create a wrapper class that includes the account, its contacts, and its opportunities as properties.

public class AccountWrapper {

    public Account account { get; set; }

    public List<Contact> relatedContacts { get; set; }

    public List<Opportunity> relatedOpportunities { get; set; }

    public AccountWrapper(Account acc, List<Contact> contacts, List<Opportunity> opportunities) {

        this.account = acc;

        this.relatedContacts = contacts;

        this.relatedOpportunities = opportunities;

    }

}

Then, in your Apex controller, you can query the related data and create a list of AccountWrapper instances to be displayed on the Visualforce page. This simplifies the process for users to access and engage with the associated data.

2. Managing Multiple Selections in a List

Wrapper classes are ideal for managing multiple selections in a list or table, enabling users to select or deselect records and perform bulk actions. By incorporating a boolean isSelected property in the wrapper class, developers can track the selection status of each record.

For instance, suppose you want to create a table of opportunities that users can select for bulk updates. You can create a wrapper class that encapsulates the opportunity and its selection status:

public class OpportunityWrapper {

    public Boolean isSelected { get; set; }

    public Opportunity opportunity { get; set; }

    public OpportunityWrapper(Opportunity opp) {

        this.isSelected = false;

        this.opportunity = opp;

    }

}

In your Visualforce page, you can create a table with a checkbox for each opportunity to enable selection or deselection. You can then use the isSelected property in your Apex controller to perform bulk actions on the selected opportunities.

3. Complex Business Logic Implementation

Wrapper classes assist in implementing complex business logic by allowing developers to group related data and operations together, making it easier to process and manipulate the data as needed. This promotes better organization and readability in the code.

For example, imagine you need to process a set of order items with various discounts and tax rules based on product categories. You can create a wrapper class that encapsulates the ordered item, its product, and the associated discounts and tax rules:

public class OrderItemWrapper {

    public OrderItem orderItem { get; set; }

    public Product2 product { get; set; }

    public List<Discount__c> discounts { get; set; }

    public List<TaxRule__c> taxRules { get; set; }

    public OrderItemWrapper(OrderItem item, Product2 prod, List<Discount__c> disc, List<TaxRule__c> rules) {

        this.orderItem = item;

        this.product = prod;

        this.discounts = disc;

        this.taxRules = rules;

    }

}

You can then implement methods within the wrapper class or your Apex controller to calculate the final price, apply discounts, and compute taxes based on the encapsulated data. Consequently, the code is more accessible to understand, maintain, and adapt as business needs evolve.

Summing Up

Wrapper class in Salesforce is a powerful tool for developers to manage complex data structures, user interfaces, and business logic. By leveraging the benefits of wrapper classes, developers can create more maintainable, scalable, and reusable code, leading to a better overall application experience for users.

Get certified as a Salesforce Developer with saasguru by enrolling in our intensive Salesforce Platform Developer 1 training program with capstone projects.

You can also check out our self-learn Platform Developer 1 Certification course – get a personalized study plan, free mock exams, quizzes, flashcards and much more.

As you continue to explore the Salesforce ecosystem, consider joining the saasguru community on Slack to connect with like-minded professionals, share your experiences, and learn from others. Don’t miss out – join the community today!

Frequently Asked Questions (FAQs)

1. What is a Wrapper Class in Salesforce?

In Salesforce, a wrapper class is a custom class defined by the user that encapsulates multiple objects and data types into a single unit. This class can include standard or custom objects, primitive data types, and other classes. It is primarily used for combining data that doesn’t naturally exist together in a standard Salesforce object or for adding additional attributes to existing objects for display or manipulation in Visualforce pages or Lightning components.

2. Why Do We Use Wrapper Class in Salesforce?

Wrapper classes are used in Salesforce to create more complex data structures that are not directly supported by the standard Salesforce object model. They enable developers to combine different data elements together, such as records from multiple objects, and add custom fields or properties. This is particularly useful for custom user interface development, like displaying a list of records with checkboxes in a Visualforce page or a Lightning component, and for implementing complex business logic that spans multiple objects.

3. When to Use Wrapper Class in Salesforce?

Wrapper classes should be used when you need to represent complex data structures or relationships that aren’t natively supported by Salesforce objects. Common scenarios include:

  • When displaying data from multiple objects in a single page or component.
  • For managing state in a Visualforce page or Lightning component, such as tracking which records are selected in a list.
  • When you need to add additional transient properties to an object for the purposes of a specific process or UI, which don’t need to be stored in the database.

4. What is the Difference Between Primitive Type and Wrapper Class in Salesforce?

Primitive types in Salesforce are basic data types like Integer, String, Boolean, etc., which hold a single value. A wrapper class, on the other hand, is a user-defined complex type that can encapsulate multiple primitive types, objects, and collections. Unlike primitive types, wrapper classes can be customized to hold a combination of various data types and can include methods to perform operations on this data.

5. How Do You Increase Code Coverage for a Wrapper Class in Salesforce?

To increase code coverage for a wrapper class in Salesforce, ensure that your test classes thoroughly test all the methods and properties of the wrapper class. This includes:

  • Creating instances of the wrapper class in test methods.
  • Setting and getting all the properties to ensure they are covered.
  • Calling any custom methods defined in the wrapper class and asserting their outcomes.
  • Simulating different scenarios and edge cases that the wrapper class might encounter in actual usage.

The goal is to validate that the wrapper class behaves as expected and to meet Salesforce’s code coverage requirements, which is a minimum of 75% coverage for deployment.

Table of Contents

Subscribe & Get Closer to Your Salesforce Dream Career!

Get tips from accomplished Salesforce professionals delivered directly to your inbox.

Looking for Career Upgrade?

Book a free counselling session with our Course Advisor.

By providing your contact details, you agree to our Terms of use & Privacy Policy

Unlock Your AI -Powered Assistant

Gain Exclusive Access to Your Salesforce Copilot

Related Articles

Dreamforce 2024: Your Complete Guide to What To Expect

Join Dreamforce 2024 in San Francisco for keynotes, sessions, and networking with over 180,000 Salesforce enthusiasts. Read now!

Salesforce June 2024 Updates by saasguru

Discover Salesforce’s June 2024 highlights: AI innovations, global expansions, sustainability investments, and industry recognition. Read now!

Salesforce B2B Solution Architect Practice Exam Questions and Answers 2024

Ace your B2B Solution Architect certification exam with our comprehensive practice questions and answers. Read now!