Wrapper class in Apex

·

1 min read

Table of contents

No heading

No headings in the article.

A wrapper class is a class, a data structure, or an abstract data type that contains different objects or collections of objects as its members. A wrapper class is a custom object defined by a programmer wherein he defines the wrapper class properties.

public with sharing class AccountWrapperDemo {
    @AuraEnabled(cacheable=true)
    public static List<AccountWrapper> getAccountWithContact(){
        List<AccountWrapper> wrapList = new List<AccountWrapper>();
        List<Account> accList = [ SELECT Id,Name,
                                        (SELECT Id,FirstName, LastName FROM Contacts)
                                    FROM Account LIMIT 5];
        if(!accList.isEmpty()){
            for(Account acc : accList){
                wrapList.add(new AccountWrapper(acc, acc.Contacts));
            }
        }
        return wrapList;
    } 

    public class AccountWrapper {
        @AuraEnabled public Account accRecord{get;set;}
        @AuraEnabled public List<Contact> contactList{get;set;}
        public AccountWrapper(Account accRecord, List<Contact> contactList){
            this.accRecord = accRecord;
            this.contactList = contactList;
        }
    }
}

lwc-template:

<template>
    <lightning-card title="Wrapper Class Demo in LWC" icon-name="custom:custom63">
    <template if:true={wrapperList.data}>
        <lightning-accordion class="example-accordion" >
            <template for:each={wrapperList.data} for:item="wrap">
                <lightning-accordion-section name={wrap.accRecord.Id} label={wrap.accRecord.Name} key={wrap.accRecord.Id}>
                    <template for:each={wrap.contactList} for:item="contWrap">
                        <lightning-layout vertical-align="center" key={contWrap.Id}>
                            <li>
                                {contWrap.FirstName}
                                {contWrap.LastName}
                            </li>
                        </lightning-layout>
                    </template>
                </lightning-accordion-section>
            </template>
        </lightning-accordion>
    </template>
</lightning-card>
</template>