Turn On – Lightning Part 4 (Building Picklist Values Dynamically)

In this blog, we will see a generic way for displaying the picklist values for the given objects.

You can view this in action here:

Step 1: Apex class to fetch the picklist values for the given set of objects:

public class CollectionsInLightningCls {
@AuraEnabled
public static Map<String, Map<String, List<String>>> getPicklistValues(String objpicklistFieldsMap){
Map<String, List<String>> objPickmap = (Map<String, List<String>>)JSON.deserialize(objpicklistFieldsMap, Map<String, List<String>>.class);
system.debug('objpickmap ' + objPickmap);

Map<String, Map<String, List<String>>> objFieldPicklistMap = new Map<String, Map<String, List<String>>>();
List<String> sobjectslist = new List<String>(objPickmap.keySet());
Schema.DescribeSobjectResult[] results = Schema.describeSObjects(sobjectslist);
Map<String, List<String>> fieldOptionsMap;
for(Schema.DescribeSObjectResult result : results){
fieldOptionsMap = new Map<String, List<String>>();

Schema.sObjectType objType = result.getSObjectType();

Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
List<String> objFieldlist = objPickmap.get(result.getName());
system.debug('objname ' + result.getName());
system.debug('list of fields ' + objFieldlist);
for(String fld : objFieldlist){
system.debug('fields ' + fld);
List<String > allOpts = new list<String>();
list<Schema.PicklistEntry> values =
fieldMap.get(fld).getDescribe().getPickListValues();

for (Schema.PicklistEntry a : values){
allOpts.add(a.getValue());
}
fieldOptionsMap.put(fld, allOpts);
}
objFieldPicklistMap.put(result.getName(), fieldOptionsMap);
}
return objFieldPicklistMap;
}
}

 

  • Method will return the list of picklist values for the given field and for the given object
  • The input String is deserialize to obtain the list of fields for which the picklist values to be fetched for the given list of objects.

Step 2: Create a lightning component:

<aura:component controller="CollectionsInLightningCls" implements="forceCommunity:availableForAllPageTypes" access="global">
<ltng:require styles="{!$Resource.SLDS + '/assets/styles/salesforce-lightning-design-system.min.css'}"/>
<aura:attribute name="picklistFields" type="Map" default="{}" />

<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<div class="container">
<div class="slds-p-top--medium slds-p-left--medium">
<fieldset class="slds-form--compound custom-border">
<div>
Account:
<ui:inputSelect aura:id="Account.singhforce__Active__c" label="Active" />
<ui:inputSelect aura:id="Account.singhforce__UpsellOpportunity__c" label="Upsell Opportunity" />
<ui:inputSelect aura:id="Account.singhforce__SLA__c" label="SLA" />
</div>
<div>
Contact:
<ui:inputSelect aura:id="Contact.LeadSource" label="Lead Source" />
<ui:inputSelect aura:id="Contact.singhforce__Hobbies__c" label="Hobbies" />
<ui:inputSelect aura:id="Contact.singhforce__Level__c" label="Level" />
</div></fieldset>
</div>
</div>
</aura:component>
  • Here aura:id is holding the object and Field API Name which will be used to populate the list of picklist values

Step 3: Component Controller:

({
doInit : function(component, event, helper) {
helper.fetchPicklistFields(component);
},
})

 

Step 4: Component Helper:

({
fetchPicklistFields: function(component) {
var picklistFields = component.get("v.picklistFields");

var contactPicklistFields = ["singhforce__Hobbies__c", "singhforce__Level__c", "LeadSource"];
picklistFields['Contact'] = contactPicklistFields;

var accountPicklistFields = ["singhforce__SLA__c", "singhforce__UpsellOpportunity__c", "singhforce__Active__c"];
picklistFields['Account'] = accountPicklistFields;

this.getPicklistValues(component,picklistFields);
},

getPicklistValues : function(component, sobjFieldsmap) {
var action = component.get("c.getPicklistValues");
action.setParams({
"objpicklistFieldsMap": JSON.stringify(sobjFieldsmap)
});
action.setCallback(this, function(resp) {
var state=resp.getState();
console.log('state ' + state);
if(state === "SUCCESS"){
var res = resp.getReturnValue();
console.log(res);
var obj;
for(obj in res){
var objName = res[obj];
console.log('object name --> ' + obj);
var field;
for(field in objName){
console.log('fields --> ' + field);
var optionValues = objName[field];
console.log('options --> ' + optionValues);
this.buildPicklist(component, obj + "." + field, optionValues);
}
}
}
});
$A.enqueueAction(action);
},

buildPicklist: function(component, elementId, optionValues) {
var opts = [];
if (optionValues != undefined && optionValues.length > 0) {
opts.push({
class: "optionClass",
label: "--- None ---",
value: ""
});
}

for (var i = 0; i < optionValues.length; i++) {
opts.push({
class: "optionClass",
value: optionValues[i],
label: optionValues[i]
});
}
component.find(elementId).set("v.options", opts);
},
})

  • fetchPicklistFields method – defines the list of picklist fields for the respective objects
  • getPicklistValues method – makes a call to the apex method to fetch the picklist values. Currently, Salesforce doesn’t support passing complex Map to the apex class which is why the parameter is converted into String using JSON.Stringify.

Here is the snapshot of the console:

picklist-consolelog

 

Please feel free to post your queries/thoughts.

Happy Coding!!!

 

Advertisements

3 thoughts on “Turn On – Lightning Part 4 (Building Picklist Values Dynamically)

  1. Hi, Thanks for publishing this code and its very useful for me and others who are working on lightning. I am facing an issue. I am not getting values in the picklist. Can you please let me know what are the changes I have to do in the code to retrieve picklist values.

    Thanks
    Babu

    Like

    1. Thanks Seshu, that code was helpful to you.
      You need to change the list of field api names and the object name in the Helper. And the Object.FieldAPIName in the CMP against the aura:id property and yes you also need to change labels

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s