Data Table

Datatable for Aura Component

Introduction

This post provides an example of how to use basic lightning:datatable.

  • It fetches data when the page has loaded.
  • It displays data as a table and formatted according to the data type.

Result:

datatable-result

Apex

Create a new apex file – MyContactListController.cls.

  • It retrieves Contact records with required fields.
  • The fields are Id, Name, Email. Phone.

MyContactListController.cls


/* 
    ------------------------------------------------------------------------------
    class   MyContactListController  
    author: Kenny Soetjipto  
    ------------------------------------------------------------------------------    
*/
public with sharing class MyContactListController {   

    /* 
    ------------------------------------------------------------------------------
    Method:  getContacts
    purpose: Get contact records from fields: Id, Name, Email, Phone
    ------------------------------------------------------------------------------    
    */
    @AuraEnabled
    public static List getContacts() {
        return [SELECT Id, Name, Email, Phone FROM Contact];
    }

}

Lightning Component

Create new lightning component – MyContactList

MyContactList.cmp


<aura:component controller="MyContactListController">
    <!--Atttributes-->
    <aura:attribute name="Contacts" type="Contact" />
    <aura:attribute name="Columns" type="List" />
    
    <!--Handler-->
    <aura:handler name="init" value="{! this }" action="{!c.myAction}" />
    
    <!--datatable attributes: data, columns, hideCheckboxClumn-->
    <lightning:datatable data="{!v.Contacts}" columns="{!v.Columns}" keyField="" hideCheckboxColumn="true" />

</aura:component>

MyContactListController.js


({
	myAction : function(component, event, helper) {
        //set Columns attribute with Contact fields
        component.set("v.Columns", [
            {label:"Name", fieldName:"Name", type:"Name"},
            {label:"Email", fieldName:"Email", type:"Email"},
            {label:"Phone", fieldName:"Phone", type:"Phone"}
        ]);
        
        //invoke getContacts from Apex
        var action = component.get("c.getContacts");
        
        //setCallback()
        action.setCallback(this, function(data) {
            //set Contacts attribute with return value from Apex
            component.set("v.Contacts", data.getReturnValue());
        });
        //execute callback and assign action as parameter
        $A.enqueueAction(action);

	}
}) 

MyContactListApp

Create new lightning application – MyContactListApp

MyContactListApp.app


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

Leave a Reply