Introduction

As this LWC is very similar to the previous one, review it if you haven’t already: LWC Datatable Inline with UI API (datatableInlineEditWithUiApi), to get the complete picture of it.

As in the previous LWC the main concepts included in this recipe are:

but instead of using an UI API function to update the data, it uses an Apex one.

<aside> 📂 Find this LWC in this folder: force-app\\main\\default\\lwc\\datatableInlineEditWithApex

</aside>

I prefer this LWC over the previous one, because it is more versatile on checking the data that the backend will require, as before executing the update contactsForUpdate all checks required can be executed.

Apex function used

The Apex function that is used, receives a List<contact> that should be updated. For this reason, after checking that the current user has access to this operation, the updatedatabase operation that we all know.

@AuraEnabled
public static void updateContacts(List<Contact> contactsForUpdate) {
    // Make sure we can update the database before trying to update
    if (!Schema.sObjectType.Contact.isUpdateable()) {
        throw new SecurityException(
            'Insufficient permissions to update contacts'
        );
    }
    **update contactsForUpdate;**
}

How is this function invoked? It is called using an async call passing the event.detail.draftValueswith no conversion required (this is the magic):

...
async handleSave(event) {
  const updatedFields = event.detail.draftValues;

  // Clear all datatable draft values
  this.draftValues = [];

  try {
      // Pass edited fields to the updateContacts Apex controller
      await updateContacts({ contactsForUpdate: updatedFields });
...

In any case, success or error a toast will be displayed.

Next recipe

LWC Datatable Custom Data Type (datatableCustomDataType)

Feedback?

Did you find an issue/mistake? You don’t like something? Do you have external content that I should link to improve the learning process? Did you find it helpful? Any of those are super valuable to me. So, please write me at [email protected], and promise to answer.

<aside> ↗️ Jump to the main page: The LWC Recipes Cookbook

</aside>