A Step-by-Step Guide to Inserting an Account Record Using Apex in Salesforce Lightning Web Components (LWC)

 How to Insert a Record of Account Object Using Apex Class in Salesforce Lightning Web Component-LWC

In this blog post, we will walk you through the process of creating an Account record in Salesforce using an Apex class and a Lightning Web Component (LWC). We will cover everything from setting up the Apex controller to building the LWC and integrating the two. By the end of this tutorial, you'll be able to insert an Account record with ease. Step 1: Create the Apex Controller First, we need to create an Apex class that will handle the insertion of the Account record. This class will be shared across different parts of the application and will be accessible from our Lightning Web Component.

Apex Controller Code


// Define a public class named lwcApexController that can be shared with other parts of the application





public with sharing class lwcApexController {


   // Annotate the method to make it accessible from Aura components and Lightning Web Components

   @AuraEnabled

   // Define a public static method named insertAccountMethod that takes an Account object as a parameter

   public static Account insertAccountMethod(Account accountObj) {

       try {

           // Attempt to insert the provided Account object into the database

           insert accountObj;

           // If successful, return the inserted Account object

           return accountObj;

       } catch (Exception exp) {

           // If an exception occurs, throw a new AuraHandledException with the exception's message

           throw new AuraHandledException(exp.getMessage());

       }

   }

}

HTML

**********************************************************************************

<template>

<lightning-card  >

     <div slot="title">

          <h3> 

         <lightning-icon icon-name="standard:account" size="small"></lightning-icon> Create an Account Using Apex Controller           

      </h3>

     </div>

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

    <lightning-input type="text" label="Name" value={getAccountRecord.Name} onchange={nameInpChange}></lightning-input>

   </p>

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

    <lightning-input type="text" label="Phone" value={getAccountRecord.Phone} onchange={phoneInpChange}></lightning-input>

   </p>


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

     <lightning-input type="text" label="Type" value={getAccountRecord.Type} onchange={typeInpChange}></lightning-input>

    </p>


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

     <lightning-input type="text" label="Website" value={getAccountRecord.Website} onchange={websiteInpChange}></lightning-input>

    </p>

      


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

     <lightning-input type="text" label="Account Site" value={getAccountRecord.Site} onchange={accSiteChange}></lightning-input>       

    </p> 

    

  <div slot="footer">

    <lightning-button label="Submit" onclick={saveAccountAction} variant="brand"></lightning-button>

  </div>





</lightning-card>

</template>

JS....

***********************************************************************************

import { LightningElement,track } from 'lwc';

import insertAccountMethod from '@salesforce/apex/lwcApexController.insertAccountMethod';

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

import accPhone from '@salesforce/schema/Account.Phone';

import accType from '@salesforce/schema/Account.Type';

import accWebsite from '@salesforce/schema/Account.Website';

import accSite from '@salesforce/schema/Account.Site';


import {ShowToastEvent} from 'lightning/platformShowToastEvent';


export default class InsertAccountLwc extends LightningElement {

   @track accountid;

   @track error;    

   @track getAccountRecord={

       Name:accName,       

       Phone:accPhone,  

       Type:accType, 

       Website:accWebsite,         

       Site:accSite

             

   };   


  

   nameInpChange(event){

      this.getAccountRecord.Name = event.target.value;

      window.console.log(this.getAccountRecord.Name);

    }


    phoneInpChange(event){

      this.getAccountRecord.Phone = event.target.value;

      window.console.log(this.getAccountRecord.Phone);

   }

   

    typeInpChange(event){

       this.getAccountRecord.Type = event.target.value;

       window.console.log(this.getAccountRecord.Type);

     }


     websiteInpChange(event){

       this.getAccountRecord.Website = event.target.value;

       window.console.log(this.getAccountRecord.Type);

     }


     accSiteChange(event){

       this.getAccountRecord.Site = event.target.value;

       window.console.log(this.getAccountRecord.Type);

     }

         

   

     saveAccountAction(){

       window.console.log('before save' + this.createAccount);

       insertAccountMethod({accountObj:this.getAccountRecord})

       .then(result=>{

         window.console.log(this.createAccount);

           this.getAccountRecord={};

           this.accountid=result.Id;

           window.console.log('after save' + this.accountid);

           

           const toastEvent = new ShowToastEvent({

             title:'Success!',

             message:'Account created successfully',

             variant:'success'

           });

           this.dispatchEvent(toastEvent);

       })

       .catch(error=>{

          this.error=error.message;

          window.console.log(this.error);

       });

     }

   

   

   }




Detailed Explanation:
HTML Template:

We create a lightning-card to hold our form.
The form includes input fields for Account Name, Phone, Type, Website, and Site.
Each input field is bound to a property of getAccountRecord and has an onchange handler.
A submit button is provided to trigger the save operation.
JavaScript Controller:

We import necessary modules, including our Apex method.
We define a tracked property getAccountRecord to hold the form data.
Change handlers update getAccountRecord properties as the user inputs data.
The saveAccountAction method calls insertAccountMethod, passing getAccountRecord.
On success, it clears the form and shows a success toast message.
On error, it logs the error message.
Conclusion
By following these steps, you can create an LWC that inserts an

Account record using an Apex controller in Salesforce. This setup allows for a clean separation of concerns, with the LWC handling the user interface and the Apex controller managing database operations.

Here’s a summary of the key points covered in this tutorial:

Apex Controller:

We created a class lwcApexController with a method insertAccountMethod that inserts an Account record into Salesforce.
We used the @AuraEnabled annotation to make the method accessible from LWC.
Proper error handling was implemented using try-catch blocks and AuraHandledException.
Lightning Web Component:

The HTML template was set up with a form for entering Account details.
We created input fields for various Account properties and a submit button to trigger the save operation.
The JavaScript controller managed form data binding, input change handling, and communication with the Apex controller.
We displayed success messages using ShowToastEvent.
With this approach, you can efficiently create, read, update, and delete (CRUD) records in Salesforce using LWCs and Apex controllers. This integration ensures a smooth user experience and leverages the powerful capabilities of Salesforce’s backend services.

Feel free to customize and expand on this example to suit your specific needs and business logic. Happy coding!






Comments

Popular posts from this blog

Integrating Salesforce with Google Drive for File Uploads

Building a Real-Time Train Status Tracker with Salesforce LWC and Apex