May 15, 2020
Estimated Post Reading Time ~

Dynamic Dropdown in AEM Content Fragments

In this post, I’ll show you how to easily and cleanly create a dynamic dropdown in an AEM Content Fragment Model driven by an ACS AEM Commons Generic List.

What are Content Fragments?
But first, what are Content Fragments? Content Fragments are a powerful feature in Adobe Experience Manager (AEM) for managing structured content.

Each Content Fragment has a model that defines the structure of the Content Fragment. To edit the model, Adobe provided an editor with common fields, including text fields, number fields, and dropdowns (called Enumerations).


Why isn’t this Out of the Box?
Unfortunately, when Adobe implemented the Content Fragment Model editor, they didn’t consider extensibility. The fields are very limited and there is no API for adding custom fields.

Despite these significant shortcomings, Content Fragments make managing simple content structures effortless, due to their simplicity and ease of use.

While Adobe made it harder for implementors by failing to follow best practices, like using Sling Resource Merger or structuring components in a sane manner, we are using Apache Sling. So, we can “kick it old school” and overlay the component.

Our Mission Statement
The Enumerations field included in Content Fragment Models only supports setting a static set of options. This is good enough for slideware, but in real life, it’s inadequate. A couple problematic use cases include:
Multiple models sharing the same set of values
Lists of options where new options need to be dynamically added
Option lists which change their options in the context of where / how the Content Fragment is used

The Solution
To create a dynamic dropdown, we’ll overlay the JSP script used to generate the dropdown options from the static list: /libs/dam/cfm/admin/components/datasources/optionrenderer/optionrenderer.jsp

By creating a script at: /apps/dam/cfm/admin/components/datasources/optionrenderer/optionrenderer.jsp

Since Sling prioritizes /apps over /libs when it looks up scripts, our script will get called instead of the original script.

The original script is simple; it hackily converts the String of comma-separated options into a com.adobe.granite.ui.components.ds.DataSource object and then sets that as a request object. Pretty easy to reproduce! But of course, we don’t want to break the existing functionality.

To avoid breaking the existing functionality, we can prefix all of our dynamic dropdowns with a known prefix. This will also allow us to even have multiple different types of dropdown population methods.

In this example, we’ll use the prefix: “acs-commons-list:” for populating a dropdown of the values of an ACS AEM Commons Generic List. Additionally, we have to use a Lambda function to map the properties in the Generic List into the format used by the DataSource. All said and done, here’s what the script looks like:

<%--
Copyright 2019 Perficient Digital

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--%>
<%@include file="/libs/granite/ui/global.jsp" %>
<%@page session="false" import="com.adobe.granite.ui.components.ds.*,java.util.*,java.util.stream.*,org.apache.sling.api.resource.ResourceMetadata,org.apache.sling.api.wrappers.ValueMapDecorator,org.apache.sling.api.resource.ResourceResolver" %>
<%
final ResourceResolver resolver = resourceResolver;
String optv = resource.getValueMap().get("options","");
if (optv.startsWith("acs-commons-list:")) {
String listPath = optv.substring(optv.indexOf(":") + 1);

log.debug("Retrieving items from: {}", listPath);
List<Resource> options = StreamSupport.stream(resourceResolver.getResource(listPath + "/jcr:content/list").getChildren().spliterator(), false)
.map(op -> {
Map<String,Object> data = new HashMap<>();
data.put("value", op.getValueMap().get("value",""));
data.put("text", op.getValueMap().get("jcr:title",""));
return new ValueMapResource(resolver, new ResourceMetadata(), "nt:unstructured", new ValueMapDecorator(data));
}).collect(Collectors.toList());
request.setAttribute(DataSource.class.getName(), new SimpleDataSource(options.iterator()));
} else { %>
<sling:call script="/libs/dam/cfm/admin/components/datasources/optionrenderer/optionrenderer.jsp" />
<% } %>

Once we have the script in place, we can use dynamic and static dropdowns together.

With this technique, we are no longer constrained to static dropdowns with AEM Content Fragments. With more prefixes, we can have even more options to populate dynamic dropdowns.


By aem4beginner

No comments:

Post a Comment

If you have any doubts or questions, please let us know.