Hello, Let us see how to create a dropdown values using JSON file which is inside DAM. I am going to explain how to achieve this using JSP file.
Use case:
In some cases authors or business might want to add or remove values from dropdown of a authoring dialog. A JSON file inside DAM will be easy for authors to update whenever required without a Developer intervention.
Why JSP?
- We know that the JSP is internally a Servlet.
- As JSP file will be as part of our component code base, it is very is easy to update.
- The usage of this JSP file is only as part Dialog/Edit mode.
Implementation:
I have created a Demo Component which is having a Language dropdown inside authoring dialog.
Now instead of creating options nodes under items, we will create a data source node under the coral select field.
- Create a node under select field with name datasource type nt:unstructured
- Add sling:resourceType property and give datasource(JSP) path (yet to create)
Now let us create a folder(nt:folder) with same path as we configured in datasource node. Create a file(language.jsp) under the folder.
Here I have created a folder under my project/component folder with name datasource and inside that I have created a folder with name language similar to the path I have specified in datasource node.
Under language folder I have created a jsp file with name language.jsp (jsp file name and folder name must be same).
Now let us create and upload a JSON file in DAM
Here in this example I have created a JSON file(language.json) with different languages like below and uploaded in DAM.
[
{
"value": "arabic",
"text": "Arabic"
},
{
"value": "chinese",
"text": "Chinese"
},
{
"value": "dutch",
"text": "Dutch"
},
{
"value": "english",
"text": "English"
},
{
"value": "french",
"text": "French"
},
{
"value": "german",
"text": "German"
},
{
"value": "italian",
"text": "Italian"
},
{
"value": "japanese",
"text": "Japanese"
},
{
"value": "russian",
"text": "Russian"
}
]
Logic to read JSON file and add options to select(dropdown)
Now inside the jsp file add the below code to read JSON file and add options to select field.
Highlighted (in yellow color) path in above code is the JSON file which we dropped inside DAM.
Here I am using json-simple bundle to parse the InputStream in to JSON Array. Below is the maven dependency and link(can directly download and install in Felix Console).
https://mvnrepository.com/artifact/com.googlecode.json-simple/json-simple/1.1.1
Output:
Now lets create a page and drop our Demo component and open the dialog.
Hope you liked the post and it helped. Meet you in next post. Thank you very much for your time.
See how to Create a dynamic dropdown(Javascript) based on value of other dropdown