Saturday, October 3, 2020

LWC example : Way to call Apex Imperatively.

Example: Create a LWC component which will call Apex Imperatively with parameters.

Lets take an example like display max 5 Account records and selection of any account record will shows it's child contacts (max 5 contacts).

Note: In this example we will learn the way to call Apex Imperatively.

Solution:

1. Create an apex class with 2 methods, one is responsible to return list 5 of accounts records and another method is responsible to return list of contacts of an account whose id is passed as a parameters and the the list of contact depends on the limit passed as a method parameters.

Both methods should be annotated with @AuraEnable

public with sharing class LWCWireToFunction {
    /**
     * This method is responsible to return 5 accounts.
     */
    @AuraEnabled(cacheable=true)
    public static List<AccountgetListOfAccounts() {
        return [SELECT IdName FROM Account LIMIT 5];
    }

    /**
     * This method is responsible to return contacts of account id passed 
     * as parameter and max number of contacts return depends on the
     * 'lmt' parameters value.
     */
    @AuraEnabled(cacheable=true)
    public static List<ContactgetListOfContacts(String accIdInteger lmt) {
        return [SELECT IdNameEmail FROM Contact WHERE AccountId =:accId LIMIT :lmt];
    }
}

2. Now create a LWC components and the code base will be look like below,

lwcWireToFunctionExample.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>49.0</apiVersion>
    <isExposed>true</isExposed>

    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>   
    </targets>
</LightningComponentBundle>

lwcWireToFunctionExample.js

import { LightningElementtrackwire } from 'lwc';
import getListOfAccounts from '@salesforce/apex/LWCWireToFunction.getListOfAccounts';
import getListOfContacts from '@salesforce/apex/LWCWireToFunction.getListOfContacts';

export default class LwcWireToFunctionExample extends LightningElement {
    @track accItems = [];
    @track accError;
    @track selectedAccount;
    @track conItems = [];
    @track conError;

    //way to call Apex by wire to a function without parameter.
    @wire(getListOfAccountslstOfAccounts({ errordata }) {
        if (data) {
            for(var i=0i<data.lengthi++) {
                this.accItems = [...this.accItems ,{value: data[i].Id , label: data[i].Name}];               
            }
        } else if (error) {
            this.accError = error;
        }
    }

    /**
     * Return list of Accounts.
     */
    get accountOptions() {
        return this.accItems;
    }

    handleChangeOperation(event) {
        this.selectedAccount = event.detail.value;

        //way to call Apex Imperatively
        getListOfContacts({accId:this.selectedAccount.toString(), lmt:'5'})
        .then(result =>{
            this.conItems = result;
        })
        .catch(error =>{
            this.conError = error;
        })
    }
}

lwcWireToFunctionExample.html

<template>
    <lightning-card title="Wire To Function Example"> 
        <lightning-radio-group name="accountGroup"
                          label="Select Accounts to get its contact details:"
                          options={accountOptions}
                          value={selectedAccount}
                          onchange={handleChangeOperation}
                          type="radio">
        </lightning-radio-group>
        <br/>
        <p>Contact details for selected Account::</p>
        <table class="slds-table slds-table_bordered slds-border_left slds-border_right">
            <thead>
                <tr class="slds-text-title_caps">
                    <th scope="col">
                        <div title="hd1">Contact Name</div>
                    </th>
                    <th scope="col">
                        <div title="hd2">Contact Email</div>
                    </th>
                </tr>
            </thead>
            <tbody>
                <template for:each={conItems} for:item="contIns">
                    <tr key={contIns.Name} class="slds-text-title_caps">
                        <td scope="col">
                            <div title="row1col1">{contIns.Name}</div>
                        </td>
                        <td scope="col">
                            <div title="row1col2">{contIns.Email}</div>
                        </td>
                    </tr>
                </template>            
            </tbody>
            </table>
    </lightning-card>
</template>

OUTPUT: Configure the above LWC component under Lightning App Builder and then check the output. The output should be like selection of account will display it's max 5 contacts list.




LWC to LWC Communication using Lightning Messaging Service (Part - 2)

In my previous post ( previous post link ) we have learn how to create a Lightning Messaging Service with 6 steps and today we will use the ...