0

I am trying to display records from Contact Object in a Lightning Component in a datatable. Somehow the records are not getting displayed. Can someone please help where am I going wrong?

Apex Controller:

public with sharing class ContactController {
    @AuraEnabled
    public static List<Contact> getContacts(){
        return [Select Id, Name, Phone, Email From Contact];
    }
}

Lightning Component 'displayContacts':

<aura:component controller="ContactController" >
<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="Id"
        hideCheckboxColumn="true"/>

Component controller js:

({
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'},
    ]);
    helper.getData(cmp);
}

})

Component helper Js:

({
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);
}

})

Result: enter image description here

2

There is a case issue with your code:

cmp.set('v.myColumns',[
        {label: 'Contact Name', fieldName: 'Name', type:'text'},
        {label: 'Phone', fieldName: 'Phone', type:'phone'},
        {label: 'Email', fieldName: 'Email', type:'email'},
    ]);

fieldname => fieldName

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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