AEM: Create a dynamic dropdown(Javascript) based on value of other dropdown

Hello, Let us see how to create a dynamic dropdown options based on value of another dropdown.

Use Case: 

In some cases we might need to generate a dynamic dropdown options based on value of an another dropdown. Just like selecting a country  should change the cities list.

Implementation:

Create dialog fields:

I have demo component and there are two dropdowns inside that as part of authoring dialog. The first dropdown(Country) will have list of countries and the second dropdown(Cities) should have cities related to that particular country.

demo-dialog


 The first dropdown(Countries) has static options configured as nodes to select field. (Check out my post to generate dropdown from JSON file from backend JSP)

country-field


The second dropdown(Cities) does not have configured nodes under select field but the values will be populated through JavaScript.


cities-field


Now we are ready with the dialog. Lets create a JSON associated to Country field options.

Create a JSON file and upload in DAM:

I have five countries under my Country dropdown and the Name and Value for each dropdown option configured in node are as follows.

Country:

        "text": "Australia",
"value": "australia"
"text": "France",
"value": "france"
"text": "India",
"value": "india"
"text": "United Kingdom",
"value": "uk"
"text": "United States",
"value": "us"

Now lets create a cities.json file which will have City names associated to each Country option.

JSON file(cities.json)


{
   "australia":[
      {
         "text":"Sydney",
         "value":"sydney"
      },
      {
         "text":"Melbourne",
         "value":"melbourne"
      },
      {
         "text":"Perth",
         "value":"perth"
      },
      {
         "text":"Adelaide",
         "value":"adelaide"
      },
      {
         "text":"Brisbane",
         "value":"brisbane"
      }
   ],
   "france":[
      {
         "text":"Paris",
         "value":"paris"
      },
      {
         "text":"Marseille",
         "value":"marseille"
      },
      {
         "text":"Bordeaux",
         "value":"bordeaux"
      },
      {
         "text":"Strasbourg",
         "value":"strasbourg"
      },
      {
         "text":"Nantes",
         "value":"nantes"
      }
   ],
   "india":[
      {
         "text":"Mumbai",
         "value":"mumbai"
      },
      {
         "text":"Bengaluru",
         "value":"bengaluru"
      },
      {
         "text":"New Delhi",
         "value":"delhi"
      },
      {
         "text":"Hyderabad",
         "value":"hyderabad"
      },
      {
         "text":"Chennai",
         "value":"chennai"
      }
   ],
   "uk":[
      {
         "text":"London",
         "value":"london"
      },
      {
         "text":"Manchester",
         "value":"manchester"
      },
      {
         "text":"Edinburgh",
         "value":"edinburgh"
      },
      {
         "text":"Cambridge",
         "value":"cambridge"
      },
      {
         "text":"Leeds",
         "value":"leeds"
      }
   ],
   "us":[
      {
         "text":"New York",
         "value":"new-york"
      },
      {
         "text":"San Francisco",
         "value":"san-francisco"
      },
      {
         "text":"Los Angeles",
         "value":"los-angeles"
      },
      {
         "text":"Cambridge",
         "value":"cambridge"
      },
      {
         "text":"Washington, D.C.",
         "value":"washington-dc"
      }
   ]
}

Each keys in JSON file should exactly match with the values of each Country option.

Now upload this JSON file in DAM.

Dialog listener (JavaScript):

Now create a node under tab/items with name clientlibs and add below properties

sling:resourceType (String) granite/ui/components/coral/foundation/includeclientlibs 

js (String) <category_name>

clientlib-node


Now create a client library folder and write JavaScript.

I have created a folder under my component and inside that I created a client library folder.

  1. Create a folder clientlibs(sling:Folder) under component node (parellel to cq:dialog)
  2. Create a folder editor(cq:clientLibraryFolder) under clientlibs and added property categories String[] <category_name> (Must be same as value configured in dialog node)
  3. Create a folder js(nt:folder) and create a file listener.js inside it
  4. Create a file js.txt parallel to js folder and add #base=js listener.js (in two different lines)
  5. Save changes
clientlib-files

js.txt file

js.txt


Now lets start writing listener to populate the values in cities dropdown. Open listener.js and paste the below code.

Below is the listener to populate the dropdown fields. Here am using hardcoded options.

(function ($, document, ns) {
    $(document).on("dialog-ready", function() {
    // In dialog ready lets request the JSON and store it
        let citiesJSON;
$.ajax({
            url: "/content/dam/adapttoaem/dialog/json/cities.json", //Update the path
            async: false,
            success: function (data) {
                citiesJSON = data;
            }
        });

        const setCitiesOptions = function () {
            let citiesField = $(".cq-dialog").find("#cities")[0];
            let countryValue = $(".cq-dialog").find("#country")[0].selectedItem.value;
            let options = citiesJSON[countryValue];
            let optionItems = citiesField.items;
            optionItems.clear();
            for (var i = 0; i < options.length; i++) {
                let obj = new Object();
                let cnt = new Object();
                obj["value"] = options[i].value;
                cnt["textContent"] = options[i].text;
                obj["content"] = cnt;
                optionItems.add(obj);
            }
        };


       $(".cq-dialog").find("#country").on("change", setCitiesOptions);
        setCitiesOptions();
    });
})(Granite.$, document, Granite.author);

Now, Lets drop the component on page and open the dialog.

dailog-with-options

Yayy..... We see options loading in cities dropdown. Now try changing the Country options, Cities will also change accordingly.

Is that it?

Hmmm... No. 

Now let us select India from Country dropdown and then select New Delhi from cities and submit the dialog and re-open the dialog again.


dialog-reopen

oh-nooo



Let us fix this.

There are two ways to fix this.

  1. Getting the node value from backend(datasource) and use it in Javascript.
  2. Do an AJAX call to page/component path and get the node value and set the value.

It is not a best practice to do AJAX calls (here we are already getting JSON using AJAX call). If we can do this from backend why do we need to do one more AJAX call from frontend? Let go with backend datasource approach. 

Create a datasource for cities dropdown.

  • Create a node name - datasource, type - nt:unstructured under cities dropdown field.
  • Set property sling:resourceType and give a path datasource (same path as below).
  • Create a folder under your project ( here I'm using /apps/adapttoaem/components/datasource/cities).
  • Create a jsp file with name cities.jsp(parent folder name and file name must be same) inside /apps/adapttoaem/components/datasource/cities.
  • Add the blow code.
  • Save the changes

<%@page session="false" 
import="org.apache.sling.api.resource.Resource,
        org.apache.sling.api.resource.ValueMap,
        org.apache.sling.api.resource.ResourceMetadata,
        org.apache.sling.api.wrappers.ValueMapDecorator,
com.adobe.granite.ui.components.Field,
        com.adobe.granite.ui.components.ds.DataSource,
        com.adobe.granite.ui.components.ds.SimpleDataSource,
        com.adobe.granite.ui.components.ds.ValueMapResource"%>

<%@taglib prefix="cq" uri="http://www.day.com/taglibs/cq/1.0" %>
<cq:defineObjects/>

<%            
ValueMap fieldProps = (ValueMap)request.getAttribute(Field.class.getName());
String[] fieldVal = fieldProps.get("value", new String[0]);
String value = "";
if (fieldVal.length > 0) {
value = fieldVal[0];
}

ValueMap vm = new ValueMapDecorator(new java.util.HashMap<String, Object>());
vm.put("value", value);
//ArrayList to hold data
java.util.List<Resource> resourceList = new java.util.ArrayList<Resource>();
resourceList.add(new ValueMapResource(resourceResolver, new ResourceMetadata(), "nt:unstructured", vm));
//Create a DataSource that is used to populate the drop-down control
request.setAttribute(DataSource.class.getName(), new SimpleDataSource(resourceList.iterator()));
%>

Here in datasource jsp, we are setting the node value to dropdown field. Now we will update our listener JavaScript file and fetch the node(field) value before  injecting options.
Once options are injected, we will set the field value to dropdown field.

Now lets get back to our listener.js and finish the job.

Final listener.js code

(function ($, document, ns) {
    $(document).on("dialog-ready", function() {
    // In dialog ready lets request the JSON and store it
        let citiesJSON;
$.ajax({
            url: "/content/dam/adapttoaem/dialog/json/cities.json", //Update the path
            async: false,
            success: function (data) {
                citiesJSON = data;
            }
        });

        const setCitiesOptions = function () {
            let countryValue = $(".cq-dialog").find("#country")[0].selectedItem.value;
            let citiesField = $(".cq-dialog").find("#cities")[0];
            //Getting the value set from datasource
            let citiesNodeVal = citiesField.selectedItem.value;

            let options = citiesJSON[countryValue];
            let optionItems = citiesField.items;
            optionItems.clear();
            for (var i = 0; i < options.length; i++) {
                let obj = new Object();
                let cnt = new Object();
                obj["value"] = options[i].value;
                cnt["textContent"] = options[i].text;
                obj["content"] = cnt;
                optionItems.add(obj);
            }
            if (citiesNodeVal !== "") // Set the value once options are loaded 
        $(citiesField).find("coral-select-item[value='"+citiesNodeVal+"']").attr("selected", "selected");
        };


       $(".cq-dialog").find("#country").on("change", setCitiesOptions);
        setCitiesOptions();
    });
})(Granite.$, document, Granite.author);


Yesss.... Just Highlighted 3 lines of code. We are done.

Here in the above code, I am getting the value that we did set from datasource(First highlighted line). And once the options are injected then we are setting back the node value to the dropdown(Last two highlighted lines).

Now let's reload the page(hard refresh to make sure js is updated), open the dialog and check.


Ta-Da


final-dialog


Hurrah.... Here we go, the value has been set.

Hope you liked the post and it helped. Meet you in next post. Thank you very much for your time.

-AG


3 comments:

  1. Nice post, but I can't see the images

    ReplyDelete
  2. Nevermind, it was my vpn, thank you!

    ReplyDelete
  3. Is this for AEM assets? I'm trying to figure out how to do this without having to add each option in from the front end in Assets.

    ReplyDelete