Hey guys, today in this post we are going to learn about How to create custom dependent Picklist dynamically in lightning component.
- Don’t forget to check out:- How to fetch picklist values from apex controller in lightning component Click Here For More Information
Real time scenarios:- Create custom dependent Picklist dynamically on custom sObject. Create two Picklist one is State and another is City.
If user changed the State drop-down option then the city name of State automatic filtered and display on city drop-down option.
Files we used in this post example:-
lightningDependentPicklistApp.app | Lightning Application | It is used for call the component to preview on browser. |
lightningDependentPicklistCmp.cmp | Lightning Component | It is used for create picklis dropdown of State and City. |
lightningDependentPicklistCmpController.js | JavaScript Controller File | It is used for communicate to server side apex method and fetch the value of picklist from init fuction. | dependentPicklistController.apxc | Apex Class Controller | It is used for collect the picklist value of both custom fields dynamically. |
Custom Object:- NewStudent__c Custom State Picklist Fields and there Option:- State__c Picklist Value:- Rajasthan, Custom City Picklist Fields and there Option:- City__c Ajmer, |
Custom Object and their fields |
It’s retrieve custom field of sObject.
|
Final Output
You can download file directly from github by Click Here.
Other related post that would you like to learn in Salesforce
Note:- Custom sObject >> NewStudent__c and there Custom Picklist Fields
You need to change Picklist Option value with your Picklist Option value.
You need to set field dependency on that fields. There State is the controller field and city is the dependent field.
Step 1:- Create Lightning Application : lightningDependentPicklistApp.app
From Developer Console >> File >> New >> Lightning Application
lightningDependentPicklistApp.app [Component Application File]
<aura:application extends="force:slds">
<c:lightningDependentPicklistCmp/>
</aura:application>
Step 2:- Create Lightning Component : lightningDependentPicklistCmp.cmp
From Developer Console >> File >> New >> Lightning Component
lightningDependentPicklistCmp.cmp [Lightning Component File]
<aura:component controller="dependentPicklistController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:attribute name="getParentList" type="list" default="[]" description=""/>
<aura:attribute name="getChildList" type="list" default="[]"/>
<aura:attribute name="getPickListMap" type="map"/>
<aura:attribute name="getDisabledChildField" type="boolean" default="true"/>
<aura:attribute name="getObjectName" type="string" default="NewStudent__c"/>
<aura:attribute name="getParentFieldAPI" type="string" default="State__c"/>
<aura:attribute name="getChildFieldAPI" type="string" default="City__c"/>
<aura:attribute name="getParentFieldLabel" type="string" />
<aura:attribute name="getChildFieldLabel" type="string"/>
<aura:attribute name="getParentValue" type="string" default=""/>
<aura:attribute name="getChildValue" type="string" default=""/>
<lightning:card title="Dependent Picklist Demo">
<div class="slds-grid slds-wrap">
<div class="slds-col slds-col_size-6-of-12">
<!-- Custom Controller Field -->
<lightning:layoutItem size="12" padding="around-small">
<lightning:select name="parentField" aura:id="parentField"
value="{!v.getParentValue}"
label="{!v.getParentFieldLabel}"
onchange="{!c.ObjFieldByParent}">
<aura:iteration items="{!v.getParentList}" var="value">
<option value="{!value}">{!value}</option>
</aura:iteration>
</lightning:select>
</lightning:layoutItem>
</div>
<div class="slds-col slds-col_size-6-of-12">
<!--Custom Dependable Field-->
<lightning:layoutItem size="12" padding="around-small">
<lightning:select name="childField"
value="{!v.getChildValue}"
label="{!v.getChildFieldLabel}"
disabled="{!v.getDisabledChildField}">
<aura:iteration items="{!v.getChildList}" var="value">
<option value="{!value}">{!value}</option>
</aura:iteration>
</lightning:select>
</lightning:layoutItem>
</div>
</div>
<br/><br/>
<!--Start RelatedTopics Section-->
<div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
<p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/05/thumbsUpLike.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:16px; font-style:italic; display:inline-block; margin-right:5px;">Don't forget to check out:-</span><a href="https://www.w3web.net/" target="_blank" rel="noopener noreferrer" style="text-decoration:none;" data-aura-rendered-by="440:0">An easy way to learn step-by-step online free Salesforce tutorial, To know more Click <span style="color:#ff8000; font-size:18px;" data-aura-rendered-by="442:0">Here..</span></a></strong></p>
<br/><br/>
<p data-aura-rendered-by="435:0"><img src="https://www.w3web.net/wp-content/uploads/2021/07/tickMarkIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;" data-aura-rendered-by="436:0"><strong data-aura-rendered-by="437:0"><span style="font-size:17px; font-style:italic; display:inline-block; margin-right:5px; color:rgb(255 128 0);">You May Also Like β</span> </strong></p>
<div style="display:block; overflow:hidden;">
<div style="width: 50%; float:left; display:inline-block">
<ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;">
<li><a href="https://www.w3web.net/lwc-get-set-lightning-checkbox-value/" target="_blank" rel="noopener noreferrer">How to get selected checkbox value in lwc</a></li>
<li><a href="https://www.w3web.net/display-account-related-contacts-in-lwc/" target="_blank" rel="noopener noreferrer">how to display account related contacts based on AccountId in lwc</a></li>
<li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to create lightning datatable row actions in lwc</a></li>
<li><a href="https://www.w3web.net/if-and-else-condition-in-lwc/" target="_blank" rel="noopener noreferrer">how to use if and else condition in lwc</a></li>
<li><a href="https://www.w3web.net/get-selected-radio-button-value-and-checked-default-in-lwc/" target="_blank" rel="noopener noreferrer">how to display selected radio button value in lwc</a></li>
</ul>
</div>
<div style="width: 50%; float:left; display:inline-block">
<ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;">
<li><a href="https://www.w3web.net/display-account-related-contacts-lwc/" target="_blank" rel="noopener noreferrer">display account related contacts based on account name in lwc</a></li>
<li><a href="https://www.w3web.net/create-lightning-datatable-row-actions-in-lwc/" target="_blank" rel="noopener noreferrer">how to insert a record of account Using apex class in LWC</a></li>
<li><a href="https://www.w3web.net/fetch-picklist-values-dynamic-in-lwc/" target="_blank" rel="noopener noreferrer">how to get picklist values dynamically in lwc</a></li>
<li><a href="https://www.w3web.net/edit-save-and-remove-rows-dynamically-in-lightning-component/" target="_blank" rel="noopener noreferrer">how to edit/save row dynamically in lightning component</a></li>
<li><a href="https://www.w3web.net/update-parent-object-from-child/" target="_blank" rel="noopener noreferrer">update parent field from child using apex trigger</a></li>
</ul>
</div>
<div style="clear:both;"></div>
<br/>
<div class="youtubeIcon">
<a href="https://www.youtube.com/channel/UCW62gTen2zniILj9xE6LmOg" target="_blank" rel="noopener noreferrer"><img src="https://www.w3web.net/wp-content/uploads/2021/11/youtubeIcon.png" width="25" height="25" style="vertical-align:top; margin-right:10px;"/> <strong>TechW3web:-</strong> To know more, Use this <span style="color: #ff8000; font-weight: bold;">Link</span> </a>
</div>
</div>
</div>
<!--End RelatedTopics Section-->
</lightning:card>
</aura:component>
Step 3:- Create Lightning Component : lightningDependentPicklistCmpController.js
From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller
lightningDependentPicklistCmpController.js [JavaScript Controller]
({
doInit : function(component, event, helper) {
var action = component.get("c.customDependablePicklist");
action.setParams({
strObjectName : component.get("v.getObjectName"),
strparentField : component.get("v.getParentFieldAPI"),
strchildField : component.get("v.getChildFieldAPI")
});
action.setCallback(this, function(response){
var status = response.getState();
if(status === "SUCCESS"){
var pickListResponse = response.getReturnValue();
component.set("v.getPickListMap",pickListResponse.pickListMap);
component.set("v.getParentFieldLabel",pickListResponse.parentFieldLabel);
component.set("v.getChildFieldLabel",pickListResponse.childFieldLabel);
var pickListMap = component.get("v.getPickListMap");
var parentkeys = [];
var parentField = [];
for (var pickKey in pickListResponse.pickListMap) {
parentkeys.push(pickKey);
}
if (parentkeys != undefined && parentkeys.length > 0) {
parentField.push('--- None ---');
}
for (var i = 0; i < parentkeys.length; i++) {
parentField.push(parentkeys[i]);
}
component.set("v.getParentList", parentField);
}
});
$A.enqueueAction(action);
},
ObjFieldByParent : function(component, event, helper) {
var controllerValue = component.find("parentField").get("v.value");
var pickListMap = component.get("v.getPickListMap");
if (controllerValue != '--- None ---') {
var childValues = pickListMap[controllerValue];
var childValueList = [];
childValueList.push('--- None ---');
for (var i = 0; i < childValues.length; i++) {
childValueList.push(childValues[i]);
}
component.set("v.getChildList", childValueList);
if(childValues.length > 0){
component.set("v.getDisabledChildField" , false);
}else{
component.set("v.getDisabledChildField" , true);
}
} else {
component.set("v.getChildList", ['--- None ---']);
component.set("v.getDisabledChildField" , true);
}
}
})
Step 4:- Create Lightning Application : dependentPicklistController.apxc
From Developer Console >> File >> New >> Apex Class
dependentPicklistController.apxc [Apex Class Controller]
public WITH sharing class dependentPicklistController {
private static final String getAlphaChars = '' +
'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
'abcdefghijklmnopqrstuvwxyz' +
'0123456789+/';
@AuraEnabled
public static customPicklistWrapper customDependablePicklist(String strObjectName, string strparentField, string strchildField) {
Map<String,List<String>> pickListMap = NEW Map<String,List<String>>();
customPicklistWrapper pw = NEW customPicklistWrapper();
pw.pickListMap = pickListMap;
IF (Schema.getGlobalDescribe().get(strObjectName) ==NULL || String.isBlank(strparentField) || String.isBlank(strChildField)){
RETURN pw;
}
Schema.sObjectType objType = Schema.getGlobalDescribe().get(strObjectName).newSObject().getSObjectType();
Map<String, Schema.SObjectField> objFieldMap = objType.getDescribe().fields.getMap();
IF (!objFieldMap.containsKey(strparentField) || !objFieldMap.containsKey(strchildField)){
RETURN pw;
}
List<customPicklistEntryWrapper> depEntriesList = (List<customPicklistEntryWrapper>)JSON.deserialize(JSON.serialize(objFieldMap.get(strChildField).getDescribe().getPicklistValues()), List<customPicklistEntryWrapper>.class);
List<String> controllingValues = NEW List<String>();
FOR (Schema.PicklistEntry ple : objFieldMap.get(strparentField).getDescribe().getPicklistValues()) {
pickListMap.put(ple.getLabel(), NEW List<String>());
controllingValues.add(ple.getLabel());
}
FOR (customPicklistEntryWrapper plew : depEntriesList) {
String validForBits = alphaBaseToBits(plew.validFor);
FOR (INTEGER i = 0; i < validForBits.length(); i++) {
String bit = validForBits.mid(i, 1);
IF (bit == '1') {
pickListMap.get(controllingValues.get(i)).add(plew.label);
}
}
}
pw.pickListMap = pickListMap;
pw.parentFieldLabel = objFieldMap.get(strparentField).getDescribe().getLabel();
pw.childFieldLabel = objFieldMap.get(strchildField).getDescribe().getLabel();
RETURN pw;
}
public static String decimalToBinary(INTEGER val) {
String bits = '';
while (val > 0) {
INTEGER remainder = Math.mod(val, 2);
val = INTEGER.valueOf(Math.floor(val / 2));
bits = String.valueOf(remainder) + bits;
}
RETURN bits;
}
public static String alphaBaseToBits(String validFor) {
IF (String.isEmpty(validFor)) RETURN '';
String validForBits = '';
FOR (INTEGER i = 0; i < validFor.length(); i++) {
String thisChar = validFor.mid(i, 1);
INTEGER val = getAlphaChars.indexOf(thisChar);
String bits = decimalToBinary(val).leftPad(6, '0');
validForBits += bits;
}
RETURN validForBits;
}
public class customPicklistWrapper{
@AuraEnabled
public Map<String, List<String>> pickListMap;
@AuraEnabled
public String parentFieldLabel;
@AuraEnabled
public String childFieldLabel;
}
public class customPicklistEntryWrapper{
public String active;
public String defaultValue;
public String label;
public String VALUE;
public String validFor;
}
}
Further post that would you like to learn in Salesforce
What is dependent picklist in Salesforce?
A dependent picklist is a custom or multi-select picklist for which the valid values depend on the value of another field, called the controlling field . Controlling fields can be any picklist (with at least one and fewer than 300 values) or checkbox field on the same record.
How do you create a dependent picklist in flow?
Draw the Screen flow element to the canvas. B. Drag the Dependent Picklist standard component to the screen area and configure it accordingly.
What is a dependent field in Salesforce?
Field Dependencies in Salesforce are the filters that allow user to change the contents of a picklist based on the value of another field. Example :- Here there are two field called Country and State. We have to display all states that are related to Country Field.
Related Topics | You May Also Like
Our Free Courses β
π Get Free Course β
π Salesforce Administrators π Salesforce Lightning Flow Builder π Salesforce Record Trigger Flow Builder |
π Get Free Course β
π Aura Lightning Framework π Lightning Web Component (LWC) π Rest APIs Integration |