Editable Lightning Datatable In LWC

Editable Lightning Datatable In salesforce lwc

HTML

<template>
    <lightning-card title="Editable Account Table">
        <lightning-datatable
            key-field="Id"
            data={accounts}
            columns={columns}
            onsave={handleSave}
            draft-values={draftValues}
            hide-checkbox-column>
        </lightning-datatable>
    </lightning-card>
</template>

JavaScript

import { LightningElement, wire, track } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
import updateAccounts from '@salesforce/apex/AccountController.updateAccounts';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { refreshApex } from '@salesforce/apex';

export default class EditableDataTable extends LightningElement {
    @track accounts;
    @track draftValues = [];

    columns = [
        { label: 'Name', fieldName: 'Name', type: 'text', editable: true },
        { label: 'Phone', fieldName: 'Phone', type: 'phone', editable: true },
        { label: 'Industry', fieldName: 'Industry', type: 'text', editable: true }
    ];

    @wire(getAccounts)
    wiredAccounts({ error, data }) {
        if (data) {
            this.accounts = data;
        } else {
            console.error(error);
        }
    }

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

        updateAccounts({ data: updatedFields })
            .then(() => {
                this.dispatchEvent(new ShowToastEvent({
                    title: 'Success',
                    message: 'Records updated successfully!',
                    variant: 'success'
                }));
                this.draftValues = [];
                return refreshApex(this.wiredAccounts);
            })
            .catch(error => {
                let message = 'Unknown error';

                if (Array.isArray(error.body)) {
                    message = error.body.map(e => e.message).join(', ');
                } else if (typeof error.body?.message === 'string') {
                    message = error.body.message;
                } else if (typeof error.message === 'string') {
                    message = error.message;
                }

                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error updating records',
                        message: message,
                        variant: 'error'
                    })
                );
            });

    }
}

Apex Controller

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccounts() {
        return [SELECT Id, Name, Phone, Industry FROM Account LIMIT 100];
    }

    @AuraEnabled
    public static void updateAccounts(List<Account> data) {
        update data;
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *