Requirement : | ‹ | › |
Create a LWC in which get the contact records in Datatable and Update single record.
Or in other words
Update Single Record through Datatable.
cmpDatatableUpdateSingleRecord.html
<template>
<lightning-card title="Update Contact Record" icon-name="custom:custom63">
<div class="slds-m-around_medium">
<template if:true={contact.data}>
<lightning-datatable
key-field="Id"
data={contact.data}
columns={columns}
draft-values={draftValues}
onsave={handleSave}>
</lightning-datatable>
</template>
</div>
</lightning-card>
</template>
import { LightningElement,track,wire } from 'lwc';
import getContactList from '@salesforce/apex/cmpDataTableUpdateSingleRecordCls.getContactList';
import { updateRecord } from 'lightning/uiRecordApi';
import { refreshApex } from '@salesforce/apex';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import FIRSTNAME_FIELD from '@salesforce/schema/Contact.FirstName';
import LASTNAME_FIELD from '@salesforce/schema/Contact.LastName';
import ID_FIELD from '@salesforce/schema/Contact.Id';
const COLS = [
{label: 'First Name' ,fieldName: 'FirstName', editable: true},
{label: 'Last Name', fieldName: 'LastName', editable: true},
{label: 'Email', fieldName: 'Email', editable: true}
];
export default class cmpDataTableUpdateSingleRecord extends LightningElement {
@track error;
@track columns = COLS;
@track draftValues = [];
@wire(getContactList)
contact;
handleSave(event){
const fields = {};
fields[ID_FIELD.fieldApiName] = event.detail.draftValues[0].Id;
fields[FIRSTNAME_FIELD.fieldApiName] = event.detail.draftValues[0].FirstName;
fields[LASTNAME_FIELD.fieldApiName] = event.detail.draftValues[0].LastName;
const recordInput = {fields};
updateRecord(recordInput)
.then(() => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Contact updated',
variant: 'success'
})
);
// Clear all draft values
this.draftValues = [];
// Display fresh data in the datatable
return refreshApex(this.contact);
})
.catch(error => {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error creating record',
message: error.body.message,
variant: 'error'
})
);
});
}
}
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>48.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
<target>lightning__Tab</target>
</targets>
</LightningComponentBundle>
public with sharing class cmpDataTableUpdateSingleRecordCls {
@AuraEnabled(cacheable=true)
public static list<Contact> getContactList(){
return[
SELECT Id,FirstName,LastName,Phone,Email,Title
FROM Contact
WITH SECURITY_ENFORCED
LIMIT 10
];
}
}
Comments
Post a Comment