Create Record example.
createRecord.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="createRecord"> <apiVersion>45.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__RecordPage</target> <target>lightning__HomePage</target> </targets> </LightningComponentBundle>
createRecord.html
<template> <lightning-card title="Create Account"> <lightning-layout> <lightning-layout-item> <lightning-input label="Account Name" onchange={handleChanges} class="slds-m-bottom_x-small"></lightning-input> <br/> <lightning-input label="Account Site" onchange={handleChanges} class="slds-m-bottom_x-small"></lightning-input> <br/> <button onclick={createAccountRecord}>Create</button> </lightning-layout-item> </lightning-layout> </lightning-card> </template>
createRecord.js
import { LightningElement } from 'lwc'; import { createRecord } from 'lightning/uiRecordApi'; import { ShowToastEvent } from 'lightning/platformShowToastEvent'; import ACCOUNT_OBJECT from '@salesforce/schema/Account'; import ACCOUNT_NAME from '@salesforce/schema/Account.Name'; import ACCOUNT_SITE from '@salesforce/schema/Account.Site'; export default class CreateRecord extends LightningElement { accountId; inputLabel; inputValue; accName; accSite; // Fetch user input. handleChanges(event){ this.inputLabel = event.target.label; this.inputValue = event.target.value; if( this.inputLabel === "Account Name" && this.inputValue !== null && this.inputValue !=='' && this.inputValue !== undefined) this.accName = event.target.value; if( this.inputLabel === "Account Site" && this.inputValue !== null && this.inputValue !=='' && this.inputValue !== undefined) this.accSite = event.target.value; } // Perform create action. createAccountRecord(){ const fields = {}; fields[ACCOUNT_NAME.fieldApiName] = this.accName; fields[ACCOUNT_SITE.fieldApiName] = this.accSite; const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields }; createRecord(recordInput) .then(account => { this.accountId = account.id; this.dispatchEvent( new ShowToastEvent({ title: 'Success', message: 'Account Id ' + this.accountId + ' is created successfully.', variant: 'success', }), ); }) .catch(error => { this.dispatchEvent( new ShowToastEvent({ title: 'Error while creating account record', message: error.body.message, variant: 'error', }), ); }); } }
Output: