If you are working on lightning components and searching for the steps to add a data grid for any object inside the lightning component, this is the right place!

In this article, I will show the detailed steps to add a contacts data grid in the lightning component.


1. Create a component in the name 'poc' and add below-mentioned code in the poc.cmp file
   
<aura:component implements="flexipage:availableForAllPageTypes" controller="poc">
    <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"/>
</aura:component>


2. Add this code in 'poccontroller.js' - this is client-side 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'}
            ]);
        helper.getData(cmp);
    }
})


3. Code in 'pochelper.js' - client side 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);
    }
})


4. Add new apex class with name 'poc' and add below-mentioned code

public with sharing class poc {
    @AuraEnabled
    public static List<Contact> getContacts() {
        List<Contact> contacts =
                [SELECT Id, Name, Phone, Email FROM Contact];
        return contacts;
    }
}


Add this component to the page layout through the app builder console and test the changes.


In case if you want to understand all the steps in detail, please go through the below-mentioned video.





Post your comments/feedback/queries in the below comments section. Subscribe to my Youtube channel and get updated with salesforce tutorials - click here