Different ways to bind picklist values in Lightning Web Components (LWC)

Different ways to bind picklist values in Salesforce Lightning Web Components (LWC)

In this blog post, we will explore various ways to bind picklist values in LWC. We will also discuss how to use them in the application.

In the given LWC component, we have used three different types of picklist fields: Type, Industry, and Rating. Let’s discuss how we have bind picklist values for these fields.

1. Using UI Object Info API

The first way to bind picklist values is by using the UI Object Info API. This API allows us to retrieve metadata information about an object. We can use it to retrieve the list of picklist values for a specific field. The given LWC component uses the Metadata API to bind the picklist values for the Type field from Account Object.

To use the UI Object Info API, we need to import the ‘getPicklistValues’ function from the ‘lightning/uiObjectInfoApi’ module. We then use the ‘@wire’ decorator to wire the function to our component. In the wired property, we map the data values to an array of options. We use this array to populate the lightning-combobox component.

Sample Code:
JS -
// Import getPicklistValues function from uiObjectInfoApi module
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
// Import constant TYPE_FIELD from Account schema
import TYPE_FIELD from '@salesforce/schema/Account.Type';
// Wire getPicklistValues function from uiObjectInfoApi module to the component
    @wire(getPicklistValues, {
		// Specify record type ID , if no record type is there specify default record type
        recordTypeId: '012000000000000AAA',
		// Specify field API name
        fieldApiName: TYPE_FIELD
    })
HTML -
<lightning-combobox label="Type" value={accountType} options={typeOptions}
                onchange={handleAccountTypeChange}>
            </lightning-combobox>

Below are the pros and cons of this approach –

Pros –

  • Simplicity: The lightning/uiObjectInfoApi module provides a simple and declarative way to retrieve picklist values using a standard API. This can make it easier for developers to customize or maintain your application.
  • Up-to-Date: By using the standard API, you can ensure that you always have the most up-to-date picklist values. There is no need to manually update an Apex class.
  • Consistency: You can use the standard API to ensure that picklist values are consistent across your organization. This API ensures that the values adhere to any custom business logic. It also checks validation rules configured on the picklist field.
  • Support Record Types – If your object has record types, you can retrieve picklist values. These values are based on the record type assignment in your org.
  • Supported for all custom objects and most of the standard objects

Cons –

  • Performance: The complexity of your application and the number of picklist fields that need to be retrieved can impact performance. Using the lightning/uiObjectInfoApi module could require additional client-server round trips.
  • API Limits: The number of API calls you make can affect your limits. The number of picklist fields you need to retrieve also contributes to this. You may run into API limits. Additionally, you might incur extra costs if you are using a third-party API provider.
  • Limited Flexibility: The lightning/uiObjectInfoApi module provides a simple way to retrieve picklist values. However, it may not offer the same level of flexibility or control as retrieving them from an Apex class. For example, you may not be able to dynamically change the available picklist values based on certain conditions. You also can’t add custom logic to handle the selected value.
  • Not supported for external objects and some of the standard objects are also not supported , make sure to check these salesforce documentation links before implementing- Salesforce Objects Supported by lightning/ui*Api Modules – Salesforce Lightning Component Library & All Supported Objects | User Interface API Developer Guide | Salesforce Developers

2. Using Hardcoded values in JS for PickList Options

The second way to bind picklist values is by using hardcoded values. In the given LWC component, we have used this approach. We bind the picklist values for the Industry field from the Account Object.

To use hardcoded values, first define an array of options in our component. Then use it to populate the lightning-combobox component.

JS - 
// Define an array of industry options
    industryOptions = [
        { label: 'Agriculture', value: 'Agriculture' },
        { label: 'Apparel', value: 'Apparel' },
        { label: 'Banking', value: 'Banking' },
        { label: 'Biotechnology', value: 'Biotechnology' },
        { label: 'Chemicals', value: 'Chemicals' }
    ];
HTML -
<lightning-combobox label="Industry" value={accountIndustry} options={industryOptions}
                onchange={handleAccountIndustryChange}></lightning-combobox>

Below are the pros and cons of this approach –

Pros –

  • Simplicity: The lightning/uiObjectInfoApi module provides a simple and declarative way to retrieve picklist values using a standard API. This can make it easier for developers to customize or maintain your application.
  • Up-to-Date: By using the standard API, you can ensure that you always have the most up-to-date picklist values. There is no need to manually update an Apex class.
  • Consistency: You can use the standard API to ensure that picklist values are consistent across your organization. This API ensures that the values adhere to any custom business logic. It also checks validation rules configured on the picklist field.
  • Support Record Types – If your object has record types, you can retrieve picklist values. These values are based on the record type assignment in your org
  • Supported for all custom objects and most of the standard objects

Cons –

  • Performance: The complexity of your application and the number of picklist fields that need to be retrieved can impact performance. Using the lightning/uiObjectInfoApi module could require additional client-server round trips.
  • API Limits: The number of API calls you make can affect your limits. The number of picklist fields you need to retrieve also contributes to this. You may run into API limits. Additionally, you might incur extra costs if you are using a third-party API provider.
  • Limited Flexibility: The lightning/uiObjectInfoApi module provides a simple way to retrieve picklist values. However, it may not offer the same level of flexibility or control as retrieving them from an Apex class. For example, you may not be able to dynamically change the available picklist values based on certain conditions. You also can’t add custom logic to handle the selected value.
  • Not supported for external objects and some of the standard objects are also not supported , make sure to check these salesforce documentation links before implementing- Salesforce Objects Supported by lightning/ui*Api Modules – Salesforce Lightning Component Library & All Supported Objects | User Interface API Developer Guide | Salesforce Developers

3. Using Apex Controller

The third way to bind picklist values is by using an Apex controller. In the given LWC component, we used this approach. It binds the picklist values for the Rating field from the Account Object.

To use an Apex controller, we first need to define the Apex method that returns the picklist values. We then import this method into our LWC component using the ‘@salesforce/apex’ module. We then use the ‘@wire’ decorator to wire the method to our component. In the wired property, we map the data to an array of options. We use this array to populate the lightning-combobox component.

JS -
// Import getRatingPicklistValues function from Apex controller
import getRatingPicklistValues from '@salesforce/apex/AccountController.getPicklistValues';
// Wire getRatingPicklistValues function from Apex controller to the component
    @wire(getRatingPicklistValues, {})
    // Define a wired property for rating picklist values
    wiredRatingPicklistValues({ error, data }) {
        // If data is returned from the wire function
        if (data) {
            // Map the data to an array of options
            this.ratingOptions = data.map(option => {
                return {
                    label: option.label,
                    value: option.value
                };
            });
        }
        // If there is an error
        else if (error) {
            // Log the error to the console
            console.error(error);
        }
    }
HTML -
<lightning-combobox label="Rating" value={accountRating} options={ratingOptions}
                onchange={handleAccountRatingChange}></lightning-combobox>
Apex - 
@AuraEnabled(cacheable=true)
    public static List<Map<String, String>> getPicklistValues() {
        List<Schema.PicklistEntry> entries = Account.Rating.getDescribe().getPicklistValues();
        List<Map<String, String>> values = new List<Map<String, String>>();
        for (Schema.PicklistEntry entry : entries) {
            Map<String, String> valueMap = new Map<String, String>();
            valueMap.put('label', entry.getLabel());
            valueMap.put('value', entry.getValue());
            values.add(valueMap);
        }
        return values;
    }

Below are the pros and cons of this approach –

Pros –

  • More Control: By getting the picklist values from an Apex class, you can have more control. You can determine how the picklist values are displayed or used in your application. For example, you could dynamically change the available picklist values based on certain conditions. Additionally, you could add custom logic to handle the selected value.
  • Better Performance: You can improve the performance of your application. Use a cached, server-side call to retrieve the picklist values. This approach reduces the number of client-server round trips required to get the picklist values.
  • Flexibility: By exposing a picklist values method through an Apex class, you can use this method across multiple components. It can also be used across pages or even across multiple applications. This makes it easier to reuse code and maintain a consistent user experience across your organization.

Cons –

  • Maintenance: If picklist values change frequently, updating an Apex class may become challenging. A standard picklist field in the UI is easier to maintain. You would need to update the Apex class every time the picklist values change.
  • No Support for Record Types – Currently there is no support for Getting Picklist values based on Record Type, you need to make your own logic to customize the options – Getting Picklist values based on Record Type | IdeaExchange (salesforce.com)

Below is the complete sample code, where we showed the below 3 ways –

  • Bind Type field by Using UI Object Info API
  • Bind Industry field by Using Hardcoded values in JS for PickList Options
  • Bind Rating field by Using Apex Controller
<template>
<lightning-card title="Account Form">
<div class="slds-m-around_medium">
<lightning-combobox label="Type" value={accountType} options={typeOptions}
onchange={handleAccountTypeChange}>
</lightning-combobox>
<lightning-combobox label="Industry" value={accountIndustry} options={industryOptions}
onchange={handleAccountIndustryChange}></lightning-combobox>
<lightning-combobox label="Rating" value={accountRating} options={ratingOptions}
onchange={handleAccountRatingChange}></lightning-combobox><br />
Selected Type – {accountType} <br />
Selected Industry – {accountIndustry} <br />
Selected Rating – {accountRating}
</div>
</lightning-card>
</template>
// Import LightningElement and wire decorator from LWC module
import { LightningElement, wire } from 'lwc';
// Import getPicklistValues function from uiObjectInfoApi module
import { getPicklistValues } from 'lightning/uiObjectInfoApi';
// Import getRatingPicklistValues function from Apex controller
import getRatingPicklistValues from '@salesforce/apex/AccountFormController.getPicklistValues';
// Import constant TYPE_FIELD from Account schema
import TYPE_FIELD from '@salesforce/schema/Account.Type';
export default class AccountForm extends LightningElement {
// Initialize properties for the component
accountType = ''; // Set default value for accountType
accountIndustry = ''; // Set default value for accountIndustry
accountRating = ''; // Set default value for accountRating
typeOptions = []; // Initialize typeOptions as an empty array
ratingOptions = []; // Initialize ratingOptions as an empty array
// Define an array of industry options
industryOptions = [
{ label: 'Agriculture', value: 'Agriculture' },
{ label: 'Apparel', value: 'Apparel' },
{ label: 'Banking', value: 'Banking' },
{ label: 'Biotechnology', value: 'Biotechnology' },
{ label: 'Chemicals', value: 'Chemicals' }
];
// Wire getPicklistValues function from uiObjectInfoApi module to the component
@wire(getPicklistValues, {
recordTypeId: '012000000000000AAA', // Specify record type ID , if no record type is there specify default record type
fieldApiName: TYPE_FIELD // Specify field API name
})
// Define a wired property for type picklist values
wiredTypePicklistValues({ error, data }) {
// If data is returned from the wire function
if (data) {
// Map the data values to an array of options
this.typeOptions = data.values.map(option => {
return {
label: option.label,
value: option.value
};
});
}
// If there is an error
else if (error) {
// Log the error to the console
console.error(error);
}
}
// Wire getRatingPicklistValues function from Apex controller to the component
@wire(getRatingPicklistValues, {})
// Define a wired property for rating picklist values
wiredRatingPicklistValues({ error, data }) {
// If data is returned from the wire function
if (data) {
// Map the data to an array of options
this.ratingOptions = data.map(option => {
return {
label: option.label,
value: option.value
};
});
}
// If there is an error
else if (error) {
// Log the error to the console
console.error(error);
}
}
// Define a method to handle changes to the account type
handleAccountTypeChange(event) {
// Set the account type to the selected value
this.accountType = event.target.value;
}
// Define a method to handle changes to the account industry
handleAccountIndustryChange(event) {
// Set the account industry to the selected value
this.accountIndustry = event.target.value;
}
// Define a method to handle changes to the account rating
handleAccountRatingChange(event) {
// Set the account rating to the selected value
this.accountRating = event.target.value;
}
}
view raw accountForm.js hosted with ❤ by GitHub
/**
* AccountFormController
* ———————-
* This Apex controller provides utility methods for retrieving metadata-related information
* about the Account object, specifically the picklist values for the Rating field.
*
* Key Features:
* – Retrieves and formats picklist values for use in Lightning components.
* – Uses field metadata to ensure consistent and dynamic picklist value retrieval.
* – Designed for use with Aura or Lightning Web Components (LWC) via @AuraEnabled.
*/
public with sharing class AccountFormController {
/**
* Retrieves the picklist values for the Rating field of the Account object.
*
* Key Features:
* – Uses @AuraEnabled(cacheable=true) to support Lightning Data Service (LDS) caching.
* – Dynamically fetches metadata for the Rating field to ensure it reflects the latest configuration.
* – Formats picklist values into a list of maps with `label` and `value` keys.
*
* @return List<Map<String, String>> – A list of maps, where each map contains the `label` and `value`
* of a picklist entry for the Rating field.
*/
@AuraEnabled(cacheable=true)
public static List<Map<String, String>> getPicklistValues() {
// Retrieve the picklist values for the Rating field of the Account object.
List<Schema.PicklistEntry> entries = Account.Rating.getDescribe().getPicklistValues();
// Initialize a list to store the formatted picklist values.
List<Map<String, String>> values = new List<Map<String, String>>();
// Loop through each picklist entry to format its label and value.
for (Schema.PicklistEntry entry : entries) {
// Create a map to store the label and value of the current picklist entry.
Map<String, String> valueMap = new Map<String, String>();
// Add the label and value to the map.
// Human-readable label for the picklist entry.
valueMap.put('label', entry.getLabel());
// Programmatic value of the picklist entry.
valueMap.put('value', entry.getValue());
// Add the map to the list of values.
values.add(valueMap);
}
// Return the formatted list of picklist values.
return values;
}
}

For more helpful articles please visit – https://thesalesforcedev.in

Leave a comment