Create Record in LWC using createRecord of uiRecordApi

In this post, we will implement the basic functionality to create records in LWC using createRecord of uiRecordApi module. Let’s get into the implementation.

Implementation

In this implementation, we will create an Account record. We will display the Account record Id in the Alert box once the record is created successfully.

Create a lightning web component ldsCreateRecord. Use lightning-input to get the user input for Account Name, Account Number, and Phone. Add lightning-button to call the JS controller method to create the record. Add onchange handler for each lightning-input tag to get the updated value in the JS controller.

ldsCreateRecord.html

<template>
    <lightning-card title="Create Account Record using LDS">
        <lightning-layout>
            <lightning-layout-item size="6">
                <!-- Displaying fields to get information. -->
                <lightning-input class="slds-p-around_medium" label="Name" name="accoutName" 
                    onchange={nameChangedHandler}></lightning-input>
                <lightning-input class="slds-p-around_medium" label="Account Number" name="accoutNumber" 
                    onchange={numberChangedHandler}></lightning-input>
                <lightning-input class="slds-p-around_medium" label="Phone" type="phone" name="accountPhone" 
                    onchange={phoneChangedHandler}></lightning-input>
                <br/>
                <lightning-button class="slds-m-left_x-small" label="Create Account" variant="brand" 
                    onclick={createAccount}></lightning-button>
            </lightning-layout-item>
        </lightning-layout>
    </lightning-card>
</template>

In the JS controller, add the onchange handlers for all the inputs and store them in private variables. createAccount() method is executed once the Create Account button is clicked.

Import the createRecord method from uiRecordApi module of the lightning namespace.

In createAccount(), create JSON variable fields where the key is API name of Account field and value is the value that we get from input fields. Add key-value pairs for all the fields that we want to store in the Account record. It is mandatory to have the name of this JSON variable as fields. Create another JSON variable objRecordInput where the first entry should be the ‘apiName’ and, value for this should be the API name of Object. The second entry should be the fields JSON that we created earlier.

createRecord() in LWC

The final step is to call the createRecord() with objRecordInput as a parameter. This method returns a Promise. A Promise can be either in pending, fulfilled, or rejected state. A pending promise can either be fulfilled with a value or rejected with an error. Hence we need to handle only a fulfilled and rejected state. When the Promise returned by createRecord() is successful or fulfilled, then() will be executed. If it returns an error, then the catch() function is executed.

If the Account record is inserted successfully, then() method will execute which will display Account record Id in Alert. If it fails, catch() will display an an error object in Alert.

ldsCreateRecord.js

import { LightningElement } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
export default class LdsCreateRecord extends LightningElement {
    strName;
    strAccountNumber;
    strPhone;
    // Change Handlers.
    nameChangedHandler(event){
        this.strName = event.target.value;
    }
    numberChangedHandler(event){
        this.strAccountNumber = event.target.value;
    }
    phoneChangedHandler(event){
        this.strPhone = event.target.value;
    }
    // Insert record.
    createAccount(){
        // Creating mapping of fields of Account with values
        var fields = {'Name' : this.strName, 'AccountNumber' : this.strAccountNumber, 'Phone' : this.strPhone};
        // Record details to pass to create method with api name of Object.
        var objRecordInput = {'apiName' : 'Account', fields};
        // LDS method to create record.
        createRecord(objRecordInput).then(response => {
            alert('Account created with Id: ' +response.id);
        }).catch(error => {
            alert('Error: ' +JSON.stringify(error));
        });
    }
}

Create Record in LWC

This is how our implementation will look:

Create Record in LWC using createRecord of uiRecordApi
Create Record in LWC using createRecord of uiRecordApi

Also Read:

This is how we can create records in LWC using createRecord of uiRecordApi module.

If you want to check more implementations using Lightning Web Components, you can check it here.

To know more about createRecord of uiRecordApi module, you can check it here.

In the next post, we will implement more functionality of the Lightning Data Service. If you don’t want to miss new posts, Subscribe here.