SalesforceBlue

Feel the rhythm of Salesforce

LWC

Create Records In LWC Using lightning/uiRecordApi

Let’s create a record today by using lightning/uiRecordApi.

Just a note that we should first explore lightning-record-*-form components for creating records and if you need more flexibility such as records getting created from callback methods or creating records on triggering of some events then we can utilize lightning/uiRecordApi.

Please create a component(LWC) named as createRecordLwc and add the following code to it.

<template>
    <lightning-card title="Create Record Using lightning/uiRecordApi" icon-name="standard:record">
       <div class="slds-m-around_medium">
           <lightning-input label="Name" onchange={handleNameChange} class="slds-m-bottom_x-small"></lightning-input>
           <lightning-button label="Create Account" variant="brand" onclick={createAccount}></lightning-button>
       </div>
    </lightning-card>
</template> 
import { LightningElement } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';

export default class createRecordLwc extends LightningElement {
    accountId;
    name = '';

    handleNameChange(event) {
        this.accountId = undefined;
        this.name = event.target.value;
    }
    createAccount() {
        const fields = {};
        fields[NAME_FIELD.fieldApiName] = this.name;
        const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };
        createRecord(recordInput)
            .then(account => {
                this.accountId = account.id;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Account created',
                        variant: 'success',
                    }),
                );
            })
            .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>50.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__HomePage</target>
    </targets>    
</LightningComponentBundle>

Let’s understand what is happening above:

In the file createRecordLwc.js we have imported createRecord from the lightning/uiRecordApi module

import { createRecord } from 'lightning/uiRecordApi';

In the createRecord function, we are passing on the required fields and their respective values. This function returns a promise object that resolves when the record is created.

createRecord(recordInput)
    .then(account => { 
        this.accountId = account.id;
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Success',
                message: 'Account created',
                variant: 'success',
            }),
        );
    })
    .catch(error => {
        this.dispatchEvent(
            new ShowToastEvent({
                title: 'Error creating record',
                message: error.body.message,
                variant: 'error',
            }),
        );
    });

Feel free to add this component to the home page and observe the behavior. You will be getting an output like in below screenshot:


Thank you for visiting SalesforceBlue.com
If you have any queries feel free to write down a comment below 🙂


3 thoughts on “Create Records In LWC Using lightning/uiRecordApi

  • seyma

    in my salesforce org import { createRecord } from ‘lightning/uiRecordApi’; a new component
    I can’t use it while creating, can you help me?

    Reply
    • Pankaj Agrahari

      Hi Seyma,

      Sure, will assist you.

      Can you share more details exactly what you are doing and where you are stuck so i can respond accordingly.

      Thanks!

      Reply
  • i just copy the code and paste in lwc component , but i changed the object naem to my custom object , and necessary fields are added , but im able to see the error like : Invalid reference Company__c.Last_Name__c of type sobjectField in file creaateNewRecord.js: Source ..

    the apiname of the objet and fields are corect , nut it w showing erro

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *