Dynamically Populate Select Options in AEM Component Dialog
Published
Using ACS AEM Commons
/etc/acs-commons/lists
.datasource
, Generic List items can be loaded into select lists. To achieve this, Generic List-specific datasource can be used.article / _cq_dialog / .content.xml
<articleTypes jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/foundation/form/select"
fieldLabel="Article Types"
name="./articleTypes">
<datasource jcr:primaryType="nt:unstructured"
sling:resourceType="acs-commons/components/utilities/genericlist/datasource"
path="/etc/acs-commons/lists/article-types" />
</articleTypes>
Using Sling Servlet
article / _cq_dialog / .content.xml
<articleTypes jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/coral/foundation/form/select"
fieldLabel="Article Types"
name="./articleTypes">
<datasource jcr:primaryType="nt:unstructured"
types="articleTypes"
sling:resourceType="/bin/public/aem-demo/dropdowns"/>
</articleTypes>
types
are passed in the above example.servlets / DropdownServlet.java
public class DropdownServlet extends SlingSafeMethodsServlet {
DropdownService dropdownService;
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) {
ResourceResolver resolver = request.getResourceResolver();
// Current Page Path
String currentPagePath = request.getRequestPathInfo().getSuffix();
// Fetch Property from datasource
Resource datasource = request.getResource().getChild("datasource");
ValueMap vm = datasource.getValueMap();
String type = vm.get("types", ""); // articleTypes
// Fetch dropdown options from External Source or other Component properties
List<String> options = dropdownService.getOptions(currentPagePath, type);
DataSource dataSource = new SimpleDataSource(
new TransformIterator<>(options.iterator(), input -> {
ValueMap valueMap = new ValueMapDecorator(new HashMap<>());
valueMap.put("value", input);
valueMap.put("text", input);
return new ValueMapResource(
resolver, new ResourceMetadata(), JcrConstants.NT_UNSTRUCTURED, valueMap);
}));
request.setAttribute(DataSource.class.getName(), dataSource);
}
}