Tuesday 18 December 2018

How to call an Apex class from a Lightning Web component (#LWC) | Invoke Apex Controller from Lightning Web Component | imperatively



Welcome in Lightning Web Components world. Last time we talk about how to create first Lightning Web Component and how to configure VsCode with Salesforce CLI.

We know how to Invoke Apex Class from lightning Component. So Today we will talk about how to invoke apex class from Lightning Web Component.

Finally get some time to play with LWC. Let see how to create LWC to Search a Account Record.

Step 1) Create Apex Class to Search Record.
 
public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> findAccounts(String searchKey) {
        String key = '%' + searchKey + '%';
        return [SELECT Id, Name, AccountNumber FROM Account WHERE Name LIKE :key  LIMIT 10];
    }
}
Create on Apex Class with @AuraEnabled annotation and method must be static.

Step 2) Create Lightning Web Component in VsCode. IF you don't know how check here.

SearchAccountRecord.html
<template>
    <lightning-card title="Search Account" icon-name="custom:custom57">
        <div class="slds-m-around_medium">
            <lightning-input type="search" onchange={handleKeyChange} class="slds-m-bottom_small" label="Search"></lightning-input>
            <template if:true={accounts}>
                <template for:each={accounts} for:item="acc">
                    <li key={acc.Id}>
                        {acc.Name}
                        {acc.AccountNumber}
                    </li>
                </template>
            </template>
        </div>
    </lightning-card>
</template>
  • <lightning-input is replacement of lightning:input in .
  • <template if:true is used for checking if condition.
  • <template for:each for Iteration.


SearchAccountRecord.js
import { LightningElement, track } from 'lwc';
import findAccounts from '@salesforce/apex/AccountController.findAccounts';

/** The delay used when debouncing event handlers before invoking Apex. */
const DELAY = 350;

export default class SearchAccountRecord extends LightningElement {
    @track accounts;
    @track error;
    handleKeyChange(event) {
        // Debouncing this method: Do not actually invoke the Apex call as long as this function is
        // being called within a delay of DELAY. This is to avoid a very large number of Apex method calls.
        window.clearTimeout(this.delayTimeout);
        const searchKey = event.target.value;
        // eslint-disable-next-line @lwc/lwc/no-async-operation
        this.delayTimeout = setTimeout(() => {
            findAccounts({ searchKey })
                .then(result => {
                    this.accounts = result;
                    this.error = undefined;
                })
                .catch(error => {
                    this.error = error;
                    this.accounts = undefined;
                });
        }, DELAY);
    }
}
  • "import findAccounts from '@salesforce/apex/AccountController.findAccounts'" is used to get apex class.


SearchAccountRecord.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="SearchAccountRecord">
     <apiVersion>45.0</apiVersion>
    <isExposed>false</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>
  • <targets> is used to to mention where we can use this LWC component
Output :-




Feel Free to share your feedback. I know we can do lots of improvement in this code. I hope this is not a bad start :)


Related Post :-
1) Create First Lightning Wed Component.
2) Developer Tools for Lightning Web Components.
3) Introducing Lightning Web Components.



Thanks,
Amit Chaudhary
amit.salesforce21@gmail.com

5 comments:

  1. How constructor will executive in lwc.........

    ReplyDelete
  2. i want to get the data from server and i have to display the data in component it has to work when componenet is loaded how to achive this

    ReplyDelete
  3. Thanks a lot Amit, very helpful.

    ReplyDelete
  4. how to call the constructor in lwc

    ReplyDelete