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](https://imgs.cloudjournal.co/2019/10/datatable-result-1024x253.png)
Apex
Create a new apex file – MyContactListController.cls.
- It retrieves Contact records with required fields.
- The fields are Id, Name, Email. Phone.
Info
Can pick other fields from Contact object. Depend on the requirements.
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
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
Info
extends="force:slds"
attribute if the application needs to use SLDS style, it requires to define extends attribute.
attribute if the application needs to use SLDS style, it requires to define extends attribute.