Saturday, August 3, 2019

How to create record using apex in Lightning Web Components(lwc)

This post explains how to create the record in Lightning Web Components(lwc)

Example

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="number" 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';

// Importing Apex Class method
import saveAccount from '@salesforce/apex/LWCExampleController.saveAccountRecord';

// importing to show toast notifictions
import {ShowToastEvent} from 'lightning/platformShowToastEvent';

// importing Account fields
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);
    }

    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() {
        saveAccount({objAcc: this.accRecord})
        .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 = error.message;
        });
    }
}
Apex Class
public inherited sharing class LWCExampleController {

    @AuraEnabled
    public static void saveAccountRecord(Account objAcc){
        try{
            insert objAcc;
        }
        catch(Exception ex) {
            throw new AuraHandledException(ex.getMessage());
        }
    }
}
Result

4 comments:

  1. Hi I used this and created a LWC for the Case object. However, I want to incorporate picklist fields and right now the form is displaying as free form text boxes. Do you know what to do to render the picklist?

    ReplyDelete
  2. Can you show me how to use this to display picklist fields?

    ReplyDelete
  3. Hi,your example is very helpful and basic. Thanks for this. Can you show in this scenario how to set lookup field value?

    ReplyDelete
  4. What is the need of initializing the object with import fields, you can also set the object with blank ?

    ReplyDelete