Inline Edit Data Table with Refresh View in LWC

 In this article,  we will learn about inline edit data table 

Apex Class

				
					public class AccountDatatable {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccount(){
        return [Select Id,Name ,Phone From Account];
    }
    @AuraEnabled
    public static boolean updaterecord(List<Account> acclist){
        try {
            update acclist;
            return true;
        } catch(Exception e) {
            return false;
        }
    }
}
				
			

accountRecord.html

				
					<template>
    <div style="height: 800px;">
               <lightning-datatable
                key-field="Id"
                show-row-number-column = false
                data={Datatable}
                hide-checkbox-column = false
                draft-values={draftValues}
                onsave={handleSave}
                columns={columns}>
        </lightning-datatable>
    </div> 
    <template if:true={error}>
        {error}
    </template>   
</template>

				
			

accountRecord.js

				
					import { LightningElement,track,wire } from 'lwc';
import getAccount from '@salesforce/apex/AccountDatatable.getAccount';
import updatelist from '@salesforce/apex/AccountDatatable.updaterecord';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class AccountRecord extends LightningElement {
    @track  columns = [
        { label: 'Account Name', fieldName: 'Name' ,type: 'text',editable: true},
        { label: 'Phone', fieldName: 'Phone',type: 'text',editable: true},
    ];
    @track error
    @track Datatable
    draftValues
    _datatableresp
    @wire(getAccount)
    wiredAccount(result) {  
        this._datatableresp = result
        if (result.data) {
            this.Datatable = result.data
        } else {
            this.error = result.error
        }
    }
    handleSave(event){
        this.draftValues = event.detail.draftValues;
       
         updatelist({acclist: this.draftValues})
         .then( result => {
            console.log( JSON.stringify( "Apex update result: " + result ) )
            if(result === true){
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success!!',
                        message: 'successfully Account has been updated',
                        variant: 'success'
                    })
                   
                );
                this.draftValues = []
                return refreshApex(this._datatableresp);
            } else {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error!!',
                        message: 'something went wrong please try again',
                        variant: 'error'
                    })
                );
            }
            
         })
    }
}
				
			

Output

Leave a Comment