Search code examples
aem

Data attributes for Select widget items in AEM when using datasource


I want to use the Data Source mechanism for granite/ui/components/coral/foundation/form/select widget in AEM dialog.

I want to render additional data attributes in the HTML of select items. When not using data source and having the select items directly in the dialog's XML file, I can add the data attributes using granite:data node:

<text
        jcr:primaryType="nt:unstructured"
        text="Text"
        value="text">
    <granite:data
            jcr:primaryType="nt:unstructured"
            custom-attribute="custom-attribute-value"/>
</text>

Is it possible to somehow include the data attribute when the items are coming from a Data Source Servlet? I am using this example code for my data source servlet. In particular, I'm updating the value map of the resource and returning it to the dialog. Is there anything I can do with this value map to render `data-custom-attribute="custom-attribute-value" in the particular element's HTML?

private Resource getItemResource(ResourceResolver resolver, String text, String value) {
    ValueMap vm = new ValueMapDecorator(new HashMap<>());
    vm.put("text", text);
    vm.put("value", value);

    return new ValueMapResource(resolver, "", "", vm);
}

Adding additional entries to this map indeed causes rendering of data attributes for granite/ui/components/foundation/form/select, but not for granite/ui/components/coral/foundation/form/select which I want to use.


Solution

  • We can add a child node with a name granite:data to the resource that we will be returning from the DataSource servlet. The properties of this child node will become pairs of data attributes in the markup. I don't think this is possible using ValueMapResource, as in the question, but can be done using real resources that are stored in JCR.

    A number of other properties can be added to the original resource (not as children), and they will get rendered in the HTML markup, too:

    • granite:id
    • granite:rel
    • granite:class
    • granite:title
    • granite:hidden
    • granite:itemscope
    • granite:itemtype
    • granite:itemprop