Create Record by UI API

Now, we will see how to create a record using UI API.
In this example, we will create a Contact record by using uiRecordApi which is a part of the UI API.

So, we have built a LWC named “createUIRecord“.

Step 1: As per previous examples, we need to update the “createUIRecord.js-meta.xml” file to set the visibility in Lightning App Builder.

createUIRecord.js-meta.xml

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

Step 2: Need to write the respective HTML file.

createUIRecord.html

<template>
    <lightning-card title="Create Record(Contact) by UIRecordAPI">            
        <lightning-layout> 
            <lightning-layout-item flexibility="auto" padding="around-small">
                <lightning-input label="First Name" onchange={handleChange}></lightning-input>
                <lightning-input label="Last Name" onchange={handleChange}></lightning-input>
                <lightning-input label="Email" onchange={handleChange} class="slds-m-bottom_x-small"></lightning-input>
                <lightning-button label="Create Record" variant="brand" onclick={createContact}></lightning-button>
            </lightning-layout-item>
        </lightning-layout> 
    </lightning-card>
</template>

Step 3: Now, we need to work on the JS file.

createUIRecord.js

import { LightningElement } from 'lwc';
import {createRecord} from 'lightning/uiRecordApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import CONTACT_OBJECT from '@salesforce/schema/Contact';
import CONTACT_FIRST_NAME from '@salesforce/schema/Contact.FirstName';
import CONTACT_LAST_NAME from '@salesforce/schema/Contact.LastName';
import CONTACT_EMAIL from '@salesforce/schema/Contact.Email';

export default class CreateUIRecord extends LightningElement {

    fieldValue;
    firstName;
    lastName; 
    email;
    contactId;

    handleChange(event){
        this.fieldValue = event.target.value;        
        if(event.target.label === "First Name" && this.fieldValue !=='' && this.fieldValue !== undefined)
            this.firstName = this.fieldValue;
        else if(event.target.label === "Last Name" && this.fieldValue !=='' && this.fieldValue !== undefined)
            this.lastName = this.fieldValue;
        else if(event.target.label === "Email" && this.fieldValue !=='' && this.fieldValue !== undefined)
            this.email = this.fieldValue;        
    }

    createContact(){

        const FIELDS = {};
        FIELDS[CONTACT_FIRST_NAME.fieldApiName] = this.firstName;
        FIELDS[CONTACT_LAST_NAME.fieldApiName] = this.lastName;
        FIELDS[CONTACT_EMAIL.fieldApiName] = this.email;
        
        const contactRecord  = {apiName:CONTACT_OBJECT.objectApiName, fields: FIELDS};
        createRecord(contactRecord)
            .then(contact => {
                this.contactId = contact.id;                
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Success',
                        message: 'Contact created. Contact Id: '+this.contactId,
                        variant: 'success',
                    }),
                );
            })
            .catch(error => {
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,//error.body.output.fieldErrors,
                        variant: 'error',
                    }),
                );
            });
    }
}

Here, we have imported createRecord adapter Id from the adapter module uiRecordApi to create Contact Record. Definitely, as per best practice, we have used Salesforce Schema to define field API Name. platformShowToastEvent adapter module has been used to set the toast messages.

We have created a function named handleChange(event) by which we will set the property based on the field name when user will provide the input in the UI.

Now, we have defined the function named “createContact()” where we have defined “createRecord()” standard function from uiRecordAPI to create the Contact Record. In this “createRecord()” standard function, we have passed the Contact Record details as parameter.

Step 4: At last, need to add this LWC into Lightning App/Home or Record Page.

Result

 

 

 

 

 

 

 

 

 

 

 

 

 

14,958 total views, 3 views today

Rating: 4.7/5. From 6 votes.
Please wait...
This entry was posted in Lightning Web Component. Bookmark the permalink.

Leave a Reply