Tuesday, 21 April 2020

How to create a record using apex class from Lightning Web Component

Hi ,

Here we are going to learn how to create a record with apex class from Lightning Web Component.

We have a simple method "createAccount"  which expects "Account" record as parameter.

For video demo . You can watch on my channel  Salesforce Techbook :
https://www.youtube.com/watch?v=31jSRKMaUGQ&list=PL-JzyFWuCbkKcFSOCRlCUk79YbET5QvZC&index=14

Apex Class:

public with sharing class AccountCreationController {
    @AuraEnabled
    public static Account createAccount(Account accountRecObj){
        try{
            insert accountRecObj;
            return accountRecObj;
        }
        catch(Exception ex){
            throw new AuraHandledException(ex.getMessage());

        }
    }
}


Lightning Web Component:

HTML file:
<template>
    <lightning-card>
        <h3 slot="title">
            <lightning-icon icon-name="standard:account" size="small"></lightning-icon>
            Account Creation using Apex Controller
        </h3>
        <div slot="footer">
                <lightning-button label="Create Account" onclick={handleSaveAccount} variant="brand"></lightning-button>                
                <lightning-badge label={accountid}></lightning-badge>
                <lightning-badge label={error}></lightning-badge>

                
        </div>
        <p class="slds-p-horizontal_small">
            <lightning-input type="text" label="Account Name" value={accountRecord.Name} onchange={handleNameChange}></lightning-input>     
            <lightning-input type="text" label="Type" value={accountRecord.Type} onchange={handleTypeChange}></lightning-input>     
            <lightning-input type="text" label="Phone" value={accountRecord.Phone} onchange={handlePhoneChange}></lightning-input>     
        </p>
    </lightning-card>
</template>



Javascript file:

Here we are importing Account Fields and ShowToastEvent through import statement.

Here the track variable "accountRecord" represents the format of the account record and we are assigning values to each key or attribute in accountRecord based  on "onchange" event from HTML file which is on every input element.

createAccount is an identifier for your apex method which is imported via '@salesforce/apex/AccountCreationController.createAccount'

here AccountCreationContoller is an apex class

and createAccount is a method of apex class

import { LightningElement,track } from 'lwc';
import createAccount from '@salesforce/apex/AccountCreationController.createAccount';
import ACCOUNT_NAME from '@salesforce/schema/Account.Name';
import ACCOUNT_TYPE from '@salesforce/schema/Account.Type';
import ACCOUNT_PHONE from '@salesforce/schema/Account.Phone';
import {ShowToastEventfrom 'lightning/platformShowToastEvent';

export default class AccountCreation_Apex extends LightningElement {
 @track accountid;
 @track error;
//Preparation of empty record
 @track accountRecord = {
    Name:ACCOUNT_NAME,
    Type:ACCOUNT_TYPE,
    Phone:ACCOUNT_PHONE
 };
 handleNameChange(event){
     this.accountRecord.Name = event.target.value;
 }
 handleTypeChange(event){
    this.accountRecord.Type = event.target.value;
 }
 handlePhoneChange(event){
    this.accountRecord.Phone = event.target.value;
 }
 handleSaveAccount(){  
//Passigng parameter to method
//Processing the result in then function if it is succcessful
//otherwise process errors in catch block  
    createAccount({accountRecObj:this.accountRecord})
    .then(result=>{    
        this.accountRecord = {};
        this.accountid = result.Id;
        window.console.log(this.accountid);
        const toastEvent = new ShowToastEvent({
            title:'Success!',
            message:'Account Record is created successfullu!',
            variant:'success'
        });
        this.dispatchEvent(toastEvent);
    })
    .catch(error=>{
        this.error = error.message;
    });
 }

}



Meta File:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>
            lightning__AppPage
        </target>
    </targets>
</LightningComponentBundle>




Output:



Reference:
https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.apex

https://www.youtube.com/watch?v=31jSRKMaUGQ&list=PL-JzyFWuCbkKcFSOCRlCUk79YbET5QvZC&index=14





1 comment:

  1. Nice article!
    I found many useful information in your blog, it was awesome to read,thanks for sharing this great content, keep sharing..
    Salesforce Support and Maintenance Services

    Its really an Excellent post.

    ReplyDelete

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...