Lightning Web Component

Lightning Datatable Inline Edit

Inline Editing for a Lightning Datatable in LWC will save users time by avoiding manual updates going to the actual record.

It empowers them to make real-time data updates effortlessly, leading to increased productivity, improved data accuracy, and a more user-friendly interface.

Lightning Datatable Inline Edit Example

Lightning Datatable Inline Edit Example

Let's create an example step by step so you can follow it easily.

1. Lightning Datatable Declaration

First, let's declare the lightning-datatable on the HTML of your component. You must include these properties that will be helpful later:

<template>
    <lightning-datatable
        key-field="Id"
        data={contacts.data}
        columns={columns}
        onsave={handleSave}
        draft-values={draftValues}
    ></lightning-datatable>
</template>

2. Importing the Methods

The first step in the Javascript file is importing the methods that you require to use to make it work:

import { LightningElement, wire } from "lwc";
import { refreshApex } from "@salesforce/apex";
import { updateRecord } from "lightning/uiRecordApi";
import { ShowToastEvent } from "lightning/platformShowToastEvent";

import getContacts from "@salesforce/apex/GetAllContacts.getContacts";

3. Declare Columns and Get Data

Then you need to do the basics of a lightning datatable, declare the columns, and get the data from the Apex Controller.

import { LightningElement, wire } from "lwc";
import { refreshApex } from "@salesforce/apex";
import { updateRecord } from "lightning/uiRecordApi";
import { ShowToastEvent } from "lightning/platformShowToastEvent";

import getContacts from "@salesforce/apex/GetAllContacts.getContacts";

const COLS = [
  {
    label: "First Name",
    fieldName: "FirstName",
    editable: true,
  },
  {
    label: "Last Name",
    fieldName: "LastName",
    editable: true,
  },
  {
    label: "Email",
    fieldName: "Email",
    type: "email",
    editable: true,
  },
];

export default class LightningDatatableInlineEdit extends LightningElement {
    columns = COLS;
    draftValues = [];

    @wire(getContacts)
    contacts;

}

4. Handle the Record's Save

Once you have everything in place, you can start saving the records in Salesforce. As you can see, there is no need to create an additional Apex Method to store the records since the updateRecord method will be in charge.

On the handleSave function, we will transform the data modified by the user to be accepted by updateRecord, save it into Salesforce, and then show an alert message if the records were stored successfully or not.

import { LightningElement, wire } from "lwc";
import { refreshApex } from "@salesforce/apex";
import { updateRecord } from "lightning/uiRecordApi";
import { ShowToastEvent } from "lightning/platformShowToastEvent";

import getContacts from "@salesforce/apex/GetAllContacts.getContacts";

const COLS = [
  {
    label: "First Name",
    fieldName: "FirstName",
    editable: true,
  },
  {
    label: "Last Name",
    fieldName: "LastName",
    editable: true,
  },
  {
    label: "Email",
    fieldName: "Email",
    type: "email",
    editable: true,
  },
];

export default class LightningDatatableInlineEdit extends LightningElement {
    columns = COLS;
    draftValues = [];

    @wire(getContacts)
    contacts;

    async handleSave(event) {
        // TRANSFORM DATA MODIFIED BY THE USER
        const records = event.detail.draftValues.slice().map((draftValue) => {
            const fields = Object.assign({}, draftValue);
            return { fields };
        });
        // console.log(records) -> [{"fields":{"FirstName":"Rose","Id":"003Dn000009zbZOIAY"}}]

        try {
            // SAVE RECORDS USING updateRecord
            const recordUpdatePromises = records.map((record) => updateRecord(record));
            await Promise.all(recordUpdatePromises);
            
            this.showMessage("Success", "The Contacts has been updated!", "success");
            await refreshApex(this.contacts);
        } catch (error) {
            this.showMessage("Error", error.body.message, "error");
        } finally{
            this.draftValues = [];
        }
    }

    // SHOW MESSAGE
    showMessage(title, message, variant){
        this.dispatchEvent(
            new ShowToastEvent({
            title: title,
            message: message,
            variant: variant,
            }),
        );
    }
}

This is the final result of the lightning datatable with inline edit:

Lightning Locker examples of you can not do on Lightning Components