function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Shuhbam SinhaShuhbam Sinha 

How to update multiple records from apex in LWC

Hello,
I have one scenario where I need to upddate status of multiple records in LWC. I was using onchange event but now i need to use SAVE button to update it. So how can i update multiple records in a single Save button.I have used . Some how I am able to update the one record but it is not updating the multiple records.

handleChange(event) {
    this.value = event.detail.value;
    const selectedRecordId = event.target.dataset.id;
    console.log('trueOwnerId',this.areDetailsVisible);
    console.log("inputno",this.value);
    console.log("record",selectedRecordId);
    //this.realFormData = {Id : event.target.dataset.id , [event.target.dataset.field] : event.detail.value};
    this.realFormData = {...this.realFormData ,Id : event.target.dataset.id ,[event.target.dataset.field] : event.detail.value};
    console.log( "newrealform",this.realFormData);

}
 handleSave(event){
  console.log('Refresh Apex called');
  updateMyCheckList({recordUpdate : this.realFormData}).then(()=>{ 
    console.log('Refresh Apexsuccess called');
    refreshApex(this.wiredAccountsResult);
    const event = new ShowToastEvent({
      title: 'Success',
      message: 'Records are updated sucessfully',
      variant: 'success',
      mode: 'dismissable'
  });
  this.dispatchEvent(event);
  });
  }


My Apex:-
 @AuraEnabled
    public static void updateCheckList(Checklist__c recordUpdate){
        system.debug('receivedPara '+ recordUpdate);
        update recordUpdate;
    }

Could anyone please help me on the same.Thanks in advance.
SubratSubrat (Salesforce Developers) 
Hello ,

To update multiple records in a single save button click event in LWC, you can follow these steps:

Maintain an array to store the updated records.

In the handleChange function, instead of updating the this.realFormData object directly, push the updated record object into the array.

In the handleSave function, pass the array of updated records to the server-side Apex method for updating.

In the Apex method, perform the update operation on the received array of records.

Here's an example implementation:

Modify the handleChange function to push the updated record into the array:
handleChange(event) {
    const selectedRecordId = event.target.dataset.id;
    const field = event.target.dataset.field;
    const value = event.detail.value;
    
    // Find the record in the array or create a new one
    let recordToUpdate = this.realFormData.find(record => record.Id === selectedRecordId);
    if (!recordToUpdate) {
        recordToUpdate = { Id: selectedRecordId };
        this.realFormData.push(recordToUpdate);
    }
    
    // Update the specific field value in the record
    recordToUpdate[field] = value;
}
Modify the handleSave function to pass the array of updated records to the server-side Apex method:
handleSave(event) {
    updateMyCheckList({ recordsToUpdate: this.realFormData })
        .then(() => {
            refreshApex(this.wiredAccountsResult);
            const toastEvent = new ShowToastEvent({
                title: 'Success',
                message: 'Records are updated successfully',
                variant: 'success',
                mode: 'dismissable'
            });
            this.dispatchEvent(toastEvent);
        })
        .catch(error => {
            console.error('Error updating records:', error);
            const toastEvent = new ShowToastEvent({
                title: 'Error',
                message: 'An error occurred while updating records',
                variant: 'error',
                mode: 'dismissable'
            });
            this.dispatchEvent(toastEvent);
        });
}
Modify the Apex method to update the received array of records:
@AuraEnabled
public static void updateCheckList(List<Checklist__c> recordsToUpdate) {
    try {
        update recordsToUpdate;
    } catch (Exception e) {
        System.debug('Error updating records: ' + e.getMessage());
        throw new AuraHandledException('An error occurred while updating records');
    }
}

Hope this helps !
Thank you.