[SalesForce] Lightning DataTable onCellChange

I would like to know if there is any way I can do autosave when I change a cell value in the Lightning:datatable.

I have gone through the doc https://developer.salesforce.com/docs/component-library/bundle/lightning:datatable/specification but there is not enough detail on the onCellChange method.

Best Answer

As you would expect onCellChange actions are fired when a table cell's value changes in an inline edit. There's a good example of using this feature here

So, here is the setup you do in the component. Note the draftValues are there because that's what onCellChange actions return on inline edits.

<aura:attribute name="draftValues" type="Object" default="[]"/>
<aura:attribute name="mydata" type="Object"/>
<aura:attribute name="mycolumns" type="List"/>
<aura:attribute name="errors" type="Object" default="[]"/>
<aura:attribute name="saveLocalStorage" type="Boolean" default="false"/>

<lightning:datatable
errors="{! v.errors }"
draftValues="{! v.draftValues }"
data="{! v.mydata }" 
columns="{! v.mycolumns }" 
keyField="Id"
onsave="{! c.handleSave }"
oncellchange="{! c.handleEditCellChange}"
oncancel="{! c.handleCancel }"
onrowaction="{! c.handleRowAction }"
/>

the controller is pretty basic. It just calls the handler method

 handleEditCellChange: function(cmp, event, helper) {
    helper.handleEditCell(cmp, event);
  },

The helper has a bunch going on:

handleEditCell: function (cmp, event) {
    var saveLocalStorage = cmp.get('v.saveLocalStorage');
    if (saveLocalStorage) {
        var atomicChange = event.getParam('draftValues');
        var atomicChanges = cmp.get('v.atomicChanges');
        atomicChanges.push(atomicChange);
        cmp.set('v.changeIndex', atomicChanges.length);

        var draftValues = this.getBuildedDraftValues(atomicChanges, atomicChanges.length);

        localStorage.setItem('demo-draft-values', JSON.stringify(atomicChanges));
    }

    if (cmp.get('v.autoSaveEnabled')) {
        this.saveChanges(cmp, draftValues);
    }
},