WrapperClass in Lightning

Posted on Updated on

Hi All,

In my series of Salesforce1 Lightning posts today you will know, how to use Wrapper Class in Lightning?
There is a little difference when using Wrapper Class in Salesforce.com and Lightning.

When complete it will look like this :

pic1

Change “bklightning” namespace to “YourNamespace”.

If you need complete code you can download from github.

Let’s walk through code:

WClassController.apxc
public class WClassController{
    
    @AuraEnabled
    public static List<WrapperClass> getAccounts() {
        List<WrapperClass> wcList = new List<WrapperClass>();
        List<Account> accList = [SELECT Name,Active__c, (SELECT Name FROM contacts) FROM Account];
        
        if(accList.size() > 0){
            for(Account acct : accList){
                if(acct.contacts.size() > 0){
                    WrapperClass wc = new WrapperClass();
                    wc.count = acct.contacts.size();
                    wc.acc = acct;
                    wcList.add(wc);
                }
            }
        }
        
        return wcList;
    }
    
}

First off all you will notice that each method has an @AuraEnabled keyword.
Any method that you want to be visible to the Aura view components will need this keyword.

In WClassController.apxc controller getAccounts() method contains a WrapperClass List but you can not see WrapperClass in WClassController.apxc class.
Actually I have created a separate class for WrapperClass with the name WrapperClass.apxc.
Why I did so?
1)Because Apex Controller/Class Types cannot be marked as AuraEnabled.
2)If you create an inner class you can not access this class in Lightning components.
3)If you want to access members of Apex Controller through Object you need to marked them with @AuraEnabled keyword.

There is no difference when accessing the members of WrapperClass.

WrapperClass.apxc
public class WrapperClass{
    @AuraEnabled
    public Integer count;
    
    @AuraEnabled
    public Account acc;
    
}

In WrapperClass.apxc class you can see that I have marked each member of this class with @AuraEnabled keyword.
If you do not mark them @AuraEnabled,you will not be able to access them in Lightning Component.

WrapperClassComponent.cmp
<aura:component controller="bklightning.WClassController">
	<aura:attribute name="accounts" type="bklightning.WrapperClass[]"/>
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <div>
        <table class="table table-bordered">
            <thead>
            	<tr>
                	<th><b>Name</b></th>
                    <th><b>Contact</b></th>
                    <th><b>Active</b></th>
                </tr>
            </thead>
            <tbody>
                <aura:iteration items="{!v.accounts}" var="account">
                    <tr>
                        <td>{!account.acc.Name}</td>
                        <td>{!account.count}</td>
                        <td>{!account.acc.bklightning__Active__c}</td>
                    </tr>
                </aura:iteration>
            </tbody>
        </table>
    </div>
</aura:component>

In WrapperClassComponent.cmp component you can see I have used WrapperClass.apxc as “aura:attribute” Type.
To access an array/list of wrapper class you define “aura:attribute” Type like type=”bklightning.WrapperClass[]”.

So that’s it.Hope it will help you.

15 thoughts on “WrapperClass in Lightning

    […] just updated my previous post with SLDS you can find the orignal post here, you can use Apex class from this […]

    Like

    Lochana said:
    May 11, 2016 at 10:25 am

    I have used wrapper class and it is fetching data correctly for aura output fields. But when I use aura:inputDate, I am facing some isuues.
    It displays date, but not able to change the date. When I set the new date, the it gets replaced with old date.
    I have set displayDatepicker as true.

    Thanks,
    Lochana

    Like

      balkishankachawa responded:
      May 11, 2016 at 11:50 am

      I can’t give you any solution before seeing your code.

      Like

        Lochana said:
        May 16, 2016 at 6:23 am

        Thanks for your reply!!

        Please find my code below:
        Component:

        Name
        Birthdate
        Account Name

        {!contact.objCon.Name}

        <!—->

        {!contact.objCon.Account.Name}

        Controller:
        ({
        myAction : function(component, event, helper) {
        var action = component.get(“c.getAllContacts”);
        action.setCallback(this, function(data) {
        component.set(“v.contacts”, data.getReturnValue());
        });
        $A.enqueueAction(action);
        }
        })

        Apex Controller:

        public class LightningContactController {
        @AuraEnabled
        public static List getContacts() {
        return [Select Id, Name, Birthdate, AccountId, Account.Name, Email, Title, Phone
        From Contact order by LastModifiedDate desc
        limit 10];
        }

        @AuraEnabled
        public static list getAllContacts(){
        list lstC = new list();
        for(Contact objC : [Select Id, Name, Birthdate, AccountId, Account.Name, Email, Title, Phone From Contact])
        {
        lstC.add(new contactWrapper(true,objC));
        }
        return lstC;
        }

        public class contactWrapper {
        @AuraEnabled
        public boolean blnActive;
        @AuraEnabled
        public Contact objCon;

        public contactWrapper(boolean blnA, Contact objC){
        blnActive = blnA;
        objCon= objC;
        }
        }
        }

        Thanks,
        Lochana

        Like

        Lochana said:
        May 16, 2016 at 6:25 am

        In previous comment, component code is not clear. Please find the code for component below:

        Name
        Birthdate
        Account Name

        {!contact.objCon.Name}

        <!—->

        {!contact.objCon.Account.Name}

        Like

        Lochana said:
        May 16, 2016 at 6:28 am

        Name
        Birthdate
        Account Name

        {!contact.objCon.Name}

        <!—->

        {!contact.objCon.Account.Name}

        Like

        Lochana said:
        May 16, 2016 at 6:36 am

        Not able to post component, it is displaying in above format only.
        Request you to please delete the above two unwanted commnets.

        I have used the wrappper the way you mentioned in the above post only.

        Thanks,
        Lochana

        Like

    Lochana Rajput said:
    May 18, 2016 at 5:54 am

    My issue is resolved by changing the wrapper class structure.
    I added new member for Date in the wrapper.
    Now it is working as expected 🙂

    Before
    public class TPSWrapper
    {
    @AuraEnabled
    public Contact objCon;

    @AuraEnabled
    public String moduleName;

    public TPSWrapper(Contact objTPS, String moduleName){
    this.objTPS = objTPS;
    this.moduleName = moduleName;
    }

    }

    After:
    public class TPSWrapper
    {
    @AuraEnabled
    public Contact objCon;

    @AuraEnabled
    public String moduleName;

    @AuraEnabled
    public Date assessmentDate;

    public TPSWrapper(Contact objTPS, String moduleName, Date assessmentDate){
    this.objTPS = objTPS;
    this.moduleName = moduleName;
    this.assessmentDate = assessmentDate;
    }

    }

    Like

    Lochana Rajput said:
    May 18, 2016 at 5:57 am

    My issue is resolved by adding new member in wrapper class for Date.
    Now it is working as expected 🙂

    Before
    public class TPSWrapper
    {
    @AuraEnabled
    public Contact objCon;

    @AuraEnabled
    public String moduleName;

    public TPSWrapper(Contact objTPS, String moduleName){
    this.objTPS = objTPS;
    this.moduleName = moduleName;

    }

    }

    After:
    public class TPSWrapper
    {
    @AuraEnabled
    public Contact objCon;

    @AuraEnabled
    public String moduleName;

    @AuraEnabled
    public Date assessmentDate;

    public TPSWrapper(Contact objTPS, String moduleName, Date assessmentDate){
    this.objTPS = objTPS;
    this.moduleName = moduleName;
    this.assessmentDate = assessmentDate;
    }

    }

    Like

    Srikanth said:
    June 17, 2016 at 11:16 am

    Hello,

    I am using wrapper class to display 2 picklists and a text box to display in lightning component. Every time user clicks on add criteria button, a new item(2 picklist and 1 text box) will be add to wrapper class list and if user clicks on reset button list will become empty.

    ISSUE : MY RESET FUNCTIONALITY IS NOT WORKING

    //My wrapper class
    class FilterCriteria{
    @Auraenabled
    string fieldVal // holds the 1st picklist value from UI;
    @Auraenabled
    string operVal;//holds the 1st picklist value from UI;
    @Auraenabled
    string textVal;
    }

    //My lightning comp snippet
    //creas is list of wrapper class items.

    //JS Script
    resetAll : function(component,event,helper)
    {
    component.set(“v.creas”, []); // This is not updating the UI
    },

    I have reset functionality. If i click on reset button, list is getting empty..but in UI it still have same no of records.
    This happens after Salesforce Api 37.0 update.

    One of my finding was, if i include wrapper class variable in VALUE attribute of input select it is not working, if i give some attribute value,it is working as mentioned below

    WRAPPER CLASS variable crea.fieldVal BREAKING reset functionality(UI is not updating)
    ……………….

    if value attibute of select list is a attribute,it IS WORKING(UI updating perfectly)..
    ……………….

    As i mentioned..this small change making the reset functionality(every other functionality) to work.
    but i need wrapper class variable to hold the value of selected option,but wrapper class variable is not supporting now(Above mentioned worked till last week,till the Api 37.0 update).

    Can any body give some suggestion to resolve this..
    Thanks in advance!!

    Like

    Srikanth said:
    June 17, 2016 at 6:22 pm

    Hello,

    I am using wrapper class to display 2 picklists and a text box to display. Every time user clicks on add criteria a new item will be add to wrapper class list.

    //Wrapper class
    class FilterCriteria{
    @Auraenabled
    string fieldVal // holds the 1st picklist value from UI;
    @Auraenabled
    string operVal;//holds the 1st picklist value from UI;
    @Auraenabled
    string textVal;
    }

    my lightning comp snippet. Below code is just pseudo code for better understanding
    creas is list of wrapper class items.

    //JS Script
    resetAll : function(component,event,helper)
    {
    component.set(“v.creas”, []);
    },

    I have reset functionality. If i click on reset button, list is getting empty(log shows it)..but in UI it still have same list(If it has 2 criterias added,on click of reset it is supposed to be zero,but it is still 2).
    This happens after Salesforce Api 37.0 update.

    One of my finding is, If i include wrapper class variable in input select value attribute it is not working, if i give some attribute value,it is working

    WRAPPER CLASS variable crea.fieldVal is BREAKING the remove and reset functionality, if this wrapper class variable is removed or replaced with normal attribute it is working fine.
    ……………….

    if value attribute of select list is a attribute,All functionalities are WORKING fine..
    ……………….

    As i mentioned..this small change making the reset,remove functionality(every other functionality) to work.
    but i need wrapper class variable to hold the value of selected option,unfortunately wrapper class variable is not supporting now(This worked till last work).

    Can any body please suggest a resolution for this..
    Thanks in advance!!

    Like

      Lochana Rajput said:
      October 7, 2016 at 8:47 am

      Hi Srikanth,
      Did you resolv this issue?

      Like

    Shambo Ray said:
    October 16, 2017 at 5:39 pm

    HI Balkrishnan/All,
    what may be the cause of below scenario:

    there is a httpcallout in the server side controller and response is coming to the server side controller i.e json and i have converted by deserializing the json to a wrapper class and it’s converted successfully.But when I am calling the serverside aura enabled method from client side controller by c.getmethodname the response is coming,state is coming as ‘SUCCESS’ and tyre of response coming as object i.e correct and it has many records but when i am putiing the response to an array it’s showing nothing like array{}..
    what may be the cause..

    If any doubts in my question I can attach the code…

    Like

Leave a Reply to Lochana Rajput Cancel reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s