0

I have a Wrapper class, which I need to instantiate in my Aura Controller. I'm not able to understand how can I instantiate it in my controller

Wrapper Class:

public class CustomWrapper {
    
    @AuraEnabled
    public Account acc {get;set;}
    @AuraEnabled
    public List<Contact> conList{get;set;}
    
    public CustomWrapper(){
        acc = new Account();
        conList = new List<Contact>();
    }
    
}

Component:

<aura:attribute name="wrapper" type="CustomWrapper[]" default="[]"/>

Controller:

var RowItemList = component.get("v.wrapper");

1 Answer 1

0

You have already defaulted it to default="[]". So it is instantiated to a blank array.

Either you need to create object in the JS and again pass that to backend, or define your default as : I have written sobjectType property just to show an example, you can fill in your Account object property and that should work fine.

default='[{"conList":[{"sobjectType":"Contact","LastName":""}],"acc":{"sobjectType":"Account","Name":""}}]'/>

Which will make your attribute as :

<aura:attribute name="wrapper" type="CustomWrapper[]" default='[{"conList":[{"sobjectType":"Contact","LastName":""}],"acc":{"sobjectType":"Account","Name":""}}]'/>

Then when you do JSON.parse(cmp.get("v.wrapper")) you will get a object where you can fill in the value.

Or you can even create an enqueuaction to return your instantiated fields.

@AuraEnabled(Cacheable=true)
public static List<CustomWrapper> instantiateCW() {
    List<CustomWrapper> lstCustomWrappers = new List<CustomWrapper>();
    lstCustomWrappers.add(new CustomWrapper());
    return lstCustomWrappers;
}

and in your doInit do this:

let action = cmp.get('c.instantiateCW');
action.setCallback(this,function(response){
    var state = response.getState();
    if (state === "SUCCESS") {
        cmp.set('v.wrapper', response.getReturnValue());
    }
});
$A.enqueueAction(action);

Issue in this is it eats up your enqueue action queue and moreover you will have to be careful in using the v.wrapper attribute as it will be set in callback which means you will have to write your code in such a way that whereever you are using v.wrapper it should be called after action is finished.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .