Lightning

Calling Apex Method with Parameters from a Lightning Web Component

There will be ample scenarios where a developer must customize things in salesforce to meet the business requirement. Customization in Lightning Web Component (LWC) can be done in multiple ways based on requirement. One is using lightning-record-edit-form and lightning-record-form. With these developers will have very minimal control over the component. Another way is by calling a server-side method. With this, developers will have good control over the component and can achieve complex business requirement. In this blog we will see how we can call a server Apex Method with parameters from an LWC JavaScript(.JS) file.

There are few things to note when you want to call an apex method.

  1. Importing the Server-side method (apex class).
  2. Calling a Server-side method from JS method.
  3. Fetching the value that is returned.

Public class C_Sample_Class{
                 
                 // In this example we will see
                 // A method to create a contact record 
                 // with 3 parameters
                 // Returning Id of record.
                 @AuraEnabled
                 Public static Id m_Insert_A_Contact_Record(String a_First_Name, String a_Last_Name, String a_Email){
                 
                                 try{
                                                 Contact a_Rec = new Contact();
                                 
                                                 a_Rec.FirstName = a_First_Name;
                                                 a_Rec.LastName = a_Last_Name;
                                                 a_Rec.Email = a_Email;
                                 
                                                 Insert a_Rec;
                                                 return a_Rec.Id;
                                 }
                                 catch(Exception ex){
                                                 System.debug('An Exception: '+ex);
                                                 return null;
                                 }
                 }
 } 

Now for this example I have used color code for Class, methods, parameters and Lightning import references for better understanding. We will see how we can write an LWC component to display list of records and a form to create a new record.

Before that, we will see syntax and basic things that is required in below development.

Importing an apex class and creating a reference.

import { LightningElement, api, wire, track } from 'lwc';

This is required for to create @api, @wire and @track reference variables.

Import a_Method_Ref from ‘@salesforce/apex/NameSpace.Apex_Class_Name.Apex_Method_Name’;

This will create reference of a apex method that is used.

import { ShowToastEvent } from 'lightning/platformShowToastEvent';

This will show a toast message on success or on error.


One advantage in LWC is we need not specify any specific controller. Any apex class and method can be referenced. In Visualforce pages or Lightning Aura Component We need to specify Controller in the page itself. Here it is not the case, any apex class and method can be used in one simple page.

“sample_Customization_Demo.html”

<template>
     <div class="slds-box slds-theme_default">
         <div class="slds-p-around_medium lgc-bg">
             <lightning-input type="text" 
                 label="Enter First Name" 
                 value={First_Name} 
                 onchange={handle_First_Name_Change}>
             </lightning-input>
         </div>
         <div class="slds-p-around_medium lgc-bg">
             <lightning-input type="text" 
                 label="Enter Last Name" 
                 value={Last_Name} 
                 onchange={handle_Last_Name_Change} required>
             </lightning-input>
         </div>
         <div class="slds-p-around_medium lgc-bg">
             <lightning-input type="email" 
                 label="Enter Email" 
                 value={Contact_Email} 
                 onchange={handle_Email_Change}>
             </lightning-input>
         </div> 
         <div class="slds-p-around_medium lgc-bg">
             <lightning-button label="Submit" 
                 onclick={handle_Submit}>
             </lightning-button>
         </div>
     </div>
 </template> 

“sample_Customization_Demo.js”

import { 
     LightningElement,
     api,
     wire,
     track 
 } from 'lwc';

 // import apex method
 import Apex_Method_One_Ref from "@salesforce/apex/C_Sample_Class.m_Insert_A_Contact_Record";
  
 // import standard toast event
 import { ShowToastEvent } from 'lightning/platformShowToastEvent';
  
 export default class Sample_Customization_Demo extends LightningElement {
     @api a_First_Name_Ref;
     @api a_Last_Name_Ref;
     @api a_Email_Ref;
  
     handle_First_Name_Change(event) {
         this.a_First_Name_Ref = event.detail.value;
     }
  
     handle_Last_Name_Change(event) {
         this.a_Last_Name_Ref = event.detail.value;
     }
  
     handle_Email_Change(event) {
         this.a_Email_Ref = event.detail.value;
     }
  
     handle_Submit(event){
         // Refering to first method and passwing parameters.
         // Note: a_First_Name, a_Last_Name and a_Email are parameters for the method.
         // all Ref variables are @api references.  
         
         Apex_Method_One_Ref({ 
             a_First_Name : this.a_First_Name_Ref, 
             a_Last_Name : this.a_Last_Name_Ref, 
             a_Email : this.a_Email_Ref
         })
         .then(result => {
             const event = new ShowToastEvent({
                 title: 'Contact created',
                 message: 'New Contact '+ this.a_First_Name_Ref +' '+ this.a_Last_Name_Ref +' created.',
                 variant: 'success'
             });
             this.dispatchEvent(event);
         })
         .catch(error => {
             const event = new ShowToastEvent({
                 title : 'Error',
                 message : 'Error creating contact. Please Contact System Admin',
                 variant : 'error'
             });
             this.dispatchEvent(event);
         });
     }
 } 

‘sample_Customization_Demo.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>
         <target>lightning__AppPage</target>
         <target>lightning__HomePage</target>
     </targets>
 </LightningComponentBundle> 

If you see the code in JS file, The handle_Submit method where the code is written which will call a apex method and returns result or catches error.

Apex_Method_One_Ref({ 
            a_First_Name : this.a_First_Name_Ref, 
            a_Last_Name : this.a_Last_Name_Ref, 
            a_Email : this.a_Email_Ref
        })
        .then(result => {
            const event = new ShowToastEvent({
                title: 'Contact created',
                message: 'New Contact '+ this.a_First_Name_Ref +' '+ this.a_Last_Name_Ref +' created.',
                variant: 'success'
            });
            this.dispatchEvent(event);
        })
        .catch(error => {
            const event = new ShowToastEvent({
                title : 'Error',
                message : 'Error creating contact. Please Contact System Admin',
                variant : 'error'
            });
            this.dispatchEvent(event);
        });

We have created a reference at top.

import Apex_Method_One_Ref from "@salesforce/apex/C_Sample_Class.m_Insert_A_Contact_Record";

Apex_Method_One_Ref is a reference to C_Sample_Class class’s m_Insert_A_Contact_Record method.

And this method has 3 parameters namely a_First_Name, a_Last_Name and a_Email and value to these parameters is passed as,

Apex_Method_One_Ref({ 
            a_First_Name : this.a_First_Name_Ref, 
            a_Last_Name : this.a_Last_Name_Ref, 
            a_Email : this.a_Email_Ref
        })

When a method is executed, the result can be a success or failure as mentioned below.

For success we can use

.then(result => { 
	// Post Success code.
	// result variable will have JSON format data that is returned from Apex
 });

For any error we can use

.catch(error => {
	// Post error code.
	// error variable will have JSON format data that is returned from Apex
});

Output of the code will be something like this.

Input form

When user click on the submit button. You will get a success message.

LWC added in home page and you can see Success Message once record is saved.

We can see the record is create and detail vide of the record.

Record detail page of contact that is saved.

Note:

  • You need not mention any apex controller in Lightning web component.
  • You can use the same LWC in different sections, like Home page, Record page, App page etc.you just need to mention it in Target section of meta.xml file.
  • Always use both success and error section when writing code to handle both scenarios.
  • Try to use lightning specific tags which is given in Lightning Design System.
  • Use Try and Catch block in apex CRUD operation.

Calling an Apex class from Lightning Web Component.

Invoke Apex class from Lightning Web Component.

Call Apex Methods in Lightning Web Component.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

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

Google photo

You are commenting using your Google 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