Monday, August 5, 2019

How to create a record using Wire service(uiRecordApi) in Lightning Web Component(lwc)

This post explains how to create a record using wire service(uiRecordApi) in Lightning Web Component(lwc).


Example

Import 'lightning/uiRecordApi' scope module in your component.

createRecordInLWC.html
<template>
    <lightning-card title="Create Account Record" icon-name="standard:account">
        <div style="margin-left: 6%" if:true={error}>
            <lightning-badge label={error} style="color: red;"></lightning-badge>
        </div>

        <template if:true={accRecord}>
            <div class="slds-m-around--xx-large">
                <div class="container-fluid">
                    <div class="form-group">
                        <lightning-input label="Enter Account Name" name="accName" required="required" type="text" value={accRecord.Name} onchange={handleNameChange}></lightning-input>
                    </div>
                    <div class="form-group">
                        <lightning-input label="Enter Phone Number" name="accPhone" type="text" value={accRecord.Phone} onchange={handlePhoneChange}></lightning-input>
                    </div>
                    <div class="form-group">
                        <lightning-input label="Enter Account Type" name="accEmail" required="required" type="text" value={accRecord.Type} onchange={handleTypeChange}></lightning-input>
                    </div>
                    <div class="form-group">
                        <lightning-input label="Enter Industry" name="accEmail" type="text" value={accRecord.Industry} onchange={handleIndustryChange}></lightning-input>
                    </div>
                </div>
                <br/>
                <lightning-button label="Submit" onclick={handleSave} variant="brand"></lightning-button>
            </div>
        </template>
    </lightning-card>
</template>
createRecordInLWC.js
import { LightningElement, track} from 'lwc';

// import uiRecordApi to create record
import { createRecord } from 'lightning/uiRecordApi';
// importing to show toast notifictions
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

// importing Account fields
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import Phone_FIELD from '@salesforce/schema/Account.Phone';
import Industry_FIELD from '@salesforce/schema/Account.Industry';
import Type_FIELD from '@salesforce/schema/Account.Type';

export default class CreateRecordInLWC extends LightningElement {
    @track error;

    // this object have record information
    @track accRecord = {
        Name : NAME_FIELD,
        Industry : Industry_FIELD,
        Phone : Phone_FIELD,
        Type : Type_FIELD
    };


    handleNameChange(event) {
        this.accRecord.Name = event.target.value;
        window.console.log('Name ==> '+this.accRecord.Name);
    }

    handlePhoneChange(event) {
        this.accRecord.Phone = event.target.value;
        window.console.log('Phone ==> '+this.accRecord.Phone);
        window.console.log('object ==> '+JSON.stringify(ACCOUNT_OBJECT));
    }

    handleTypeChange(event) {
        this.accRecord.Type = event.target.value;
        window.console.log('Type ==> '+this.accRecord.Type);
    }

    handleIndustryChange(event) {
        this.accRecord.Industry = event.target.value;
        window.console.log('Industry ==> '+this.accRecord.Industry);
    }


    handleSave() {
        const fields = {};

        fields[NAME_FIELD.fieldApiName] = this.accRecord.Name;
        fields[Phone_FIELD.fieldApiName] = this.accRecord.Phone;
        fields[Industry_FIELD.fieldApiName] = this.accRecord.Industry;
        fields[Type_FIELD.fieldApiName] = this.accRecord.Type;
       
        // Creating record using uiRecordApi
        let recordInput = { apiName: ACCOUNT_OBJECT.objectApiName, fields }
        createRecord(recordInput)
        .then(result => {
            // Clear the user enter values
            this.accRecord = {};

            window.console.log('result ===> '+result);
            // Show success messsage
            this.dispatchEvent(new ShowToastEvent({
                title: 'Success!!',
                message: 'Account Created Successfully!!',
                variant: 'success'
            }),);
        })
        .catch(error => {
            this.error = JSON.stringify(error);
        });
    }
}
createRecordInLWC.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="CreateRecordInLWC">
    <apiVersion>46.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
Output

3 comments:

  1. What is the significance of using accRecord array, we can simply create a reactive properties

    ReplyDelete
  2. hi, please how do you create a lightning component form to insert a contact record containing account name, first name, last name, email and all necessary form fields.

    ReplyDelete
  3. hi, please how do you create a lightning component form to insert a contact record containing account name, first name, last name, email and all necessary form fields.

    ReplyDelete