Introduction:
Hi everyone, welcome to our new blog post “Creating Picklist from Sobject Field values in Lightning Aura Component”. In this blog post, we will explain a custom aura component, which shows an example of how to create a picklist field from the picklist field values of an object.
apex class [ fetchPicklistOptsController.apxc ]
public class fetchPicklistOptsController {
@AuraEnabled
public static List<String> getselectOptions(sObject objObject, string fld) {
List<String> allOpts = new List<String>();
// Get the object type of the SObject.
Schema.sObjectType objType = objObject.getSObjectType();
// Describe the SObject using its object type.
Schema.DescribeSObjectResult objDescribe = objType.getDescribe();
// Get a map of fields for the SObject
map<String, Schema.SObjectField> fieldMap = objDescribe.fields.getMap();
// Get the list of picklist values for this field.
list<Schema.PicklistEntry> values = fieldMap.get(fld)
.getDescribe()
.getPickListValues();
// Add these values to the selectoption list.
for (Schema.PicklistEntry a : values) {
allOpts.add(a.getValue());
}
allOpts.sort();
return allOpts;
}
}
Component [sample.cmp]
<aura:component controller="fetchPicklistOptsController">
<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>
Controller [ sampleController.js]
({
doInit: function (component, event, helper) {
helper.fetchPickListVal(component, 'Industry', 'accIndustry');
},
function(component, event, helper) {
// get the value of select option
alert(event.getSource().get("v.value"));
},
})
Helper [sampleHelper.js]
({
fetchPickListVal: function (component, fieldName, elementId) {
var action = component.get("c.getselectOptions");
action.setParams({
"objObject": component.get("v.objInfo"),
"fld": fieldName
});
var opts = [];
action.setCallback(this, function (response) {
if (response.getState() == "SUCCESS") {
var allValues = response.getReturnValue();
if (allValues != undefined & allValues.length > 0) {
opts.push({
class: "optionClass",
label: "--- None ---",
value: ""
});
}
}
});
$A.enqueueAction(action);
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);
},
})
TestApp.app
<aura:application extends="force:slds">
<c:sample/>
<!-- here c: is org. namespace prefix-->
</aura:application>

Leave a comment