Wednesday, March 13, 2019

dual list box component in Lightning Web Components(lwc)

This post explains how to create a dual list box in lightning web components(lwc)

Demo
dualListBoxLWCDemo.html
<template>
    <lightning-card title="Dual List Box Example" icon-name="custom:custom43">
        <template if:true={IndustryValues.data}>
            <lightning-dual-listbox name="Industries"
                                    label="Select Industries"
                                    source-label="Available"
                                    selected-label="Selected"
                                    field-level-help="This is a dual listbox"
                                    options={IndustryValues.data.values}
                                    onchange={handleChange}></lightning-dual-listbox>
        </template><br/>
    <div class="slds-box" >
        <p>Selected values are: <b style="color:blue;">{selected}</b></p>
    </div>
</lightning-card>
</template>

dualListBoxLWCDemo.js
import {LightningElement, track, wire} from 'lwc';
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';

export default class DualListBoxLWCDemo extends LightningElement {
    @track _selected = []; // this array tracks the seleted values

    // Getting Account Object info using wire service
    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })
    objectInfo;

    // Getting Pickvalues based on default recordtype using wire service
    @wire(getPicklistValues, { recordTypeId: '$objectInfo.data.defaultRecordTypeId', fieldApiName: INDUSTRY_FIELD})
    IndustryValues;

    // assigning none if you are not seleted any values
    get selected() {
        return this._selected.length ? this._selected : 'none';
    }

    // Handling the change event
    handleChange(event) {
        this._selected = event.detail.value;
    }
}

dualListBoxLWCDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="dualListBoxLWCDemo">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Result

1 comment:

  1. Is this applicable for the custome field on user object ??? This is not working

    ReplyDelete