How to insert account records using LWC?
InsertAccountRecords.html:
<template>
<lightning-card title="Account Information" icon-name="standard:account">
<div class="slds-p-around_x-small">
<lightning-input label="Name" value={rec.Name} onchange={handleNameChange}></lightning-input>
<lightning-input label="Industry" value={rec.Industry} onchange={handleIndChange}></lightning-input>
<lightning-input type="Phone" label="Phone" value={rec.Phone} onchange={handlePhnChange}></lightning-input><br/>
<lightning-button label="Save" onclick={handleClick}></lightning-button>
</div>
</lightning-card>
</template>
InsertAccountRecords.js:
import { LightningElement, track} from 'lwc';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
import createAccount from '@salesforce/apex/InsertAccController.createAccount';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
export default class CreateRecordWithFieldIntigrity extends LightningElement {
@track name = NAME_FIELD;
@track industry = INDUSTRY_FIELD;
@track phone = PHONE_FIELD;
rec = {
Name : this.name,
Industry : this.industry,
Phone : this.phone
}
handleNameChange(event) {
this.rec.Name = event.target.value;
console.log("name1", this.rec.Name);
}
handleIndChange(event) {
this.rec.Industry = event.target.value;
console.log("Industry", this.rec.Industry);
}
handlePhnChange(event) {
this.rec.Phone = event.target.value;
console.log("Phone", this.rec.Phone);
}
handleClick() {
createAccount({ acc : this.rec })
.then(result => {
this.message = result;
this.error = undefined;
if(this.message !== undefined) {
this.rec.Name = '';
this.rec.Industry = '';
this.rec.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));
});
}
}
InsertAccountRecords.meta.xml:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>56.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
InsertAccController.apxc:
public with sharing class InsertAccController {
@AuraEnabled
public static Account createAccount(Account acc){
try {
System.debug(acc);
insert acc;
return acc;
} catch (Exception e) {
throw new AuraHandledException(e.getMessage());
}
}
}
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.