Salesforce Custom Data Table Inline Editing with LWC in 4 Easy Steps

Business Justification: Why Implement Salesforce custom data table inline editing?

Managing data effectively in Salesforce is crucial for ensuring productivity and maintaining data integrity. However, standard tools often fall short when it comes to bulk record updates or providing an efficient editing interface. Here’s why implementing a Salesforce Custom Data Table Inline Editing was necessary:

Challenges Faced:

  1. Time-Consuming Data Management:
    • Users were required to open and edit records individually, which was tedious and inefficient for bulk updates.
  2. Limited Standard Features:
    • The out-of-the-box lightning-datatable does not fully support inline editing with enhanced features, creating limitations for modern business needs.
  3. Data Entry Errors:
    • Manual edits across multiple records often led to inconsistent or incorrect data due to the lack of validation mechanisms during the process.
  4. Multiple Clicks and Page Loads:
    • The multi-screen process for record updates created a poor user experience and negatively impacted workflow speed.

How This Solution Addresses These Issues:

  1. Improved Productivity:
    • Inline editing allows users to modify multiple records directly from the data table, saving time and effort.
  2. Real-Time Validation:
    • Changes are validated instantly, ensuring that data remains consistent and error-free.
  3. User-Friendly Interface:
    • The modern LWC-based design provides a seamless experience with a focus on usability and efficiency.
  4. Bulk Record Updates Made Easy:
    • Multiple records and fields can be updated simultaneously, reducing redundancy and increasing operational speed.
  5. Reusability Across Pages:
    • The component can be deployed on various pages, such as Record Pages or App Pages, making it versatile and scalable for different use cases.

This custom solution not only enhances the Salesforce user experience but also aligns with modern data management needs, ensuring faster and more reliable business processes.

Step 1: Create the Apex Class for Data Handling

In this implementation, the Apex controller plays a critical role in handling data retrieval and updates between the LWC component and the Salesforce database. Here are the two primary methods used in the AccountControllerInlineEdit class:

Fetching Account Records (getAccounts)

  • Class declaration: Defines a public Apex class with with sharing, ensuring the class respects user permissions and sharing rules for secure data access.
public with sharing class AccountControllerInlineEdit
@AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
        return [SELECT Id, Name, Industry, Phone FROM Account LIMIT 10];
    }
  • This method retrieves 10 Account records with key fields (Id, Name, Industry, Phone).
  • @AuraEnabled(cacheable=true) allows the method to be called from the LWC and caches the data for better performance, reducing server calls.
  • Key Benefit: Faster data loading with reduced server traffic.

Updating Account Records (updateAccounts):

@AuraEnabled
    public static void updateAccounts(List<Account> accountsToUpdate) {
        update accountsToUpdate;
    }
  • This method updates multiple Account records in Salesforce based on the provided list.
  • @AuraEnabled makes the method available for LWC interactions, allowing bulk updates in a single server call.
  • Key Benefit: Efficient bulk data handling with minimal server interactions.

Step 2: Create the LWC Component Structure

In this step, we will create the necessary files for your Lightning Web Component (LWC) to function as a custom data table with inline editing.

accountsforDataTable.html

  • This file contains the structure of the data table and defines the UI elements.
<template>
    <lightning-card title="Accounts Data Table with Inline Editing">
        <lightning-datatable
            key-field="Id"
            data={accounts}
            columns={columns}
            draft-values={draftValues}
            onsave={handleSave}
            hide-checkbox-column="true">
        </lightning-datatable>
    </lightning-card>
</template> 
//Salesforce Custom Data Table Inline Editing
  • <lightning-card>: A Lightning Web Component wrapper for the table to create a card-like UI.

<lightning-datatable>:

  • key-field=”Id”: The field used as the unique identifier for each row (Account record).
  • data={accounts}: The accounts variable will hold the list of Account records retrieved from the Apex class.
  • columns={columns}: Specifies the column definitions, which will determine the columns shown in the table (e.g., Account Name, Industry, Phone).
  • draft-values={draftValues}: Holds the draft (modified) values when the user edits the data inline.
  • onsave={handleSave}: Calls the handleSave method in the JS file when the user saves their changes.
  • hide-checkbox-column=”true”: Hides the selection checkbox column (since we aren’t using row selection in this case)

accountsforDataTable.js

  • This file contains the JavaScript logic for handling data, such as fetching, displaying, and updating records.
import { LightningElement, wire, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountControllerInlineEdit.getAccounts';
import updateAccounts from '@salesforce/apex/AccountControllerInlineEdit.updateAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
//Salesforce Custom Data Table Inline Editing
const COLUMNS = [
    { label: 'Account Name', fieldName: 'Name', editable: true },
    { label: 'Industry', fieldName: 'Industry', editable: true },
    { label: 'Phone', fieldName: 'Phone', editable: true, type: 'phone' }
];

export default class AccountsforDataTable extends LightningElement {
    @track accounts;
    @track draftValues = [];
    columns = COLUMNS;

    @wire(getAccounts)
    wiredAccounts({ data, error }) {
        if (data) {
            this.accounts = data;
        } else if (error) {
            this.showToast('Error', 'Error loading data', 'error');
        }
    }
 //Salesforce Custom Data Table Inline Editing
    handleSave(event) {
        const updatedFields = event.detail.draftValues;

        updateAccounts({ accountsToUpdate: updatedFields })
            .then(() => {
                this.showToast('Success', 'Records updated successfully', 'success');
                this.draftValues = [];
                return this.refreshData();
            })
            .catch(error => {
                this.showToast('Error', 'Error updating records', 'error');
            });
    }

    refreshData() {
        return getAccounts()
            .then(data => {
                this.accounts = data;
            });
    }

    showToast(title, message, variant) {
        this.dispatchEvent(
            new ShowToastEvent({
                title,
                message,
                variant
            })
        );
    }
} 

//Salesforce Custom Data Table Inline Editing
  • @wire(getAccounts): This wire adapter calls the getAccounts Apex method to retrieve the Account records.
  • draftValues: This tracks any changes made in the datatable (e.g., when a user edits a field). The datatable component uses this to pass updated data to the save function.
  • handleSave(event): When the user clicks Save after editing a row, this method is triggered.
  • event.detail.draftValues: Holds the edited values, which are then passed to the Apex method updateAccounts for saving to Salesforce.
  • accountsforDataTable.js-meta.xml
  • The <LightningComponentBundle> file defines the metadata for your Lightning Web Component, specifying where it can be used in Salesforce.
  • The <targets> section allows the component to be added to Record Pages, App Pages, and Home Pages in the Lightning App Builder.
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>59.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle> 

//Salesforce Custom Data Table Inline Editing

Step 3: Deploy the Component

  • Authorize Your Org: Use sfdx force:auth:web:login to connect VS Code with your Salesforce org.
  • Deploy Components: Right-click the force-app folder and select SFDX: Deploy Source to Org.
  • Verify Deployment: Check the Output Panel in VS Code or confirm in Setup > Apex Classes and Lightning Components.
  • Add Component: Open Lightning App Builder and drag the LWC component onto the page.
  • Save and Activate: Click Save and Activate the page to make the component visible to users.

Step 4: Test Inline Editing Functionality

  • Before Editing: Open the Lightning page or application where the component is added and view the list of Account records displayed in the data table.
salesforce custom data table inline editing
  • Save Changes: Edit a record directly in the table, modify fields like Name, Industry, or Phone, and click Save.
salesforce custom data table inline editing
  • Success Confirmation: Verify the changes are saved successfully, and the data refreshes with the updated values.
Salesforce custom data table inline editing



This is about the article to implement Salesforce Custom Data Table Inline Editing using LWC. Kindly share your salesforce friends.

Author

  • Shantanu Joshi

    Shantanu Joshi is a certified Salesforce professional holding both Developer & AI Salesforce certifications, as well as Copado DevOps certifications. He currently works as an experienced Salesforce Developer at a reputable organization, driven by a strong enthusiasm for learning new skills. Shantanu continuously seeks opportunities for growth while delivering innovative and scalable solutions.

    View all posts

Leave a Comment