Play Games

Search This Blog

Tuesday, January 4, 2022

How to show dropdown or select list with salesforce records as options in Lightning Web Component(LWC) - Salesforce Globe For You

How to show dropdown or select list with salesforce records as options in Lightning Web Component(LWC) - Salesforce Globe For You

Solution: Use <lightning-combobox> to display select list in LWC

Example:

Apex Class: LeadDataController

public class LeadDataController {

    @AuraEnabled

    public static List<Lead> fetchLeads() {

        List<Lead> lstLead = new List<Lead>();

        lstLead = [Select id,name from Lead limit 5];

        return lstLead;

    }

}

displayDropDownInLWC.html

<template>

    <lightning-card>

    <lightning-combobox

            name="progress"

            label="Display Top 5 Lead Records in Drop Down"

            value={selectedLead}

            placeholder="Select Lead Record"

            options={lstLeadRecordOptions}

            onchange={handleChange} ></lightning-combobox>


    <p>Selected value is: {selectedLead}</p>

    </lightning-card>

</template>

displayDropDownInLWC.js:

import { track,LightningElement } from 'lwc';

import fetchLeads from '@salesforce/apex/LeadDataController.fetchLeads';

export default class DisplayDropDownInLWC extends LightningElement {

    @track lstLeadRecordOptions=[];

    @track selectedLead;

    connectedCallback() {

        fetchLeads()

        .then(result => {

            if(result){

                const temp = { label: 'None', value: 'None' };

                this.lstLeadRecordOptions = [ ...this.lstLeadRecordOptions, temp ];

                for(var item of result) {

                    var lead = { label: item.Name, value: item.Id };

                    this.lstLeadRecordOptions = [ ...this.lstLeadRecordOptions, lead ];

                }

            }

        })

        .catch(error => {

            this.error = error;

        });

    }

    handleChange(event) {

        this.selectedLead = event.detail.value;

    }

}

displayDropDownInLWC.js-meta.xml:

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>52.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__RecordPage</target>

        <target>lightning__AppPage</target>

        <target>lightning__HomePage</target>

    </targets>

</LightningComponentBundle>

Output:



No comments:

Post a Comment