Skip to main content

Dynamically populate lightning:combobox


In order to dynamically populate values in lightning:combobox using javascript we can create a list variable and push the values. We also require the values like ids associated to the particular option for back-end logic.
For example  : If we want to show the list of contacts using lightning:combobox component where the option should display the contact name but the value should be the contact id which will be used for back-end logic

For this we can create a temporary Map variable in our lightning component and set the value and label parameters of the lightning:combobox.

lightning:combobox


Here is the code for this component

Combo.app


<aura:application extends="force:slds" access="global"  description="Lightning Combo Demo">
 <c:Combo_Cmpt/> 
</aura:application>


Combo_Cmpt.cmp

<aura:component implements="flexipage:availableForAllPageTypes" access="global" controller="ComboController">
<!-- attributes -->
<aura:attribute name="options" type="List" default="[]"/>
<aura:attribute name="TempMap" type="Map"/>
<!-- handlers-->
<aura:handler name="init" value="{!this }" action="{!c.init }"/>
  <lightning:card footer="Combobx Demo" title="Combobx Demo">
        <aura:set attribute="actions">
            <lightning:button variant="brand"  label="New"/>
        </aura:set>
        <p class="slds-p-horizontal_small">
            <lightning:layout multipleRows="true" verticalAlign="center">    
            
            <lightning:layoutItem smallDeviceSize="12" mediumDeviceSize="6" largeDeviceSize="4" size="12" padding="around-small">
                <lightning:combobox name="Contacts" 
                                    label="Contacts" 
                                    value="All Contacts" 
                                    placeholder="-Select Contacts-" 
                                    options="{! v.options }" 
                                    onchange="{! c.handleChange }"/>
            </lightning:layoutItem>           
            </lightning:layout>
        </p>
    </lightning:card>
</aura:component>



Combo_CmptController.js

({
     init: function (cmp, event, helper) {         
        helper.getContactList(cmp);        
    },
    handleChange: function (cmp, event) {
        // This will contain the string of the "value" attribute of the selected option
        var selectedOptionValue = event.getParam("value");
        alert("Option selected with value: '" + selectedOptionValue + "'");
    }
})



Combo_CmptHelper.js

({
     getContactList : function(cmp) {
        var action = cmp.get('c.getContactList');
        action.setCallback(this, $A.getCallback(function (response) {
            var state = response.getState();
            if (state === "SUCCESS") {  // create a attribute of type map to store the map values returned 
   // from the controller (ComboController ) 
   var myMap = cmp.get("v.TempMap");
                var myOptions = [];
                if(myMap == null){
                     myMap = {};
                }
                
                myMap = JSON.parse(JSON.stringify(response.getReturnValue())); 
                console.log('myMap '+myMap);
   // iterate the map for key and value
                for(var cont in myMap){
   // populate the list with the required JSON format
                    myOptions.push({label:myMap[cont], value:cont});
                }
                console.log('myOptions '+myOptions);
   // set the options to the combobox
                cmp.set("v.options", myOptions); 
            } else if (state === "ERROR") {
                var errors = response.getError();
                console.error(errors);
            }
        }));
        $A.enqueueAction(action);
    }
})




ComboController.apxc

public class ComboController {
    
    @AuraEnabled
    public static Map<String,String> getContactList(){

   Map<string,string> contactOptions= new Map<string,string>();
      List<Contact> contList = [Select Id, Name From Contact Limit 10];
           
      contactOptions.put('','-Select One-');
      for(Contact contStr : contList) {
            contactOptions.put(contStr.Name,contStr.id);        
      }
      System.debug('contactOptions >>>>>> '+contactOptions);
      return contactOptions;
       
    }
}

Comments

Popular posts from this blog

Einstein Bot user authentication

Using Bot for data manipulation use case in your company requires need of implementing some extra security layer to make it spoof proof. One of exciting salesforce feature we have is the well known Einstein Bot which many companies have implemented. I am going to cover detail step-by-step implementation of User validation use case using encrypted token. STEP-1: Create a Site & Site User go to setup > Sites & Domains > Sites Create a Site and make your user as "Site Contact". This is a prerequisites for live agent or Embedded Service setup. STEP-2 : Create a Embedded Service(formerly snap-ins) go to Service setup > Embedded Service Create a new Embedded Service Deployment record and copy the embedded service code snipped generated in a notepad. STEP-3  : Create a Visualforce page to test the chatbot (it will simulate the actual web portal which is going to consume the embedded service snipped.) BotController.apxc public class BotControlle...

Use of wrapper class in lightning:datatable

As you guys know the wrapper class concept in visualforce pages , we generally use it to create a data-table which fetches data from different objects or if we want to redirect user to some other page on click of a link as one of the column of data-table.        For example we want a column "Account Name" on the data-table which is a link and once user clicks it should redirect respective account record. Or , suppose we want to display a column with some images or icons as a visual indicator Or what not. These requirements require us to use a wrapper on the lighting data-table (lightning:datatable) I am going to use my previous account search example ( Account Search Lightning Component ) and explain the use of wrapper. AccountSearchWrapper.app <aura:application extends="force:slds" access="global" >     <c:AccountSearchWrapper /> </aura:application> AccountSearchWrapper.cmp <aura:component controller="...