Wrapper Class In Apex
A wrapper is a class, an abstract data type that contains different objects or collections of objects as its members.
A wrapper class is a custom object defined by the programmer wherein he defines the wrapper class properties. Its similar to the custom object of Salesforce. In custom object of Salesforce, we have different fields of different data types. Similarly wrapper class is a custom class which has different data types or properties as per requirement. We can wrap different object types or any other data types in a wrapper class.
Its instances could be different data types:
- Primitive
- Collections
- sObjects
- Converting the JSON string into an object (and vice versa) is easily achieved using Wrapper Class.
- Wrapper Class helps to combine different types(datatype) of data.
For example:
public class AccountContactController{
public static AccountContactListWrapper getAccountWithContacts(String accId){
AccountContactListWrapper accConListWrapper = new AccountContactListWrapper();
List<Account> accountList = [SELECT Id, Name,
(SELECT Id, FirstName, LastName From Contacts)
FROM Account WHERE Id =: accId];
if(!accountList.isEmpty()){
accConListWrapper.accountRecord = accountList[0];
accConListWrapper.accContactList = accountList[0].Contacts;
}
return accWrapper;
}
public class AccountContactListWrapper{
public Account accountRecord{get;set;}
public List<Contact> accContactList{get;set;}
}
}
Comments
Post a Comment