Create Record Through LWC

Hi Friends . This is my first post on LWC. So today we will discuss 2 different way of creating record through LWC.

1.Creating Form and Save Controller .

template.html

<template>
    <lightning-card title="Create Account" icon-name="standard:account">
            <div class="slds-p-around_x-small">
                <div class="slds-p-around_medium lwc-bg">
                    <lightning-input type="text" label="Name" value={rec.Name} onchange={handleNameChange} required></lightning-input>
                </div>
                
                <div class="slds-p-around_medium lwc-bg">
                    <template if:true={TypePicklistValues.data}>
                        <lightning-combobox name="progress"
                                            label="Type"
                                            value={rec.Type}
                                            placeholder="-Select-"
                                            options={TypePicklistValues.data.values}
                                            onchange={handleChangeType} >
                        </lightning-combobox>
                    </template>
                </div>
                <div class="slds-p-around_medium lwc-bg">
                    <lightning-input type="url" label="Website" value={rec.Website} onchange={handleURLChange}></lightning-input>
                </div>
                <div class="slds-p-around_medium lwc-bg">
                    <lightning-input type="date" label="SLA Expiration Date " value={rec.SLAExpirationDate__c} onchange={handleSLADAteChange} required></lightning-input>
                </div>
                <div class="slds-p-around_medium lwc-bg">
                    <lightning-input type="checkbox" label="Active" value={rec.IsActive__c} onchange={handleActiveChnage}></lightning-input>
                </div>
                <div class="slds-p-around_medium lwc-bg">
                    <template if:true={SLAPicklistValues.data}>
                        <lightning-combobox name="progress"
                                            label="SLA"
                                            value={rec.SLA__c}
                                            placeholder="-Select-"
                                            options={SLAPicklistValues.data.values}
                                            onchange={handleSLAType} >
                        </lightning-combobox>
                    </template>
                </div>
                <div class="slds-p-around_medium lwc-bg">
                    <br/>
                </div>
                <div class="slds-p-around_medium lwc-bg">
                    <lightning-button label="Save" onclick={handleClick}></lightning-button>
                </div>
                
                
            </div>
        </lightning-card>
</template>

template.js

/* eslint-disable no-console */
import { LightningElement, wire, track } from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import TYPE_FIELD from '@salesforce/schema/Account.Type';
import WEBSITE_FIELD from '@salesforce/schema/Account.Website';
import SLA_FIELD from '@salesforce/schema/Account.SLA__c';
import SLA_EXP_FIELD from '@salesforce/schema/Account.SLAExpirationDate__c';
import ACTIVE_FIELD from '@salesforce/schema/Account.IsActive__c';
import createAccount from '@salesforce/apex/createAccountController.createAccount';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class template extends LightningElement {
    @track name = NAME_FIELD;
    @track type = TYPE_FIELD;
    @track website = WEBSITE_FIELD;
    @track sla = SLA_FIELD;
    @track slaExpDate = SLA_EXP_FIELD;
    @track active = ACTIVE_FIELD;

    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    objectInfo;

    @wire(getPicklistValues, { recordTypeId: '$objectInfo.data.defaultRecordTypeId', fieldApiName: TYPE_FIELD})
    TypePicklistValues;

    @wire(getPicklistValues, { recordTypeId: '$objectInfo.data.defaultRecordTypeId', fieldApiName: SLA_FIELD})
    SLAPicklistValues;
    rec = {
        Name : this.name,
        Type : this.type,
        Website : this.website,
        SLA__c : this.sla,
        SLAExpirationDate__c : this.slaExpDate,
        IsActive__c : this.active
    }
    
    handleNameChange(event) {
        this.rec.Name = event.target.value;
    }
    handleURLChange(event) {
        this.rec.Website = event.target.value;
    }
    handleSLADAteChange(event) {
        this.rec.SLAExpirationDate__c = event.target.value;
    }
    handleActiveChnage(event) {
        this.rec.IsActive__c = event.target.checked;
    }
    handleChangeType(event){
        this.rec.Type = event.target.value;
    }
    handleSLAType(event){
        this.rec.SLA__c = event.target.value;
    }
    handleClick() {
        createAccount({ acc : this.rec })
            .then(result => {
                this.message = result;
                this.error = undefined;
                if(this.message !== undefined) {
                    this.rec.Name = '';
                    this.rec.Type = '';
                    this.rec.Website = '';
                    this.rec.SLA__c = '';
                    this.rec.SLAExpirationDate__c = '';
                    this.rec.IsActive__c = '';
                    this.dispatchEvent(
                        new ShowToastEvent({
                            title: 'Success',
                            message: 'Account created',
                            variant: 'success',
                        }),
                    );
                }
                window.location.reload();
            })
            .catch(error => {
                this.message = undefined;
                this.error = error;
                this.dispatchEvent(
                    new ShowToastEvent({
                        title: 'Error creating record',
                        message: error.body.message,
                        variant: 'error',
                    }),
                );
            });
           
    }
}

Using Query Selector instead of fetching input through onchange

Changes in Input Field:

<div class="slds-p-around_medium lwc-bg">
     <lightning-input class="input" type="text" label="Name" value={rec.Name}> . 
      </lightning-input>
</div>

Changes in JS CODE:

import { LightningElement, track } from 'lwc';
export default class template extends LightningElement {
    @track name;
    handleClick(event)
    {
        console.log(event.target.label);
        var input=this.template.querySelector("lightning-input");
        this.name=input.value;
        console.log(input.value);
    }
}

If we have multiple input statement then we can use.
var input =this.template.querySelectorAll(".input");
Where .input refers to class in HTML file.

template.css :

You can add the css file to component bundle by creating new file with same name.

.lwc-bg {
    background-color: rgb(242, 242, 242);
}

2. Create Record Using Record Form :

template.html

<lightning-record-form
        object-api-name={objectApiName}
        fields={fields}
        onsuccess={handleSuccess}>
</lightning-record-form>

template.js :

import { LightningElement, api } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import REVENUE_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import INDUSTRY_FIELD from '@salesforce/schema/Contact.Industry';

export default class template extends LightningElement {
    
    objectApiName = ACCOUNT_OBJECT;
    fields = [NAME_FIELD, REVENUE_FIELD, INDUSTRY_FIELD];

    handleSuccess(event) {
        const evt = new ShowToastEvent({
            title: "Account created",
            message: "Record ID: " + event.detail.id,
            variant: "success"
        });
        this.dispatchEvent(evt);
    }
}

Thanks for reading and please do share the feedback.

One thought on “Create Record Through LWC

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s