Salesforce Menu

Wrapper Classes in Salesforce

A wrapper class in apex is a custom apex class which consists of data structures and variables or a collection of these said variables as properties inside of it.
Wrapper classes are generally used by developers, and they define all the properties inside of a wrapper class. Just like standard and custom objects have fields which behave as properties, wrapper classes also have variables which behave as properties.
A wrapper class can consist of a combination of primitive and non-primitive data types, like :

public class Wrapper
	public String text;
	public list accs;


A really common scenario for using wrapper classes is creating a class as per your requirement in order to display it on a visualforce page. Let’s say we want to show a list of Accounts with a checkbox next to each of the records to allow selection.
So we will need a wrapper class with an Sobject property for the Account object and a Boolean property for the checkbox.

public class AccountWrapper
	public Account acc {get;set;}	
      public Boolean selected {get;set;}

This wrapper class can be used in our apex controller to fill data and display it on a visualforce page :

public class VFController
	public list accs{get;set;}
	public VFController()
		accs = new list();

		for(Account ac : [SELECT Id,Name FROM Account])
			AccountWrapper acW = new AccountWrapper();
			acW.acc = ac;
			acW.selected = false;


And here is the visualforce page to display this :


Select Account Id Account Name
{!wrap.acc.Id} {!wrap.acc.Name}

Output :

Subscribe Now