Requirement : | ‹ | › |
Create a LWC which will take information like Name, Phone and Industry and on click of Save button , record should be saved to the org as Account.
or in other words
Create account record LWC.
cmpAccountRecord.html
<template>
<lightning-card title="New Account" icon-name="standard:account">
<lightning-input
label= "Name"
value={objAccount.Name}
onchange={handleNameChange}>
</lightning-input>
<lightning-input
label="Phone"
value={objAccount.Phone}
onchange={handlePhoneChange}>
</lightning-input>
<lightning-input
label="Industry"
value={objAccount.Industry}
onchange={handleIndustryChange}>
</lightning-input>
<br>
<lightning-button label="Save" onclick={handleSaveRecord}></lightning-button>
</lightning-card>
</template>
cmpAccountRecord.js
import createAccount from '@salesforce/apex/cmpAccountRecordCls.createAccount';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { LightningElement,track } from 'lwc';
export default class DevCmpCreateRecord extends LightningElement {
@track objAccount = {
Name : '',
Industry : '',
Phone : ''
}
handleNameChange(event){
this.objAccount.Name = event.target.value;
}
handleIndustryChange(event){
this.objAccount.Industry = event.target.value;
}
handlePhoneChange(event){
this.objAccount.Phone = event.target.value;
}
handleSaveRecord(){
createAccount({objAccount : this.objAccount})
.then(result => {
this.message = result;
this.objAccount = {};
this.error = undefined;
if(this.message !== undefined){
this.objAccount.Name = '';
this.objAccount.Industry = '';
this.objAccount.Phone = '';
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: 'Account created',
variant: 'success',
}),
);
}
console.log(JSON.stringify(result));
console.log("result", this.message);
})
.catch(error => {
this.message = undefined;
this.error = error;
this.dispatchEvent(
new ShowToastEvent({
title: 'Error creating record',
message: error.body.message,
variant: 'error',
}),
);
console.log("error", JSON.stringify(this.error));
});
}
}
cmpAccountRecord.js-meta.xml
<?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>
cmpAccountRecordCls.cls
public with sharing class cmpAccountRecordCls {
@AuraEnabled
public static Account createAccount(Account objAccount){
insert objAccount;
return objAccount;
}
}
Output:
Very nice knowledgefull post... you have explained in very detail..
ReplyDelete