Apex Calling Methods In Lightning web components
Let’s discuss here how to call the apex class from the Lightning web components. Lightning web components can import methods from Apex classes into the JavaScript classes using ES6 import. 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. 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.
Import Syntax
You can able use default export syntax to import an Apex method via the @salesforce/apex scoped module into JavaScript controller class. The Syntax looks like below.Default
import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';
apexMethod—The imported symbol that identifies the Apex method.
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.
Classname—The name of the Apex class.
Create Apex Class
In this example, we will be getting account data and show it into the UI. Create an apex class using SFDX create apex class command.Default
sfdx force:apex:class:create -n GetAccountData -d force-app/main/default/apex
Here is the apex class. To expose an Apex method to a Lightning web component, the method must be static and either global or public. Annotate the method with @AuraEnabledDefault
public with sharing class GetAccountData {
@AuraEnabled(cacheable=true)
public static List<Account> getAccountList() {
return [SELECT Id, Name,Type,Rating,Phone FROM Account];
}
}
Now you can able to call the apex class in Lightning web component using these different ways.
- Wire a property
- Wire a function
- Call a method imperatively
Wire an Apex Method to a Property
If an Apex method is annotated with @AuraEnabled(Cacheable=true), you can invoke it from a component via the wire service. You can @wire a property or a function. Here is the syntaxDefault
import apexMethod from '@salesforce/apex/Namespace.Classname.apexMethod';
@wire(apexMethod, { apexMethodParams })
propertyOrFunction;
Create a Lightning web component using below SFDX commandsDefault
sfdx force:lightning:component:create --type lwc -n LWCWireEx -d force-app/main/default/lwc
Here is the LWCWireEx.html markup for the lightning web components.Default
<template>
<lightning-card title="Apex Class Example" 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>
</div>
</lightning-card>
</template>
Here is the LWCWireEx.js classDefault
import { LightningElement, wire } from 'lwc';
import getAccountList from '@salesforce/apex/GetAccountData.getAccountList';
export default class LWCWireEx extends LightningElement {
@wire(getAccountList) accounts;
}
Here is the LWCWireEx.js-meta.xml markup.Default
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>45.0</apiVersion>
<isExposed>false</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
Push the changes to scratch org and add the lightning web component to the record page. You can able to see the result like below.
Wire an Apex Method to a Function
Now let’s look at how to wire an apex method to function.we will be updating the same code here to operate the apex method as function.
Update the LWCWireEx.js class as shown belowDefault
import { LightningElement, wire,track } from 'lwc';
import getAccountList from '@salesforce/apex/GetAccountData.getAccountList';
export default class LWCWireEx 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;
}
}
}
update the LWCWireEx.html markup as shown belowDefault
<template>
<lightning-card title="Apex Wire To Function Example" icon-name="custom:custom63">
<div class="slds-m-around_medium">
<template if:true={accounts}>
<ul>
<template for:each={accounts} for:item="account">
<li key={account.Id}> {account.Name} </li>
</template>
</ul>
</template>
<template if:true={error}>
{error}
</template>
</div>
</lightning-card>
</template>
Push the changes to scratch org and add the lightning web component to the record page. You can able to see the result like below.
Call an Apex Method Imperatively
Now let’s see here how to call apex method imperatively. Create a new Lightning web component using the below SFDX commandDefault
sfdx force:lightning:component:create --type lwc -n ImperativEx -d force-app/main/default/lwc
Use the below ImperativEx.html codeDefault
<template>
<lightning-card title="Apex Imperative Method Example">
<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="account">
<p key={account.Id}>{account.Name}</p>
</template>
</template>
<template if:true={error}>
{error}
</template>
</div>
</lightning-card>
</template>
Use the below ImperativEx.js class codeDefault
import { LightningElement, wire,track } from 'lwc';
import getAccountList from '@salesforce/apex/GetAccountData.getAccountList';
export default class ImperativEx extends LightningElement {
@track accounts;
@track error;
handleLoad() {
getAccountList()
.then(result => {
this.accounts = result;
})
.catch(error => {
this.error = error;
});
}
}
Use the below ImperativEx.js-meta.xml class codeDefault
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="hello">
<apiVersion>45.0</apiVersion>
<isExposed>false</isExposed>
<targets>
<target>lightning__RecordPage</target>
</targets>
</LightningComponentBundle>
push the changes to scratch org and add the lightning web component to the record page and you can able to see the below result when you click on the button .
Call an Apex Method with Parameters
Pass parameters values to an Apex method in an object whose properties match the parameters of the Apex method. For example, if the Apex method takes a string parameter, don’t pass a string directly. Instead, pass an object that contains a property whose value is a string.
// apexImperativeMethodWithParams.js
import { LightningElement } from 'lwc';
import findContacts from '@salesforce/apex/ContactController.findContacts';
export default class ApexImperativeMethodWithParams extends LightningElement {
searchKey = '';
contacts;
error;
handleKeyChange(event) {
this.searchKey = event.target.value;
}
handleSearch() {
findContacts({ searchKey: this.searchKey })
.then((result) => {
this.contacts = result;
this.error = undefined;
})
.catch((error) => {
this.error = error;
this.contacts = undefined;
});
}
}
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> findContacts(String searchKey) {
String key = '%' + searchKey + '%';
return [
SELECT Id, Name, Title, Phone, Email, Picture__c
FROM Contact
WHERE Name LIKE :key AND Picture__c != NULL
WITH SECURITY_ENFORCED
LIMIT 10
];
}
}
It’s appropriate time to make some plans for the future and it
is time to be happy. I have read this post and if I could I wish to suggest you
some interesting things or tips. Perhaps you could write next articles referring
to this article. I desire to read more things about it!
It is perfect time to make some plans for the future and it’s time to be happy.
I have read this post and if I could I want to suggest you some interesting things or suggestions.
Perhaps you can write next articles referring to this article.
I wish to read more things about it! Ahaa, its nice conversation on the topic of this post at this
place at this website, I have read all that,
so now me also commenting at this place. http://Nestle.com/
Wow, awesome blog layout! How long have you been blogging for?
you made blogging look easy. The overall look of your
site is excellent, as well as the content!
Just started couple of months ago. Thanks for you kind words!
I am really enjoying the theme/design of your weblog.
Do you ever run into any internet browser compatibility issues?
A number of my blog readers have complained about
my blog not operating correctly in Explorer but looks great in Safari.
Do you have any advice to help fix this problem?
Thanks. No, I haven’t run into any browser issues. I personally recommend use any CSS Framework like bootstrap.
I love the efforts you have put in this,
appreciate it for all the great articles.