• #31481
    Forcetalks

    How can you edit your record from within the lightning:dataTable itself?

    How can you edit your record from within the lightning:dataTable itself?

     

    #31487
    Forcetalks

    Hello Shradha,

    #Summer18 release was a power-packed release and has a lot to offer. One of the features introduced is lightning is the editable lightning data table.

    Not sure how you can do this, no worries, this post is all about this. Follow this post and create your own editable lightning data table.

    Editable lightning:dataTable – Summer18 feature

    Thanks.

    #35136
    Salesforce | shariq shariq #1
    Forcetalks

    Hi,

    Try this –

    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: ‘Custom Field’, fieldName: ‘My_Custom_Field__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, My_Custom_Field__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.

    Hope this helps.

    #35347
    Salesforce | Parul Parul #2
    Forcetalks

    Hi

    Summer’18 offers a wide range of additions and enhancements to Lightning Components, including the ever-useful Base Components. Let’s walk through two examples: one is a brand new component which makes it easy to create a form related to a record and the other is an update to dataTable for editing data. Because Summer18 release was a power-packed release and has a lot to offer. One of the features introduced is lightning is the editable lightning data table.

     

    Thanks

     

Viewing 4 posts - 1 through 4 (of 4 total)

Please to reply to this topic.

CONTACT US

We're not around right now. But you can send us an email and we'll get back to you, asap.

Sending

About Us

Forcetalks is a Salesforce collaboration platform for coders & developers, geeks & nerds, consultants & business heads, admins & architects, managers & marketers and of course the business owners. A community where you can learn from, where you can contribute to. For you. For Salesforce. Read More...

Copyright 2019 Forcetalks. All Right Reserved.

Log in with your credentials

or    

Forgot your details?