Lightning Web Component createRecord example

Telegram logo Join our Telegram Channel

In this post, we will see how to create a record using createRecord method from uiRecordApi in Lightning Web Component.

For this example, we will create an account record from Lightning Web Component. Let's go through it step by step. We will create a form in which users can enter the Account Name, Website, and Phone.

LWC-CreateRecord-uiRecordApi-example


How to use createRecord method?

Before we go to the final code let us see how to use the getRecord method in detailed steps. Firstly you need to import the method like below.

import { createRecord } from 'lightning/uiRecordApi';

Then, you can directly call this method from the controller. This method requires one parameter, called recordInput, and below is the structure of recordInput.

{
    apiName: '- object api name -',
    fields : {
        /* field values here */
    }
}

This method returns a promise let us see how to call that in the next section. If you don't know what are apex promises visit: Promises in LWC.


Simple working example to create an Account.

I have created a new Lightning web component name createRecordExample. In that component, I have added three lighting inputs to get the Name, Website, and Phone fields of an Account.

Also, I have added the change handler handleChange on those to get the values entered. So the field values are getting stored in the attribute called accountRecord. This attribute we going to pass to the createRecord method.

createRecordExample.js

import { LightningElement, track } from "lwc";

import { ShowToastEvent } from "lightning/platformShowToastEvent";
import { createRecord } from "lightning/uiRecordApi";
import { reduceErrors } from "c/ldsUtils";

import ACCOUNT_OBJECT from "@salesforce/schema/Account";

export default class CreateRecordExample extends LightningElement {
    accountRecord = {};
    isLoading = false;

    handleChange(event) {
        this.accountRecord[event.target.name] = event.target.value;
    }

    createAccount() {
        this.isLoading = true;
        const fields = this.accountRecord;

        const recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields };

        createRecord(recordInput)
            .then((account) => {
                this.accountId = account.id;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: "Success",
                        message: "Account created successfully!",
                        variant: "success"
                    })
                );

                this.accountRecord = {};
            })
            .catch((error) => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: "Error creating record",
                        message: reduceErrors(error).join(", "),
                        variant: "error"
                    })
                );
            })
            .finally(() => {
                this.isLoading = false;
            });
    }
}

In the HTML code, the createAccount method is being called from the button. Also, I have assigned the value attribute of the input to its respective field from the accountRecord. The name attribute of the input tags is used to associate the fields with values from the inputs.

createRecordExample.html

<template>
    <lightning-card title="Create Account" icon-name="standard:account">
        <div class="slds-var-m-around_small slds-is-relative">

            <lightning-spinner 
                if:true={isLoading}
                alternative-text="Loading"
                size="large">
            </lightning-spinner>

            <lightning-input 
                label="Account Name" 
                name="Name" 
                onchange={handleChange} 
                class="slds-var-p-around_x-small"
                value={accountRecord.Name}>
            </lightning-input>

            <lightning-input 
                label="Website" 
                name="Website"
                onchange={handleChange} 
                class="slds-var-p-around_x-small"
                value={accountRecord.Website}>
            </lightning-input>

            <lightning-input 
                label="Phone" 
                name="Phone" 
                type="phone"
                onchange={handleChange} 
                class="slds-var-p-around_x-small"
                value={accountRecord.Phone}>
            </lightning-input>

            <div class="slds-var-m-around_x-small">
                <lightning-button
                    label="Create an account"
                    variant="brand"
                    onclick={createAccount}>
                </lightning-button>
            </div>
            
        </div>   
    </lightning-card>
</template>

createRecordExample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="CreateRecordExample">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>


LWC Series

  1. Lightning Web Components Folder Structure
  2. Lightning data service with LWC
  3. All methods from uiRecordApi LWC
  4. Lightning Web Component createRecord example
4 comments:
  1. Thank you very much for this wonderful example !!

    ReplyDelete
    Replies
    1. Thank you Goverdhan! I am glad it was helpful. Please follow for more updates!

      Delete
  2. Thank you so much. great example.

    ReplyDelete

Hi there, comments on this site are moderated, you might need to wait until your comment is published. Spam and promotions will be deleted. Sorry for the inconvenience but we have moderated the comments for the safety of this website users. If you have any concern, or if you are not able to comment for some reason, email us at rahul@forcetrails.com