Monday, 10 February 2020

Convert List of Records into picklist in lightning.



Converting List of Account records into Picklist values in the component.

Component:- ListToPicklist.cmp

<aura:component access="global" controller="ListToPicklistcon" implements="flexipage:availableForAllPageTypes">

    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
   <aura:attribute name="objInfo" type="account" default="{sobjectType : 'Account'}" />

   <div class="slds-form-element">
      <label class="slds-form-element__label" for="select-01">Select Label</label>
      <div class="slds-select_container">
         <ui:inputSelect  aura:id="accIndustry" class="slds-select" change="{!c.onPicklistChange}"/>
      </div>
   </div>
 
</aura:component>

JS:- ListToPicklistController.js

({
doInit: function(component, event, helper) {
        helper.fetchPickListVal(component, 'accIndustry');
    },
    onPicklistChange: function(component, event, helper) {
        // get the value of select option
        alert(event.getSource().get("v.value"));
    },
})

Helper:- ListToPicklistHelper.js

({
    fetchPickListVal: function(component, elementId) {
       
        var action = component.get("c.getselectOptions");
       
        var opts = [];
        action.setCallback(this, function(response) {
            if (response.getState() == "SUCCESS") {
                var allValues = response.getReturnValue();
  alert('allValues---'+allValues);
                if (allValues != undefined && allValues.length > 0) {
                    opts.push({
                        class: "optionClass",
                        label: "--- None ---",
                        value: ""
                    });
                }
                for (var i = 0; i < allValues.length; i++) {
                    opts.push({
                        class: "optionClass",
                        label: allValues[i],
                        value: allValues[i]
                    });
                }
                component.find(elementId).set("v.options", opts);
            }
        });
        $A.enqueueAction(action);
    },
})

Apex Class: 

public class ListToPicklistcon {
   
    @AuraEnabled
    public static List < String > getselectOptions() {
       
        List<account> values = [select id,name from account];
        List < String > allOpts = new list < String > ();
       
        // Add these values to the selectoption list.
        for (account a: values) {
            allOpts.add(a.name);
        }
        system.debug('allOpts ---->' + allOpts);
        allOpts.sort();
        return allOpts;
    }
   
}



No comments:

Post a Comment