How do I effectively develop a lightning combo box?
I'm developing a lightning web component and I want to fill or populate my combobox from the result of the apex method so that I can in the html file get the result from the JavaScript file and put them in the combobox.
Template:
name="Role"
label="Role Name"
value={value}
placeholder=""
options={rolesList.data.values}
onchange={handleChange} >
javascript file:
import { LightningElement, track, wire} from 'lwc';
import getRoles from '@salesforce/apex/LeaveSettingsController.getRoles';
@wire(getRoles)
rolesList;
Regarding the lightning combo box -
Controller
Here retrieve UserRole records based on SOQL query and no data transformation in this class
public with sharing class UserRoleController {
@AuraEnabled (cacheable=true)
public static List getUserRoles(){
return [SELECT Id, Name FROM UserRole];
}
}
js Controller class
In this class, inside wiredUserRoles() method, perform data transformation for value and label.
Use, roleOptions() getter property to return the array.
/* eslint-disable no-console */
import { LightningElement , wire, track} from 'lwc';
//import method which should be used from Controller
import getUserRoles from '@salesforce/apex/UserRoleController.getUserRoles';
let i=0;
export default class DisplayUserRole extends LightningElement {
@track items = []; //this will hold key, value pair
@track value = ''; //initialise combo box value
@track chosenValue = '';
@wire(getUserRoles)
wiredUserRoles({ error, data }) {
if (data) {
//create array with elements which has been retrieved controller
//here value will be Id and label of combobox will be Name
for(i=0; i
Output
After selection, display the value.