Create account without Apex controller in LWC
It's always recommends to use Lightning Data Service(LDS) of lightning-record-form to create any record from UI. But sometimes we don't need to take inputs from user, just we need to create record with some static data, in this use case we can use UIRecordApi to create any object record without calling apex method and without using lightning record form.
1. First import createRecord method from uiRecordApi.
[import {createRecord} from 'lightning/uiRecordApi';]
2. Create an javascript object with object api name and fields with data to insert.
[// we have to create an object of fields to enter dataconst fields = {Name: accountName.value,};// It's the final object to send CreateRecord method to createconst recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };]
3. Now pass the recordInput object to createRecord method to create record.
[// Calling createRecord method of uiRecordApicreateRecord(recordInput)]
Let's see with an example:
CreateRecordUsingUiRecordApi.html
[<template><lightning-card title="Create account using Ui record api" icon-name="standard:account"><div class="slds-m-around_medium"><lightning-input type="string" label="Account Name"></lightning-input><br/><lightning-button name="CreateAccount" label="Create Account" onclick={handleCreateAccount}></lightning-button></div></lightning-card></template>]
CreateRecordUsingUiRecordApi.js
[import { LightningElement } from 'lwc';import {createRecord} from 'lightning/uiRecordApi';import { ShowToastEvent } from 'lightning/platformShowToastEvent';import ACCOUNT_OBJECT from '@salesforce/schema/Account';export default class CreateRecordUsingUiRecordApi extends LightningElement {handleCreateAccount(){// get the entered value from UIlet accountName = this.template.querySelector('lightning-input');// we have to create an object of fields to enter dataconst fields = {Name: accountName.value,};// It's the final object to send CreateRecord method to createconst recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };// Calling createRecord method of uiRecordApicreateRecord(recordInput).then(account =>{this.dispatchEvent(new ShowToastEvent({title: 'Success',message: 'New account has been created',variant: 'success',}),);}).catch(error => {this.dispatchEvent(new ShowToastEvent({title: 'Error while creating account',message: error.body.message,variant: 'error',}),);});}}]
CreateRecordUsingUiRecordApi.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></targets></LightningComponentBundle>]
You can also find the above code in SWDC WORLD.
COMMENTS