Display List of Records Using DataTable in Lightning Component

By | October 30, 2019

Hi, In this scenario we have Shown how to display sObject data in dataTable format using Lightning Component…We can display data in dataTable using iteration or lightning datatable, but in this scenario we used lightning datatable….

Apex Controller

public class DisplayListofRecordsUsingDataTable {
    @AuraEnabled
    public static list<lead> fetchLeadRecords(){
        return [select LastName,Company,Status from Lead Order By createdDate DESC LIMIT 5];        
    }
}

Component : DisplayListofRecordsUsingDataTable

<aura:component controller="DisplayListofRecordsUsingDataTable">
    <aura:attribute name="mycolumn" type="Object[]"/>
    <aura:attribute type="Lead[]" name="leadList"/>
    <aura:handler name="init" value="{!this}" action="{!c.fetchLeads}"/>
    
    <lightning:datatable data="{!v.leadList }" 
                         columns="{!v.mycolumn }" 
                         keyField="id"
                         hideCheckboxColumn="false" />
</aura:component>

Js Controller

({        
     fetchLeads : function(component, event, helper) {
         component.set('v.mycolumn', [
             {label: 'LastName', fieldName: 'LastName', type: 'text'},
             {label: 'Company', fieldName: 'Company', type: 'Text'},
             {label: 'Status', fieldName: 'Status', type: 'text'}            
         ]);
         var action = component.get("c.fetchLeadRecords");
         action.setCallback(this, function(response){
             component.set("v.leadList", response.getReturnValue());
         });
         $A.enqueueAction(action);
     },
 })

Application

<aura:application extends="force:slds">
    <c:DisplayListofRecordsUsingDataTable/>
</aura:application>

Output

Leave a Reply

Your email address will not be published. Required fields are marked *