Usage of lightning:combobox
In this blog I am going to show a simple usage of the lightning:combobox .lightning:combobox is an input element that enables single selection from a list of options. The result of the selection is displayed as the value of the input.A widget that provides an input field that is read-only, accompanied with a dropdown list of selectable options.In this example, once the user selects the Department from the contact, it will get all the contacts and display as the table shown below.
Apex Class
public class ContactsController { @AuraEnabled public static List<String> getDepartment () { Set<String> uniqDepartment = new Set<String>(); List<Contact> results=[Select Id, Department from Contact]; for(Contact c : results){ if(c.Department!=null){ uniqDepartment.add(c.Department); } } List<String> finalResult = new List<String>(); finalResult.addAll(uniqDepartment); finalResult.sort(); return finalResult; } @AuraEnabled public static List<Contact> getContactsByDept (String deptName) { List<Contact> results=[Select Id,FirstName,LastName,Email,Department from Contact where Department=:deptName]; return results; } }
Lightning Component
<aura:component controller="ContactsController"> <aura:attribute name="statusOptions" type="List" default="[]"/> <aura:attribute name="contacts" type="Contact[]" default="[]"/> <aura:handler name="init" value="{! this }" action="{! c.loadOptions }"/> <lightning:combobox aura:id="selectItem" name="status" label="Status" placeholder="Choose Status" value="new" required="true" dropdownAlignment="right" variant="standard" messageWhenValueMissing="You Must Select the Value" onchange="{!c.handleOptionSelected}" options="{!v.statusOptions}"/> <table class="slds-table slds-table--bordered"> <thead> <th> LastName </th> <th> FirstName </th> <th> Email </th> </thead> <tbody> <aura:iteration items="{!v.contacts}" var="row"> <tr> <td> {!row.LastName} </td> <td> {!row.FirstName} </td> <td> {!row.Email} </td> </tr> </aura:iteration> </tbody> </table> </aura:component>
({ loadOptions: function (cmp, event, helper) { var options = [ ]; var action = cmp.get("c.getDepartment"); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { var arr = response.getReturnValue() ; arr.forEach(function(element) { options.push({ value: element, label: element }); }); cmp.set("v.statusOptions", options); } }); $A.enqueueAction(action); }, handleOptionSelected: function (cmp, event) { var action = cmp.get("c.getContactsByDept"); action.setParams({deptName:event.getParam("value")}); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { cmp.set("v.contacts" , response.getReturnValue() ) ; } }); $A.enqueueAction(action); } })