10

Are Parent Fields supported in lightning Datatable?

I'm trying to display Account Name with Contact information, but it seems parent fields are not supported in lightning datatable.

Component:

<aura:component controller="PagingSortingController">
    <aura:attribute name="mydata" type="Object"/>
    <aura:attribute name="mycolumns" type="List"/>
    <aura:handler name="init" value="{! this }" action="{! c.init }"/>
    <lightning:datatable data="{! v.mydata }" 
        columns="{! v.mycolumns }" 
        keyField="con.id"
        onrowselection="{! c.getSelectedName }"/>
</aura:component>

Controller:

({
    init: function (cmp, event, helper) {
    cmp.set('v.mycolumns', [
                {label: 'Contact Name', fieldName: 'Name', type: 'text'},
                {label: 'Phone', fieldName: 'Phone', type: 'phone'},
                {label: 'Email', fieldName: 'Email', type: 'email'},
                {label: 'Account Name', fieldName: 'Account.Name', type: 'text'}
            ]);
        helper.getData(cmp);
    }

})

Helper:

({
    getData : function(cmp) {
        var action = cmp.get('c.getContacts');
        action.setCallback(this, $A.getCallback(function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                cmp.set('v.mydata', response.getReturnValue());
            } else if (state === "ERROR") {
                var errors = response.getError();
                console.error(errors);
            }
        }));
        $A.enqueueAction(action);
    }
})

Apex Controller:

@AuraEnabled
    public static List<Contact> getContacts() {
        List<Contact> contacts = 
                [SELECT Id, Name, Phone, Email,Account.Name FROM Contact];
        return contacts;
    }
0

1 Answer 1

20

Doing the "flattening" as mentioned in Winter 18 <lightning:datatable> does not get values from a parent record can be simple if everything is hard coded:

        if (state === "SUCCESS") {
            var rows = response.getReturnValue();
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (row.Account) row.AccountName = row.Account.Name;
            }
            cmp.set('v.mydata', rows);

and then replace "Account.Name' with "AccountName" in your column data.

1
  • Thanks @Keith C it works like a charm
    – Pavan tej
    Jul 7, 2022 at 17:49

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