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
Abhishek Sharma 527Abhishek Sharma 527 

update records in LWC

Hello there, I have LWC to show contact records and modal to edit the records, I'm able to fetch records and editing also showing but don't know how to run query to update records, pls look into my code and suggest.

//html 
  <!-- <template>
    <c-record_modal></c-record_modal>
    <lightning-card title="Contact Records" style="font-size: 10px">
        <template if:true={contacts.data}>
            <lightning-datatable key-field="Id"
                                 data={contacts.data}
                                 columns={columns}
                                 onsave={handleSave}
                                 draft-values={saveDraftValues}
                                 hide-checkbox-column
                                 show-row-number-column>
                                </lightning-datatable>
        </template>
           
    </lightning-card>
</template> -->

<template>
    <lightning-card title="Contact Records">
       
        <lightning-datatable data={wireContact.data} columns={columns} key-field="id" hide-checkbox-column="true"  onrowaction={handleRowAction}></lightning-datatable>
       
        <template if:true={modalContainer}>
            <section  class="slds-modal slds-fade-in-open">
                <div class="slds-modal__container">
                    <header class="slds-modal__header">
                        <button class="slds-button slds-button_icon slds-modal__close slds-button_icon-inverse" title="Close" onclick={closeModalAction}>
                           <lightning-icon icon-name="utility:close" alternative-text="close" variant="inverse" size="small" ></lightning-icon>
                        </button>
                       
                        <h2 class="slds-text-heading_medium slds-hyphenate">Contact Record Detail</h2>
                     </header>
                     <div class="slds-modal__content slds-p-around_medium">
                        <table class="slds-table slds-table_bordered slds-table_col-bordered slds-table_cell-buffer">
                           <thead>
                            <tr>
                                <th>First Name</th>
                                <th>Last Name</th>
                                <th>Email Name</th>
                                <th>Phone Name</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr>

                                <td><lightning-input
                                    type="text"
                                    label="first name"
                                    value={contactRow.FirstName}>
                                </lightning-input></td>
                                <td><lightning-input
                                    type="text"
                                    label="Last name"
                                    value={contactRow.LastName}>
                                </lightning-input></td>
                                <td><lightning-input
                                    type="Email"
                                    label="Email"
                                    value={contactRow.Email}>
                                </lightning-input></td>
                                <td><lightning-input
                                    type="tel"
                                    label="Phone"
                                    value={contactRow.Phone}>
                                </lightning-input> </td>
                            </tr>
                        </tbody>  
                        </table>
                     </div>
                     <footer class="slds-modal__footer">
                     
                        <lightning-button class="slds-p-horizontal_medium" id="btn1" variant="brand" label="Close" title="Close"  onclick={closeModalAction}></lightning-button>
                        <lightning-button class="slds-p-horizontal_medium" variant="brand" label="Save" title="Save"  onclick={handleSave}></lightning-button>
                       
                   </footer>
                </div>
            </section>
            <div class="slds-backdrop slds-backdrop_open"></div>
        </template>
    </lightning-card>
</template>

--------------------------------------------------------------------------

//JS code

import { LightningElement, track, wire } from 'lwc';
import getContacts from '@salesforce/apex/LWCExampleController.getContacts';
const columns=[
    {
        label: 'View',
        type: 'button-icon',
        initialWidth: 75,
        typeAttributes: {
            iconName: 'action:preview',
            title: 'Preview',
            variant: 'border-filled',
            alternativeText: 'View'
        }
      },
      {
        label: 'First Name',
        fieldName: 'FirstName'
    },
    {
        label: 'Last Name',
        fieldName: 'LastName'
    },
    {
        label: 'Email',
        fieldName: 'Email'
    },
    {
        label: 'Phone',
        fieldName: 'Phone'
    }
];
export default class LwcDataTableRowAction extends LightningElement {
  @track columns = columns;
  @track contactRow={};
  @track rowOffset = 0;  
  @track modalContainer = false;
   @wire(getContacts) wireContact;
 
   handleRowAction(event){
      const dataRow = event.detail.row;
      window.console.log('dataRow@@ ' + dataRow);
      this.contactRow=dataRow;
      window.console.log('contactRow## ' + dataRow);
      this.modalContainer=true;
   }
//    handleSave(){
//     saveRecords()
//    }
   closeModalAction(){
    this.modalContainer=false;
   }
}

----------------------------------------------------------------

// class file

public inherited sharing class LWCExampleController {
    @AuraEnabled(Cacheable = true)
    public static List<Contact> getContacts() {
        return [SELECT Id, Name, FirstName, LastName, Phone, Email
                FROM Contact
                WHERE Email != null
                AND Phone != null
                ORDER BY CreatedDate DESC NULLS LAST limit 10];
    }
    // @AuraEnabled(Cacheable = true)
    // public static List<Contact> saveRecords(){
    //     return [UPDATE FirstName, LastName, Phone, Email FROM Contact] //clarification on this
    // }
}
 
TobyKutlerTobyKutler
You cannot use a query to update, create, or delete records. You want to pass in the collection of records to update and then use a Update DML statement. Something like this: 

     @AuraEnabled(Cacheable = true)
   public static void saveRecords(List <Contact> contactsToUpdate){
      update contactsToUpdate; 
   }
Abhishek Sharma 527Abhishek Sharma 527
Thanks Toby, I created method as - 

@AuraEnabled(Cacheable = true)
   public static void saveRecords(List <Contact> contactsToUpdate){
   
    contactsToUpdate = [Select FirstName, LastName, Phone, Email FROM Contact];
   
    update contactsToUpdate;
   }

// and from JS file I'm calling this method as -

handleSave(){
    saveRecords(this.contactRow)
   }

but it's giving error, am I doing incorrect, please suggest.

 User-added image
TobyKutlerTobyKutler
No need to do a query at all since you are passing in the records to update from the javascript. If you are just going to update one record in your logic you can pass it in as a single record, otherwise in your javascript, you would need to first put the contact into a list. In the JS file, you need to call the Apex method by using wire or importing it and call it asynchronously 
 
@AuraEnabled(Cacheable = true)
   public static void saveRecord(Contact contactToUpdate){
   update contactToUpdate;
  }

Then the JS would look like this: 
import saveRecord from '@salesforce/apex/{YourClassName}.saveRecord' 

export default class yourComponentName extends LightningElement {

async handleSave(){

   try{
         await saveRecord({
         contactToUpdate : this.contactRow

       )}
   }
   catch(error){
        console.log(error); 
   }


   }

}
If you need to pass in multiple values to save :
 
@AuraEnabled(Cacheable = true)
   public static void saveRecords(List <Contact> contactsToUpdate){
   update contactToUpdate;
  }
and Js: 
import saveRecords from '@salesforce/apex/{YourClassName}.saveRecords' 

export default class yourComponentName extends LightningElement {

async handleSave(){

   try{
         let contactList = [this.contactRow] ; 
        //add any other contacts to List above or below by adding to list
         await saveRecords({
         contactsToUpdates : contactList
       )}
   }
   catch(error){
        console.log(error); 
   }


   }

}