Tuesday, January 28, 2020

lightning:dataTable 
  • Editable lightning:dataTable – Summer18 feature

Component – Markup of your component

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes"
                access="global"
                controller="AccountController">
    <aura:attribute name="data" type="Object"/>
    <aura:attribute name="columns" type="List"/>
    <aura:attribute name="recordId" type="String"/>
    <!-- This attribute will hold the update records from data table-->
    <aura:attribute name="updatedRecord" type="Object[]" />

    <aura:handler name="init" action="{!c.doInit}" value="{!this}"/>

    <!-- You must define keyField as 'Id' to save the record back in Salesforce
'onsave' attribute will executed when user clicks on save button -->
    <lightning:card title="Account Editable Datatable">
        <lightning:datatable
                             aura:id="accountDataTable"
                             columns="{! v.columns }"
                             data="{! v.data }"
                             keyField="Id"
                             onsave ="{!c.onSave}"
                             hideCheckboxColumn="true"
                             onrowaction="{! c.handleRowAction }" />
    </lightning:card>
</aura:component>
Client Controller – Handles event of your markup
({
    /*
     * This finction defined column header
     * and calls getAccounts helper method for column data
     * editable:'true' will make the column editable
     * */
doInit : function(component, event, helper) {        
        component.set('v.columns', [
            {label: 'Name', fieldName: 'Name', editable:'true', type: 'text'},
            {label: 'Phone', fieldName: 'Phone', editable:'true', type: 'phone'},
            {label: 'Rating', fieldName: 'Rating', editable:'true', type: 'text'},
            {label: 'Active', fieldName: 'Active__c', editable:'true', type: 'text'}
        ]);        
        helper.getAccounts(component, helper);
    },

    /*
     * This function is calling saveDataTable helper function
     * to save modified records
     * */
    onSave : function (component, event, helper) {
        helper.saveDataTable(component, event, helper);
    }
})
Client Helper – Handles server interaction and reusable code
({
    getAccounts : function(component, event, helper) {
        var action = component.get("c.getAccounts");
        action.setCallback(this,function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.data", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    },

    /*
     * This function get called when user clicks on Save button
     * user can get all modified records
     * and pass them back to server side controller
     * */
    saveDataTable : function(component, event, helper) {
        var editedRecords =  component.find("accountDataTable").get("v.draftValues");
        var totalRecordEdited = editedRecords.length;
        var action = component.get("c.updateAccounts");
        action.setParams({
            'editedAccountList' : editedRecords
        });
        action.setCallback(this,function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                //if update is successful
                if(response.getReturnValue() === true){
                    helper.showToast({
                        "title": "Record Update",
                        "type": "success",
                        "message": totalRecordEdited+" Account Records Updated"
                    });
                    helper.reloadDataTable();
                } else{ //if update got failed
                    helper.showToast({
                        "title": "Error!!",
                        "type": "error",
                        "message": "Error in update"
                    });
                }
            }
        });
        $A.enqueueAction(action);
    },

    /*
     * Show toast with provided params
     * */
    showToast : function(params){
        var toastEvent = $A.get("e.force:showToast");
        if(toastEvent){
            toastEvent.setParams(params);
            toastEvent.fire();
        } else{
            alert(params.message);
        }
    },

    /*
     * reload data table
     * */
    reloadDataTable : function(){
    var refreshEvent = $A.get("e.force:refreshView");
        if(refreshEvent){
            refreshEvent.fire();
        }
    },
})
Server Controller – Returns and update record
public class AccountController {
@AuraEnabled
    public static List<Account> getAccounts(){
        return [SELECT
               Id, Name, Phone, Rating, Active__c
               FROM Account LIMIT 200];
    }

    @AuraEnabled
    public static boolean updateAccounts(List<Account> editedAccountList){
        try{
            update editedAccountList;
            return true;
        } catch(Exception e){
            return false;
        }
    }
}
So this is how you can create your own editable lightning data table. Below are few considerations and facts about lightning:dataTable:
  • lightning:dataTable is not supported on mobile devices
  • The keyField attribute is required to hold unique row id. You should always define keyField=”Id” which means row id will be same as record id and it will make easier to update, view and edit records.
  • You component version needs to be at least on API version 43 for the editable data table. However if you are not using editable columns, then you can run data table from api version 41 onwards.