Sunday, February 28, 2021

How to use createRecord(recordInput) in LWC?

In this blog post we will learn "How to create record using lightning/uiRecordApi"?

Let's understand with simple example as explained below:

createRecordExampleLwc.html

<template>

    <lightning-card  title="Create Account">

        <p class="slds-p-horizontal_small">

            <lightning-input type="text" label="Enter Account name" onchange={handleAccName}></lightning-input>

        </p>

        <p slot="footer"> <lightning-button label="Create Account"  onclick={createAccount}></lightning-button></p>

      

</lightning-card>

</template>


createRecordExampleLwc.js

import { LightningElement } from 'lwc';

import { createRecord } from 'lightning/uiRecordApi';

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

import ACCOUNT_NAME from '@salesforce/schema/Account.Name';

export default class CreateRecordExampleLwc extends LightningElement {

 

    accName;

    handleAccName(event){

    this.accName=event.target.value;

    }

    createAccount(){

        var fields ={'Name' : this.accName};

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

        createRecord(accRecord)

        .then( response => {

            alert('Account Inserted and Id is'+response.id);

        })

        .catch( error =>   {

        alert('Some error occured'+JSON.stringify(error));

        });

 

    }

}


createRecordExampleLwc.js-meta.xml

<?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__RecordPage</target>

    </targets>

</LightningComponentBundle>



Output:

How to use createRecord(recordInput) in LWC?


How to use createRecord(recordInput) in LWC?

No comments:

Post a Comment