Friday 27 March 2020

Wire an Apex Method with a Dynamic Parameter (Account Search)

Hi,

Here we are going to learn how to pass a parameter to an apex method using wire.

The following method takes a parameter "searchKey".

Apex Class:

public with sharing class AccountSearchCls { @AuraEnabled(cacheable=true) public static List<Account> findAccounts(String searchKey) { String key = '%' + searchKey + '%'; return [ SELECT Id, Name FROM Account WHERE Name LIKE :key LIMIT 10 ]; } }


Now let's see how our Lightning Web Component looks like and how can we pass parameter value to apex class:
The component’s JavaScript prefaces the value of the searchKey parameter with $ to indicate that it’s dynamic and reactive. 
It references a property of the component instance. If its value changes, the template rerenders.


AccountSearchLWC.JS

import { LightningElement,wire } from 'lwc';
import findAccounts from '@salesforce/apex/AccountSearchCls.findAccounts';
/** The delay used when debouncing event handlers before invoking Apex. */
const DELAY = 300;
export default class AccountSearchLWC extends LightningElement {
    searchKey = '';

    @wire(findAccounts, { searchKey: '$searchKey' })
    accounts;
    handleKeyChange(event) {
        // Debouncing this method: Do not update the reactive property 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;
        this.delayTimeout = setTimeout(() => {
            this.searchKey = searchKey;
        }, DELAY);
    }
}

AccountSearchLWC.HTML

<template>
    <lightning-card title="accountSearch" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <lightning-input type="search" onchange={handleKeyChange} class="slds-m-bottom_small" label="Search" value={searchKey}></lightning-input>
            <template if:true={accounts.data}>
                <template for:each={accounts.data} for:item="account">
                    <p key={account.Id}>{account.Name}</p>
                </template>
            </template>           
        </div>
    </lightning-card>
</template>

AccountSearchLWC.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__Tab</target>
    </targets>
</LightningComponentBundle>


Output:


Reference:


No comments:

Post a Comment

How to include a screen flow in a Lightning Web Component

 Hi, Assume  you have a flow called "Quick Contact Creation" and API Name for the same is "Quick_Contact_Creation". To i...