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 example : Way to call Apex by wire to a function with/without parameter(s).

Example: Create a LWC component which will call Apex method with parameters using wire service.

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 by wire to a function with/without parameter(s).

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 @AuraEnabled.

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 by wire to a function with parameters
    @wire
    (getListOfContacts, { accId'$selectedAccount'lmt:'5'}) listOfContacts({ errordata }) {
        if (data) {
            this.conItems = data;
        } else if (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.




Friday, October 2, 2020

How to write IF ELSE condition under LWC .html file:

Below is the block of code to use If/Else condition under LWC UI (.html file). Condition variable you can defined under .js file.

<!-- If Condition-->
    <template if:true={your_Variable_defined_in_JS}>
        <!-- Put your UI logic here. -->
    </template>
    <!-- Else Condition-->
    <template if:false={your_Variable_defined_in_JS}>
        <!-- Put your UI logic here. -->
    </template>


LWC Table Example With Dynamic Values:

 Example:

Create a table in LWC which will display 2 columns (Object Label and Object API) table and now of rows will display based on numbers of objects available under the testing Org.

Solutions:

1. First create an Apex class named as LWCTableExamplController and under this class create a method named as getListOfObjDetails()  which will return list of object details. Copy paste the below code base,

public with sharing class LWCTableExamplController {
    @AuraEnabled(cacheable=true)
    public static List<ObjectDetailsWrappergetListOfObjDetails() {
        Map<StringSObjectTypemapOfObjs = schema.getGlobalDescribe();
        if(mapOfObjs != null && mapOfObjs.keySet() != null) {
            List<ObjectDetailsWrapperlstOfObjWrapper = new List<ObjectDetailsWrapper>();

            for(String keymapOfObjs.keySet()) {
                ObjectDetailsWrapper objWrapInst = new ObjectDetailsWrapper();
                if(mapOfObjs.get(key) != null && mapOfObjs.get(key).getDescribe() != null)
                    objWrapInst.objLabel = mapOfObjs.get(key).getDescribe().getLabel();
                objWrapInst.objAPI = key;

                lstOfObjWrapper.add(objWrapInst);
            }

            return lstOfObjWrapper;
        }
        return null;
    }

    public class ObjectDetailsWrapper {
        @AuraEnabled
        public String objLabel;
        @AuraEnabled
        public String objAPI;
    }
}

2. Now Create a Lightning Web Component named as "lwcTableExample". System will automatically create 3 files (lwcTableExample.html, lwcTableExample.js, lwcTableExample.js-meta.xml) under "lwc" folder (default location).

3. Copy paste the below line of code for lwcTableExample.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>

4. Copy paste the below line of code for lwcTableExample.js
import { LightningElementwire } from 'lwc';
import getListOfObjDetails from '@salesforce/apex/LWCTableExamplController.getListOfObjDetails';
export default class LwcTableExample extends LightningElement {
    @wire
    (getListOfObjDetailslistOfObjectDetails;
}

5. Copy paste the below line of code for lwcTableExample.html
<template>
    <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">Object Label</div>
                </th>
                <th scope="col">
                    <div title="hd2">Object API</div>
                </th>
            </tr>
        </thead>
        <tbody>
            <template for:each={listOfObjectDetails.data} for:item="objIns">
                <tr key={objIns.objAPI} class="slds-text-title_caps">
                    <td scope="col">
                        <div title="row1col1">{objIns.objLabel}</div>
                    </td>
                    <td scope="col">
                        <div title="row1col2">{objIns.objAPI}</div>
                    </td>
                </tr>
            </template>            
        </tbody>
    </table>
</template>

6. Now create a Lightning App Builder and assign this component and from then check the output and it will look like below,


LWC Table Example With Static Values:

 Example:

Create a LWC components with static headers, rows and columns values.


Solutions:

1. Create a Lightning Web Component named as "lwcTableExample". System will automatically create 3 files (lwcTableExample.html, lwcTableExample.js, lwcTableExample.js-meta.xml) under "lwc" folder (default location).


2. Copy paste the below line of code for lwcTableExample.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>

3. Copy paste the below line of code for lwcTableExample.html
<template>
    <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">Header 1</div>
                </th>
                <th scope="col">
                    <div title="hd2">Header 2</div>
                </th>
                <th scope="col">
                    <div title="hd3">Header 3</div>
                </th>
            </tr>
        </thead>
        <tbody>
            <tr class="slds-text-title_caps">
                <td scope="col">
                    <div title="row1col1">Row1 Col1</div>
                </td>
                <td scope="col">
                    <div title="row1col2">Row1 Col2</div>
                </td>
                <td scope="col">
                    <div title="row1col3">Row1 Col3</div>
                </td>
            </tr>
            <tr class="slds-text-title_caps">
                <td scope="col">
                    <div title="row2col1">Row2 Col1</div>
                </td>
                <td scope="col">
                    <div title="row2col2">Row2 Col2</div>
                </td>
                <td scope="col">
                    <div title="row2col3">Row2 Col3</div>
                </td>
            </tr>
            <tr class="slds-text-title_caps">
                <td scope="col">
                    <div title="row3col1">Row3 Col1</div>
                </td>
                <td scope="col">
                    <div title="row3col2">Row3 Col2</div>
                </td>
                <td scope="col">
                    <div title="row3col3">Row3 Col3</div>
                </td>
            </tr>
        </tbody>
    </table>
</template>

4. As I am showing this example with static value, so no change is required for file lwcTableExample.js

5. Now create a Lightning App Builder and assign this component and from then check the output and it will look like below,


LWC checkbox-group Example:

 Scenario: 

Create a checkbox-group in LWC which will display list of Object with CHECK-BOX selection in your ORG.

Solution:
Check combobox example in my previous post (LWC combobox Example:) and create LWC component and it's controller class same as describe on that post. Once done just modify the full .html file with below line of codes,
<template>
    <lightning-card title="checkbox-group Example"> 
        <p>Object selection are:: {selectedObjValue}</p>
        <br/>
        <lightning-checkbox-group name="objects"
            label="Please Select The Object(s)."
            options={objectOptions}
            value={selectedObjValue}
            onchange={handleObjectChange}>
        </lightning-checkbox-group>    
    </lightning-card>
</template>


OUTPUT:


After selection of Checkbox




LWC combobox Example:

Scenario: 
1. Create a combobox in LWC which will display list of Object in your ORG. 
2. Combobox details is as follows, 
              Label: Object Label 
              Value: Object API

Solution:
For this example first we have to create a LWC project in Visual Studio.
[Check my post to how to create LWC project and LWC component


1. First create an Apex class named as LWCComboboxExamplController and under this class create a
method named as getListOfObjDetails()  which will return list of object details. Copy paste the
below code base,
public with sharing class LWCComboboxExamplController {
    @AuraEnabled(cacheable=true)
    public static List<ObjectDetailsWrappergetListOfObjDetails() {
        Map<StringSObjectTypemapOfObjs = schema.getGlobalDescribe();
        if(mapOfObjs != null && mapOfObjs.keySet() != null) {
            List<ObjectDetailsWrapperlstOfObjWrapper 
                                    new List<ObjectDetailsWrapper>();

            for(String keymapOfObjs.keySet()) {
                ObjectDetailsWrapper objWrapInst 
                                        new ObjectDetailsWrapper();
                if(mapOfObjs.get(key) != null 
                        && mapOfObjs.get(key).getDescribe() != null)
                  objWrapInst.objLabel 
                            mapOfObjs.get(key).getDescribe().getLabel();
                objWrapInst.objAPI = key;

                lstOfObjWrapper.add(objWrapInst);
            }

            return lstOfObjWrapper;
        }
        return null;
    }

    public class ObjectDetailsWrapper {
        @AuraEnabled
        public String objLabel;
        @AuraEnabled
        public String objAPI;
    }
}

2. Create a Lightning Web Component named as "lwcComboboxExample". System will automatically create 3 files (lwcComboboxExampl.html, lwcComboboxExampl.js, lwcComboboxExampl.js-meta.xml) under "lwc" folder (default location).


3. Modify "lwcComboboxExampl.js-meta.xml" with below line of codes.
<?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>

4. Modify "lwcComboboxExampl.hml" with below line of codes.
<template>
    <lightning-card title="Combobox Example">        
        <lightning-combobox
            name="objects"
            label="Select an Object"
            value={selectedObjValue}
            placeholder="Select an Object"
            options={objectOptions}
            onchange={handleObjectChange} >
        </lightning-combobox>
    <p>Object selection is: {selectedObjValue}</p>
    </lightning-card>
</template>

5.Modify "lwcComboboxExampl.js" with below line of codes
import { LightningElementwiretrack } from 'lwc';
import getListOfObjDetails from '@salesforce/apex/LWCComboboxExamplController.getListOfObjDetails';

export default class LwcComboboxExample extends LightningElement {
    //variable responsibles for holding the array for records with value & label.
    @track objItems = [];
    //variable responsibles for holding errors.
    @track objError;
    //variable responsibles for holding the selected object value of combo-box.
    @track selectedObjValue = '';

    /**
     * Calling Apex class method getListOfObjDetails() and hold the information under variable listOfObjectDetails.
     * This is also responsible to creat a JSON array with key and value pair for combobox and the
     * array value are stored under the tracking array variable named as 'objItems[]'.
     */
    @wire
    (getListOfObjDetailslistOfObjectDetails({ errordata }) {
        if (data) {
            for(var i=0i<data.lengthi++) {
                this.objItems = [...this.objItems ,{value: data[i].objAPI , label: data[i].objLabel}];                
            }
        } else if (error) {
            this.objError = error;
            this.objects = undefined;
        }
    }

    /**
     * Return list of Objects for combobox.
     */
    get objectOptions() {
        return this.objItems;    
    }

    /**
     * Holding onchange object under tracking variable 'selectedObjValue'.
     * @param {*} event 
     */
    handleObjectChange(event) {
        this.selectedObjValue = event.detail.value;
    }
}

6. Go to Lighting App Builder and then create a new App Page (Combobox Example). Drag your "lwcComboboxExampl" in to "Combobox Example". Than save and activate it. 

7. Now from "App Launcher" click on the "Combobox Example" and the output will like below,


After selecting object say Account, it will be look like below,





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 ...