Call Apex Methods In Lightning web components

Call Apex Methods In Lightning web components

Lightning web components can import methods from Apex classes into the JavaScript classes. Once after importing the apex class method you can able call the apex methods as functions into the component by calling either via the wire service or imperatively. The Apex Method should be marked with @AuraEnabled. Before you use an Apex method, make sure that there isn’t an easier way to get the data. See whether a base Lightning component, like lightning-record-form, lightning-record-view-form, or lightning-record-edit-form works for your use case. If they don’t give you enough flexibility, use a wire adapter like getListUi or getRecordUi. And if you can’t use a wire adapter, write an Apex method.

In this example, we will query all account records and will display it.

Import Syntax

We need to import the @salesforce/apex scoped module into JavaScript controller class.

import apexMethodName from '@salesforce/apex/Namespace.Classname.apexMethodReference';

Here is list of important point of importing apex method:

  • apexMethodName : An imported symbol that identifies the Apex method.
  • apexMethodReference : The name of the Apex method to import.
  • Classname : The name of the Apex class.
  • Namespace—The namespace of the Salesforce organization. Specify a namespace unless the organization uses the default namespace (c), in which case don’t specify it.

 

Call Apex Methods In Lightning web components Example

Apex class AccountHelper

 
public with sharing class AccountHelper {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name, Type, Rating, Phone 
            FROM Account];
    }
}

We can call the apex class in  Lightning web component using these different ways:

  • Wire a property
  • Wire a function
  • Call a method imperatively

 

Wire a property in lightning Web Component

We can invoke apex method from a component via the wire service. We can @wire a property or a function. Here is the syntax

 
import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';
@wire(apexMethod, { apexMethodParams })
propertyOrFunction;

Lets see example of Wire an Apex Method to a Property

accountListLWC.js

 
import { LightningElement, wire } from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
 
export default class AccountListLWC extends LightningElement {
    @wire(getAccountList) accounts;
}

accountListLWC.html

 
<template>
    <lightning-card title="Account List From Apex" icon-name="custom:custom63">
            <div class="slds-m-around_medium">
                <template if:true={accounts.data}>
                    <template for:each={accounts.data} for:item="acc">
                        <p key={acc.Id}>{acc.Name}</p>
                    </template>
                </template>
                <template if:true={accounts.error}>
                    {accounts.error}
                </template>
            </div>
        </lightning-card>
</template>

accountListLWC.js-meta.xml

 
<?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__HomePage</target>
    </targets>
</LightningComponentBundle>

Now we can add this lwc component on account detail page.

  • Go to Home page
  • Click Setup (Gear Icon) and select Edit Page.
  • Under Custom Components, find your accountListLWC component and drag it on right hand side top.
  • Click Save and activate.

We will have following output.

 

Wire a function in lightning Web Component

We can use same example of showing account list

accountListLWC.js

import { LightningElement, wire,track } from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
 
export default class AccountListLWC extends LightningElement {
    @track accounts;
    @track error;
    @wire(getAccountList)
    wiredAccounts({ error, data }) {
        if (data) {
            this.accounts = data;
        } else if (error) {
            console.log(error);
            this.error = error;
        }
    }
}

accountListLWC.html

 
<template>
    <lightning-card title="Account List using Apex Wire To Function" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <template if:true={accounts}>
                <template for:each={accounts} for:item="acc">
                    <p key={acc.Id}>{acc.Name}</p>
                </template>
            </template>
            <template if:true={error}>
                {error}
            </template>
        </div>
    </lightning-card>
</template>

Call a method imperatively

accountListLWC.js

import { LightningElement, track } from 'lwc';
import getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
export default class AccountListLWC extends LightningElement {
    @track accounts;
    @track error;
    handleLoad() {
        getAccountList()
            .then(result => {
                this.accounts = result;
            })
            .catch(error => {
                this.error = error;
            });
    }
}

accountListLWC.html

<template>
    <lightning-card title="Account List using ApexImperativeMethod" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <p class="slds-m-bottom_small">
                <lightning-button label="Load Accounts" onclick={handleLoad}></lightning-button>
            </p>
            <template if:true={accounts}>
                <template for:each={accounts} for:item="acc">
                    <p key={acc.Id}>{acc.Name}</p>
                </template>
            </template>
            <template if:true={error}>
                {error}
            </template>
        </div>
    </lightning-card>
</template>

Following will be output when you click on Load Account button

Call Apex Methods In LWC Imperative Method

For more detail please refer to official link.

Happy Coding 🙂

Permanent link to this article: https://www.sfdcpoint.com/salesforce/call-apex-methods-in-lightning-web-components/

8 comments

Skip to comment form

    • Saksham on June 26, 2020 at 12:18 pm
    • Reply

    how to call a constructor of a apex class from lwc component .

    1. You can not call constructor of apex class from lwc component. But you can call apex method from lwc constructor. For that you need to create @AuraEnabled and static method.

    • Neha on August 23, 2020 at 1:10 pm
    • Reply

    I have a batch job with constructor. Since we can not call a constructor directly, can we create a method and call constructor via that method?

    • Guest Admin on October 15, 2020 at 4:06 pm
    • Reply

    How to call the 2 methods of single apex class into LWC

      • Mounika Atmakuri on March 9, 2022 at 12:56 pm
      • Reply

      you can write 2 import methods for that like

      import getAccountList from ‘@salesforce/apex/AccountHelper.getAccountList’;
      import relatedAccountList from ‘@salesforce/apex/AccountHelper.getRelatedAccountList’;

    • jamal_dt on May 4, 2021 at 7:59 am
    • Reply

    What about the others object fields?

    • Vineesh on July 8, 2021 at 8:03 pm
    • Reply

    Hi Ankush,

    I am sending the record id on Load to the apex controller to check if the opportunity product exists or not. If not I show the pop up modal window. This piece of code works fine for sysadmin but not for other users. All of them have access to the fields too. Any insights pls ?

    import { LightningElement,track,api,wire } from ‘lwc’;
    import checkOppProductAdded from ‘@salesforce/apex/OpportunityFieldUpdater.checkOppProductAdded’;

    export default class ModalPopupLWC extends LightningElement {
    //Boolean tracked variable to indicate if modal is open or not default value is false as modal is closed when page is loaded
    @track isModalOpen = false;
    @track error;
    @api recordId;
    openModal() {
    // to open modal set isModalOpen tarck value as true
    this.isModalOpen = true;
    }
    closeModal() {
    // to close modal set isModalOpen tarck value as false
    this.isModalOpen = false;
    }
    submitDetails() {
    // to close modal set isModalOpen tarck value as false
    //Add your code to call apex method or do some processing
    this.isModalOpen = false;
    }

    @wire(checkOppProductAdded, {recordId:’$recordId’})
    checkOppProducts({error, data}){
    if(data){
    if(data === ‘yes’){
    this.isModalOpen = true;
    }else{
    this.isModalOpen = false;
    }
    this.error = undefined;
    }
    else{
    this.error = error;
    this.isModalOpen = undefined;
    }
    }

    }

    • SFDC Developer on August 14, 2021 at 10:13 pm
    • Reply

    handleLoad() {
    getAccountList()
    .then(result => {
    this.accounts = result;
    })
    .catch(error => {
    this.error = error;
    });
    console.log(this.accounts) –> Getting value as undefined
    }
    }
    Can you help me?

Leave a Reply

Your email address will not be published.