When working with LWC sometimes, you need a list of values in picklist(combobox) which is fetched from an apex class. Values can be based on some condition. So, in this blog, we will see how to fetch a list of sObject records and bind values into <lightning-combobox />.
Sample_Combobox.cmp
<template>
<div class="slds-p-horizontal_medium">
<lightning-combobox name="types" label="Type" value={value} options={TypeOptions} onchange={handleTypeChange}> </lightning-combobox>
</div>
</template>
Sample_Combobox.js
import {
LightningElement,
track,
wire,
api
} from 'lwc';
import Objects_Type from "@salesforce/apex/Sample_Controller.f_Get_Types";
export default class Sample_Combobox extends LightningElement {
@track l_All_Types;
@track TypeOptions;
@wire(Objects_Type, {})
WiredObjects_Type({ error, data }) {
if (data) {
try {
this.l_All_Types = data;
let options = [];
for (var key in data) {
// Here key will have index of list of records starting from 0,1,2,....
options.push({ label: data[key].Name, value: data[key].Id });
// Here Name and Id are fields from sObject list.
}
this.TypeOptions = options;
} catch (error) {
console.error('check error here', error);
}
} else if (error) {
console.error('check error here', error);
}
}
handleTypeChange(event){
var Picklist_Value = event.target.value;
// Do Something.
}
}
Sample_Combobox.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>48.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__RecordPage</target>
<target>lightning__AppPage</target>
<target>lightning__HomePage</target>
</targets>
</LightningComponentBundle>
Sample_Controller.cls
public with sharing class Sample_Controller {
@AuraEnabled(cacheable=true)
public static List<sObject> f_Get_Types(){
try {
List<sObject> l_Types = new List<sObject>();
l_Types = [Select id, Name from Test_Object__c]; // Can include multiple fields,
// You can also use any standard or custom object
// You can get values from custom setting also.
return l_Types;
} catch (Exception e) {
System.debug('Exception: '+e.getMessage());
return null;
}
}
}
List that is returned can be
- From Query result
- Custom list – based on condition
- From Custom Setting
- Can be from Any Custom or standard objects.
- A primitive data type list (list of String or Double or Integer etc.)
- A non-primitive data type list (any list of sObject)
Resources:
Hi,
Can we sort the records in Combobox?
Thanks,
Swaroopa
LikeLike
Yes.
You can sort the list in Apex or even in JS file.
LikeLike
I need a particular value from the source to be selected by default on Combo Box. Can we do that?
LikeLike
Yes it is possible. In JS file, Set value=”default_value”; where you declare a variable named value.
something like this.
export default class Sample_Combobox extends LightningElement {
value=’Some default value text’;
/*
Other JS code
*/
}
if there are multiple combobox, use unique names for all.
LikeLike