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 with apex

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 write apex class and call into JS, please anyone guide, it will be great help.

//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(this.contactRow)
   }
   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 void saveRecords(List <Contact> contactsToUpdate){

contactsToUpdate = [Select FirstName, LastName, Phone, Email FROM Contact];

      update contactsToUpdate; 
   }
}
SwethaSwetha (Salesforce Developers) 
HI Abhishek ,
I see you also posted on https://salesforce.stackexchange.com/questions/383706/update-records-in-lwc-using-apex and it has been addressed.
 

If you are willing to use lightning-input and apex, then you need to follow few steps:-

  • Add a change handler in lightning-input like below:- <lightning-input label="First Name" value={contactRow.FirstName} onchange={handleChange}></lightning-input>

  • handle the change handler in your JS file like below:-
     

    handleChange(event){
         if(event.target.label=='First Name'){
             this.contactRow.FirstName = event.target.value;
         }
         if(event.target.label=='Last Name'){
             this.contactRow.LastName = event.target.value;
         }            
         if(event.target.label=='Phone'){
             this.contactRow.Phone = event.target.value;
         }
         //similarly add other fields
      }
    Now pass the contactRow to apex method and save the record. To call the apex method, check the example here
  • handleSave(){
        saveRecords({ contactToUpdate: this.contactRow })
             .then((result) => {
                 console.log(result);
             })
             .catch((error) => {
                 console.log(error);
             });
    }
     

    and your apex method will be like below, make sure you do not add the caacheable=true otherwise it will throw too many dml error
     

    @AuraEnabled
       public static void saveRecords(Contact contactToUpdate){
          update contactsToUpdate; 
       }
Please consider marking this answer best to close the thread so it can help other too in future.

Thanks