Dynamic custom dependent picklist in lightning component | how to create custom dependent pick-list dynamically in Salesforce lightning component

3,566 views


Hey guys, today in this post we are going to learn about How to create custom dependent Picklist dynamically in lightning component.

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,
Gujrat,
Madhya Pradesh

Custom City Picklist Fields and there Option:- City__c

Ajmer,
Jaipur,
Kota,
Udaypur,
Bharuch,
Ahmedabad,
Surat,
Gandhi Nagar,

Bhopal,
Indore,
Jabalpur

Custom Object and their fields

It’s retrieve custom field of sObject.

 

Final Output

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!

 

w3web.net--dynamic dependent picklist in lightning component

 

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.

w3web.net -- dynamic dependent picklist in lightning component

Step 1:- Create Lightning Application : lightningDependentPicklistApp.app

Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 

From Developer Console >> File >> New >> Lightning Application

lightningDependentPicklistApp.app [Component Application File]

  1.   <aura:application extends="force:slds">
  2.     <c:lightningDependentPicklistCmp/>
  3. </aura:application>

Step 2:- Create Lightning Component : lightningDependentPicklistCmp.cmp

From Developer Console >> File >> New >> Lightning Component

lightningDependentPicklistCmp.cmp [Lightning Component File]

  1.   <aura:component controller="dependentPicklistController" implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,force:hasRecordId" access="global" >
  2. 	 <aura:handler name="init" value="{!this}" action="{!c.doInit}" />   
  3.  
  4.     <aura:attribute name="getParentList" type="list" default="[]" description=""/>
  5.     <aura:attribute name="getChildList" type="list" default="[]"/>
  6.     <aura:attribute name="getPickListMap" type="map"/>
  7.     <aura:attribute name="getDisabledChildField" type="boolean" default="true"/>
  8.  
  9.     <aura:attribute name="getObjectName" type="string" default="NewStudent__c"/>
  10.     <aura:attribute name="getParentFieldAPI" type="string" default="State__c"/>
  11.     <aura:attribute name="getChildFieldAPI" type="string" default="City__c"/>
  12.     <aura:attribute name="getParentFieldLabel" type="string" />
  13.     <aura:attribute name="getChildFieldLabel" type="string"/>
  14.     <aura:attribute name="getParentValue" type="string" default=""/>
  15.     <aura:attribute name="getChildValue" type="string" default=""/>
  16.  
  17.  
  18.    <lightning:card title="Dependent Picklist Demo">
  19.       <div class="slds-grid slds-wrap"> 
  20.            <div class="slds-col slds-col_size-6-of-12">
  21.                 <!-- Custom Controller Field -->
  22.                 <lightning:layoutItem size="12" padding="around-small">    
  23.                     <lightning:select name="parentField" aura:id="parentField"
  24.                                       value="{!v.getParentValue}"
  25.                                       label="{!v.getParentFieldLabel}"
  26.                                       onchange="{!c.ObjFieldByParent}">
  27.                         <aura:iteration items="{!v.getParentList}" var="value">
  28.                             <option value="{!value}">{!value}</option>
  29.                         </aura:iteration>
  30.                     </lightning:select>
  31.                 </lightning:layoutItem>
  32.                </div> 
  33.  
  34.              <div class="slds-col slds-col_size-6-of-12">
  35.                 <!--Custom Dependable Field-->
  36.                 <lightning:layoutItem size="12" padding="around-small">
  37.                     <lightning:select name="childField"
  38.                                       value="{!v.getChildValue}"
  39.                                       label="{!v.getChildFieldLabel}"
  40.                                       disabled="{!v.getDisabledChildField}">
  41.                         <aura:iteration items="{!v.getChildList}" var="value">
  42.                             <option value="{!value}">{!value}</option>
  43.                         </aura:iteration>
  44.                     </lightning:select>
  45.                 </lightning:layoutItem>
  46.           </div>    
  47.       </div>    
  48.  
  49. <br/><br/>
  50.    <!--Start RelatedTopics Section-->
  51. <div style="border:1px #ddd solid; padding:10px; background:#eee; margin:40px 0;">
  52.  
  53.             <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>
  54.  
  55.             <br/><br/>
  56.             <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>
  57.             <div style="display:block; overflow:hidden;"> 
  58.                 <div style="width: 50%; float:left; display:inline-block">
  59.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  60.                         <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>
  61.                         <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>
  62.                         <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>
  63.                         <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>
  64.                         <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>
  65.                     </ul>
  66.             </div>
  67.  
  68.             <div style="width: 50%; float:left; display:inline-block">
  69.                     <ul style="list-style-type: square; font-size: 16px; margin: 0 0 0 54px; padding: 0;"> 
  70.                         <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>
  71.                         <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>
  72.                         <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>
  73.                         <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>
  74.                         <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>
  75.                     </ul>
  76.                 </div>
  77.                <div style="clear:both;"></div> 
  78.                <br/>
  79.                 <div class="youtubeIcon">
  80.                     <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>
  81.                 </div>
  82.     </div>
  83.  
  84. </div>
  85.  
  86.   <!--End RelatedTopics Section-->
  87.  
  88.     </lightning:card> 
  89. </aura:component>

Step 3:- Create Lightning Component : lightningDependentPicklistCmpController.js

From Developer Console >> File >> New >> Lightning Component >> JavaScript Controller

lightningDependentPicklistCmpController.js [JavaScript Controller]

  1.    ({
  2. 	doInit : function(component, event, helper) {
  3.  
  4. 		var action = component.get("c.customDependablePicklist");
  5.         action.setParams({
  6.             strObjectName : component.get("v.getObjectName"),
  7.             strparentField : component.get("v.getParentFieldAPI"),
  8.             strchildField : component.get("v.getChildFieldAPI")
  9.         });
  10.  
  11.         action.setCallback(this, function(response){
  12.          	var status = response.getState();
  13.             if(status === "SUCCESS"){
  14.                 var pickListResponse = response.getReturnValue();                
  15.  
  16.                 component.set("v.getPickListMap",pickListResponse.pickListMap);
  17.                 component.set("v.getParentFieldLabel",pickListResponse.parentFieldLabel);
  18.                 component.set("v.getChildFieldLabel",pickListResponse.childFieldLabel);
  19.                 var pickListMap = component.get("v.getPickListMap");
  20.  
  21.                 var parentkeys = [];
  22.                 var parentField = [];                
  23.  
  24.                 for (var pickKey in pickListResponse.pickListMap) {
  25.                     parentkeys.push(pickKey);
  26.                 }
  27.  
  28.                 if (parentkeys != undefined && parentkeys.length > 0) {
  29.                     parentField.push('--- None ---');
  30.                 }
  31.  
  32.                 for (var i = 0; i < parentkeys.length; i++) {
  33.                     parentField.push(parentkeys[i]);
  34.                 }  
  35.  
  36.                 component.set("v.getParentList", parentField);
  37.  
  38.             }
  39.         });
  40.  
  41.         $A.enqueueAction(action);
  42. 	},
  43.  
  44.     ObjFieldByParent : function(component, event, helper) {
  45.     	var controllerValue = component.find("parentField").get("v.value");
  46.         var pickListMap = component.get("v.getPickListMap");
  47.  
  48.         if (controllerValue != '--- None ---') {             
  49.             var childValues = pickListMap[controllerValue];            
  50.             var childValueList = [];
  51.             childValueList.push('--- None ---');
  52.             for (var i = 0; i < childValues.length; i++) {
  53.                 childValueList.push(childValues[i]);
  54.             }
  55.  
  56.             component.set("v.getChildList", childValueList);
  57.  
  58.             if(childValues.length > 0){
  59.                 component.set("v.getDisabledChildField" , false);  
  60.             }else{
  61.                 component.set("v.getDisabledChildField" , true); 
  62.             }
  63.  
  64.         } else {
  65.             component.set("v.getChildList", ['--- None ---']);
  66.             component.set("v.getDisabledChildField" , true);
  67.         }
  68. 	}    
  69.  })

Step 4:- Create Lightning Application : dependentPicklistController.apxc

From Developer Console >> File >> New >> Apex Class

dependentPicklistController.apxc [Apex Class Controller]

  1.   public WITH sharing class dependentPicklistController {
  2. 	private static final String getAlphaChars = '' +
  3.         'ABCDEFGHIJKLMNOPQRSTUVWXYZ' +
  4.         'abcdefghijklmnopqrstuvwxyz' +
  5.         '0123456789+/';
  6.  
  7.     @AuraEnabled 
  8.     public static customPicklistWrapper customDependablePicklist(String strObjectName, string strparentField, string strchildField) {
  9.         Map<String,List<String>> pickListMap = NEW Map<String,List<String>>();
  10.         customPicklistWrapper pw = NEW customPicklistWrapper();
  11.         pw.pickListMap = pickListMap;
  12.  
  13.         IF (Schema.getGlobalDescribe().get(strObjectName) ==NULL || String.isBlank(strparentField) || String.isBlank(strChildField)){
  14.             RETURN pw;
  15.         }
  16.  
  17.         Schema.sObjectType objType = Schema.getGlobalDescribe().get(strObjectName).newSObject().getSObjectType();
  18.         Map<String, Schema.SObjectField> objFieldMap = objType.getDescribe().fields.getMap();
  19.  
  20.         IF (!objFieldMap.containsKey(strparentField) || !objFieldMap.containsKey(strchildField)){
  21.             RETURN pw;     
  22.         }
  23.  
  24.         List<customPicklistEntryWrapper> depEntriesList = (List<customPicklistEntryWrapper>)JSON.deserialize(JSON.serialize(objFieldMap.get(strChildField).getDescribe().getPicklistValues()), List<customPicklistEntryWrapper>.class);
  25.         List<String> controllingValues = NEW List<String>();
  26.  
  27.         FOR (Schema.PicklistEntry ple : objFieldMap.get(strparentField).getDescribe().getPicklistValues()) {
  28.             pickListMap.put(ple.getLabel(), NEW List<String>());
  29.             controllingValues.add(ple.getLabel());
  30.         }
  31.  
  32.         FOR (customPicklistEntryWrapper plew : depEntriesList) {
  33.             String validForBits = alphaBaseToBits(plew.validFor);
  34.             FOR (INTEGER i = 0; i < validForBits.length(); i++) {
  35.                 String bit = validForBits.mid(i, 1);
  36.                 IF (bit == '1') {
  37.                     pickListMap.get(controllingValues.get(i)).add(plew.label);
  38.                 }
  39.             }
  40.         }
  41.  
  42.         pw.pickListMap = pickListMap;
  43.         pw.parentFieldLabel = objFieldMap.get(strparentField).getDescribe().getLabel();
  44.         pw.childFieldLabel = objFieldMap.get(strchildField).getDescribe().getLabel();
  45.         RETURN pw;
  46.     }
  47.  
  48.  
  49.     public static String decimalToBinary(INTEGER val) {
  50.         String bits = '';
  51.         while (val > 0) {
  52.             INTEGER remainder = Math.mod(val, 2);
  53.             val = INTEGER.valueOf(Math.floor(val / 2));
  54.             bits = String.valueOf(remainder) + bits;
  55.         }
  56.         RETURN bits;
  57.     }
  58.  
  59.     public static String alphaBaseToBits(String validFor) {
  60.         IF (String.isEmpty(validFor)) RETURN '';
  61.  
  62.         String validForBits = '';
  63.  
  64.         FOR (INTEGER i = 0; i < validFor.length(); i++) {
  65.             String thisChar = validFor.mid(i, 1);
  66.             INTEGER val = getAlphaChars.indexOf(thisChar);
  67.             String bits = decimalToBinary(val).leftPad(6, '0');
  68.             validForBits += bits;
  69.         }
  70.  
  71.         RETURN validForBits;
  72.     }
  73.  
  74.     public class customPicklistWrapper{
  75.     	@AuraEnabled
  76.         public Map<String, List<String>> pickListMap;
  77.         @AuraEnabled
  78.         public String parentFieldLabel;
  79.         @AuraEnabled
  80.         public String childFieldLabel;      
  81.     }
  82.  
  83.     public class customPicklistEntryWrapper{
  84.         public String active;
  85.         public String defaultValue;
  86.         public String label;
  87.         public String VALUE;
  88.         public String validFor;
  89.  
  90.     }
  91.  }

 

Further post that would you like to learn in Salesforce

 

 

 

FAQ (Frequently Asked Questions)

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

 
Note:: – You will get an email, so put correct email and mobile number and BEGIN YOUR JOURNEY from Today!
 
 
  

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



Hi, This is Vijay Kumar behind the admin and founder of w3web.net. I am a senior software developer and working in MNC company from more than 8 years. I am great fan of technology, configuration, customization & development. Apart of this, I love to write about Blogging in spare time, Working on Mobile & Web application development, Salesforce lightning, Salesforce LWC and Salesforce Integration development in full time. [Read full bio] | | The Sitemap where you can find all published post on w3web.net

Leave a Comment