9

This question already has an answer here:

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;
    }

marked as duplicate by Himanshu, glls, Dave Humm, battery.cord, Santanu Boral Dec 4 '17 at 23:07

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

18

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.