Populate Touch UI Dropdown options from JSON file or Servlet which returns JSON
In AEM classic UI, the selection/dropdown widget's options can be populated using JSON response(via JSON file or servlet) but in Touch UI, you need to write a piece of code to achieve same. This blog is about a utility which populates dropdown options dynamically from a JSON file which presents in the repository or from the servlet JSON response.Custom Utility to populate a dropdown
This custom java utility populates touch UI dropdown from JSON data.Steps are as follows:
- Create a dropdown using granite/coral select type and create datasource node under the select node.
- Add following properties to datasource node :
- options (String) - path of json file or Servlet, which returns json examples : /apps/commons/utils/json/dropdown/color.json /bin/utils/json/dropdown/style - sling:resourceType (String) - utils/granite/components/select/datasource/json- repoSource (Boolean) - optional property to specify file in repository or servlet json source. - true(Default) : to read JSON file stored in repository
- false : to get JSON from another Servlet
if repoSource property is true JSON file will be read using Node API, if false then another HTTP call is to be made to get JSON response either from json file or servlet.
if repoSource is false it works in both cases in file or servlet JSON response. This property is just added to avoid unnecessary HTTP call if the file is in the repository.
datasource node properties |
Utility Servlet code
https://github.com/arunpatidar02/aem63app-repo/blob/master/java/dropdown/PopulateTouchUIDropdownFromJsonResource.java
POM file changes
Add below dependencies in parent and core pom(if not already added)
1. GSON
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
2. HTTP Client
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.5</version>
</dependency>
Example JSON file/response
The Josn response can have array of options in below formates:
{"text": "White","value": "white"}
{"text": "White","value": "white","disabled": true} - to disable option in dropdown
{"text": "White","value": "white","selected": true} - to preselect option in dropdown
Example file -
https://github.com/arunpatidar02/aem63app-repo/blob/master/java/dropdown/sample.json
This comment has been removed by a blog administrator.
ReplyDeleteHi, I need to render the json present in the dam path to my dropdown . So , could you please let me know whether this approach will work.
ReplyDeleteHi, This will work but you need to read original rendition of xml to get the binary stream
Delete