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/

2 comments

    • 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.

Leave a Reply

Your email address will not be published.