Friday, December 16, 2022

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.

1
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

1
2
3
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


No comments:

Post a Comment

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC)

Understanding Wire vs Imperative Apex Method Calls in Salesforce Lightning Web Components (LWC) Introduction: Salesforce Lightning Web ...