html code

Generating and populating an Apex wrapper

In Apex, being a statically typed language, you are typically required to choose a single object type per list when iterating. However, there are situations where you might want to iterate over a collection that contains multiple standard and custom objects together. In such cases, you can use a “wrapper class” to collectively encapsulate those objects.

A wrapper class is a custom class that serves as a container for multiple objects of different types. It allows you to group related data together and work with them more easily.

For example, let’s consider a scenario where you have an inner wrapper class called “MyWrapper” inside the “CustomWrapperController” class. This wrapper class contains two member variables of type “Contact” and “Opportunity.”

By populating data into the member variables of the outer class (CustomWrapperController) inside its constructor, you can use the same List type member variable in a Visualforce page or Lightning Component to display the data in an aesthetically appealing manner.

Below is an example of a wrapper class that includes two objects, Contact and Opportunity:

public with sharing class CustomWrapperController {

    public class MyWrapper {
        public Contact contactObj { get; set; }
        public Opportunity opportunityObj { get; set; }

        public MyWrapper(Contact contact, Opportunity opportunity) {
            this.contactObj = contact;
            this.opportunityObj = opportunity;
        }
    }

    public List<MyWrapper> myWrapperList { get; set; }

    public CustomWrapperController() {
        myWrapperList = new List<MyWrapper>();
        
        // Assuming you have retrieved some Contact and Opportunity records
        // from your data source, you can populate them into the wrapper.
        List<Contact> contactList = [SELECT Id, Name, Email FROM Contact LIMIT 5];
        List<Opportunity> opportunityList = [SELECT Id, Name, Amount FROM Opportunity LIMIT 5];
        
        // Matching contacts and opportunities are combined into the wrapper
        for (Integer i = 0; i < 5; i++) {
            MyWrapper wrapper = new MyWrapper(contactList[i], opportunityList[i]);
            myWrapperList.add(wrapper);
        }
    }

In the above example, the MyWrapper class encapsulates both a Contact object and an Opportunity object. The CustomWrapperController populates the data in the myWrapperList member variable, which can be accessed in the Visualforce page or Lightning Component to display the information in a more organized manner.