Quick Read | What is ContentPolicyManager in AEM?

ContentPolicyManager is a service that facilitates the management and application of content policies to components. Content policies are configurations that define how components should behave and appear on a page. They help enforce consistency in design, styling, and behavior across different instances of the same component.

So if you want to pick up different value for a component based on different policy attached to a component we can use ContentPolicyManager which gives us the exact value attached to that component in design dialog based on the policy.

Let’s see how we can write the code to get the values

ResourceResolver resourceResolver = request.getResourceResolver();
Resource currentResource = resourceResolver.resolve(request.getRequestPathInfo().getResourcePath());
ContentPolicyManager contentPolicyManager = resourceResolver.adaptTo(ContentPolicyManager.class);
ContentPolicy contentPolicy = contentPolicyManager.getPolicy(currentResource);

String deignDialogValue = contentPolicy.getProperties().get("nameProperty",String.class);

To get the object of the content policy manager we need to have resourceResolver. So in first step I am getting the resource resolver object from the request and later in step two i am getting the current resource .
Once we have Content Policy manager we can get the content policy for the current resource which will be specific to ONLY current resource i.e current component.
Once I have content policy object we get which ever design dialog property we want to fetch.

Some of the useful APIs of Content Policy are:

Some of the useful APIs of Content Policy Manager are:


NOTE: Above implementations works when you have a policy correctly attaches to a resource i.e component in AEM.

Thank you for reading.
Happy Coding!

Select All and De-Select All fields in Dropdown using Coral UI JavaScript in AEM

In this article we will try out a custom Coral UI Javascript in AEM and all a functionality to a dropdown where, dropdown will have n number of values and will have Select All and De-select All option as well in the dropdown. This is really helpful when you have lot’s of options in a dropdown and you have to select all and de-select all.

First create a simple AEM dropdown field with multiselect functionality and add some 5-6 options in the dropdown and then add two option with following text and value combination which will help us select all fields in dropdown as well as de-select all fields in dropdown.


NOTE: The name property used in this article is ./country for the dropdown.



Select All option:

text: Select All (You can keep any name as it just shows on the UI).
value: all (We are keeping all here because we will be using the same value in JS)

Deselect All option:

text: De-Select All (You can keep any name as it just shows on the UI).
value: none (We are keeping none here because we will be using the same value in JS)

Now create a clientlibrary in AEM with category name as cq.myproject.select-deselect. And then attach this clientlib at the cq:dialog node of the component by adding the following property at cq:dialog node.

extraClientlibs – String – cq.myproject.select-deselect

Once we are done setting up everything then paste the following code in your JS file of the clientlibs and checkout the functionality in the dropdown.

(function (document, $){
"use strict";

$(document).on("foundation-field-change", "coral-select[name='./country']", function (e) {
let postSelect = $("coral-tag[aria-selected='true']").val();
let allDropdownselect=($(this).Find("coral-selectlist-item(value='all']")).is(':selected');
let nodropdownSelect = ($(this).find("coral-selectlist-item[value='none']")).is(':selected');
        if (!!allDropdownselect  && !postSelect) {
            $(this) .find("coral-selectlist-item[value! ='none']").attr("selected", true);
            $(this). find("coral-tag[value='all']"). remove();
        }
        if (!!nodropdownSelect  && !postSelect) {
            $(this).find("coral-selectlist-item[value!='none']").attr("selected", false);
            $(this).find("coral-tag[value='none' ]") .remove();
        }
    });
}) (document, Granite.$);



Also if you want to customise the above Coral UI JS as per your name property and dropdown options then you need to update the following props.

Field NamePurpose
./countryUsed as the name property of the dropdown field
allUsed as the value of Select All dropdown field
noneUsed as the value of De-Select All dropdown field

Extending Core Component’s Model and Creating it’s new Implementation | AEM

The Core Components implement several patterns that allow easy customization, from simple styling to advanced functionality reuse.

The Core Components were designed from the beginning to be flexible and extensible. A look at an overview of their architecture reveals where customizations can be made.

Now let’s see how we can customise our AEM Core components business logic. We will try to customise the OOTB image core component. And the customisation that we are going to do is that, if image alt text is not authored, we will pick up the image alt text from the image name.

@Model(adaptables = SlingHttpServletRequest.class,
       adapters = Image.class,
       resourceType = "myproject/components/image")
public class ExtendedImageComponent implements Image {
   

   String alt;

   @ValueMapValue
   String altText;

   @ValueMapValue
   String fileReference;

    @Self @Via(type = ResourceSuperType.class)
    private Image image;

    @Override 
    public String getAlt() {
        return alt;

    }

    public Image getImage(){
        return image;
    }

    @PostConstruct
    protected void init(){

        if(null == altText && null!= fileReference){
            String [] imgPathArray = fileReference.split("/");
            alt = imgPathArray[imgPathArray-1];
        }

    }
  
}

In above java class we have used the adapter for Image.class and implemented the OOTB functionality for Image Component and using @Self annotation we have created a object of Image class so that we will go ahead and update the image.{{variable}} with model.image.{{variable}} to load the untouched functionality of the OOTB java class. whereas the customized altText here can be referred by model.alt.

No we can go ahead and replace the data-sly-use.image=”com.adobe.cq.wcm.core.components.models.Image” with data-sly-use.model=”com.myproject.core.components.models.ImageComponent”.

Now we can replace the custome altText which was image.alt to model.alt and rest of the image variable with model.image.{{variable}}.


Thank you for reading.
Happy Coding!

Maxlength custom validator for Richtext using Granite UI Jquery | AEMaaCs

As we all know that when it comes to apply the maxlegth property to a richtext field in AEM, it doesn’t actually work. Because RTE in dialog uses the concept of validation from the Form Validation in Granite UI. And, since, Inline-editing does not behave as a form, it can’t use that validation concept.

So we will make use of Granite UI api to create our custom validator which will help us to add validation of maxlength even on the richtext field in AEM TouchUI.

  1. Create a validator.js in clientlibs with following Jquery: Here we are targeting the richtext-container and inside that container we are targeting a class that we will provide to the richtext field i.e rich-custom using Granite UI Api.

;(function (window, $) {
    'use strict';
 
    var RichTextMaxLengthValidation= function () {
        var CONST = {
            TARGET_GRANITE_UI: '.coral-RichText-editable',
            ERROR_MESSAGE: 'Your text length is {0} but character limit is {1}!',
        };

        function init() {
            // register the validator which includes the validate algorithm
            $(window).adaptTo('foundation-registry').register('foundation.validation.validator', {
                selector: CONST.TARGET_GRANITE_UI,
                validate: function (el) {
                    var $rteField = $(el);
                    var $field = $rteField.closest('.richtext-container').find('input.rich-custom');
                    var maxLength = $field.data('maxlength');
                    var textLength = $rteField.text().trim().length;
                    if (maxLength && textLength > maxLength) {
                        return Granite.I18n.get(CONST.ERROR_MESSAGE, [textLength, maxLength]);
                    }
                    return null;
                }
            });
            // execute Jquery Validation onKeyUp
            $(document).on('keyup', CONST.TARGET_GRANITE_UI, function (e) {
                executeJqueryValidation($(this));
            });
        }

        function executeJqueryValidation(el) {
            var validationApi = el.adaptTo('foundation-validation');
            if (validationApi) {
                validationApi.checkValidity();
                validationApi.updateUI();
            }
        }
       return {
            init: init
        }
    }();
    RichTextMaxLengthValidation.init();
})(window, Granite.$);

2. Now add this validator.js in your js.txt and give the category of your clientlibs as cq.author.maxvalidator

#base=js
validator.js

3. Now once we have our validator.js ready now we will create our AEM dialog which will have a richtext field and we will give two properties to this richtext field in dialog.

  • maxlength – {String} – 60 //This is the maxlength of the richtext text.
  • class – {String} – rich-custom //This is the custom class that is used in validator to target the richtext field.

Also we need to add the extraClientlibs property on the cq:dialog to load the custom validator that we created in Step 1.

Following the dialog.xml of one my component where this custom validator is used to restrict the character count based on maxlength.

<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling=http://sling.apache.org/jcr/sling/1.0 xmlns:cq=http://www.day.com/jcr/cq/1.0 xmlns:jcr=http://www.jcp.org/jcr/1.0 xmlns:nt=http://www.jcp.org/jcr/nt/1.0
    jcr:primaryType="nt:unstructured"
    jcr:title="Richtext Maxlength"
    sling:resourceType="cq/gui/components/authoring/dialog"
    extraClientlibs="[cq.author.maxvalidator]">
    <content
        jcr:primaryType="nt:unstructured"
        sling:resourceType="granite/ui/components/coral/foundation/container">
        <items jcr:primaryType="nt:unstructured">
            <tabs
                jcr:primaryType="nt:unstructured"
                sling:resourceType="granite/ui/components/coral/foundation/tabs"
                maximized="{Boolean}true">
                <items jcr:primaryType="nt:unstructured">
                    <properties
                        jcr:primaryType="nt:unstructured"
                        jcr:title="Properties"
                        sling:resourceType="granite/ui/components/coral/foundation/container"
                        margin="{Boolean}true">
                        <items jcr:primaryType="nt:unstructured">
                            <columns
                                jcr:primaryType="nt:unstructured"
                                sling:resourceType="granite/ui/components/coral/foundation/fixedcolumns"
                                margin="{Boolean}true">
                                <items jcr:primaryType="nt:unstructured">
                                    <column
                                        jcr:primaryType="nt:unstructured"
                                        sling:resourceType="granite/ui/components/coral/foundation/container">
                                        <items jcr:primaryType="nt:unstructured">
                                            <caption
                                                jcr:primaryType="nt:unstructured"
                                                sling:resourceType="cq/gui/components/authoring/dialog/richtext"
                                                class="rich-custom"
                                                fieldDescription="A description to display as the subheadline for the teaser."
                                                fieldLabel="Caption"
                                                maxlength="60"
                                                name="./caption"
                                                removeSingleParagraphContainer="{Boolean}true"
                                                useFixedInlineToolbar="{Boolean}true">
                                                <rtePlugins jcr:primaryType="nt:unstructured">
                                                    <format
                                                        jcr:primaryType="nt:unstructured"
                                                        features="bold,italic"/>
                                                    <justify
                                                        jcr:primaryType="nt:unstructured"
                                                        features="-"/>
                                                    <links
                                                        jcr:primaryType="nt:unstructured"
                                                        features="modifylink,unlink"/>
                                                    <lists
                                                        jcr:primaryType="nt:unstructured"
                                                        features="*"/>
                                                    <misctools jcr:primaryType="nt:unstructured">
                                                        <specialCharsConfig jcr:primaryType="nt:unstructured">
                                                            <chars jcr:primaryType="nt:unstructured">
                                                                <default_copyright
                                                                    jcr:primaryType="nt:unstructured"
                                                                    entity="&amp;copy;"
                                                                    name="copyright"/>
                                                                <default_euro
                                                                    jcr:primaryType="nt:unstructured"
                                                                    entity="&amp;euro;"
                                                                    name="euro"/>
                                                                <default_registered
                                                                    jcr:primaryType="nt:unstructured"
                                                                    entity="&amp;reg;"
                                                                    name="registered"/>
                                                                <default_trademark
                                                                    jcr:primaryType="nt:unstructured"
                                                                    entity="&amp;trade;"
                                                                    name="trademark"/>
                                                            </chars>
                                                        </specialCharsConfig>
                                                    </misctools>
                                                    <paraformat
                                                        jcr:primaryType="nt:unstructured"
                                                        features="*">
                                                        <formats jcr:primaryType="nt:unstructured">
                                                            <default_p
                                                                jcr:primaryType="nt:unstructured"
                                                                description="Paragraph"
                                                                tag="p"/>
                                                            <default_h1
                                                                jcr:primaryType="nt:unstructured"
                                                                description="Heading 1"
                                                                tag="h1"/>
                                                            <default_h2
                                                                jcr:primaryType="nt:unstructured"
                                                                description="Heading 2"
                                                                tag="h2"/>
                                                            <default_h3
                                                                jcr:primaryType="nt:unstructured"
                                                                description="Heading 3"
                                                                tag="h3"/>
                                                            <default_h4
                                                                jcr:primaryType="nt:unstructured"
                                                                description="Heading 4"
                                                                tag="h4"/>
                                                            <default_h5
                                                                jcr:primaryType="nt:unstructured"
                                                                description="Heading 5"
                                                                tag="h5"/>
                                                            <default_h6
                                                                jcr:primaryType="nt:unstructured"
                                                                description="Heading 6"
                                                                tag="h6"/>
                                                            <default_blockquote
                                                                jcr:primaryType="nt:unstructured"
                                                                description="Quote"
                                                                tag="blockquote"/>
                                                            <default_pre
                                                                jcr:primaryType="nt:unstructured"
                                                                description="Preformatted"
                                                                tag="pre"/>
                                                        </formats>
                                                    </paraformat>
                                                    <table
                                                        jcr:primaryType="nt:unstructured"
                                                        features="-">
                                                        <hiddenHeaderConfig
                                                            jcr:primaryType="nt:unstructured"
                                                            hiddenHeaderClassName="cq-wcm-foundation-aria-visuallyhidden"
                                                            hiddenHeaderEditingCSS="cq-RichText-hiddenHeader--editing"/>
                                                    </table>
                                                    <tracklinks
                                                        jcr:primaryType="nt:unstructured"
                                                        features="*"/>
                                                </rtePlugins>
                                                <uiSettings jcr:primaryType="nt:unstructured">
                                                    <cui jcr:primaryType="nt:unstructured">
                                                        <inline
                                                            jcr:primaryType="nt:unstructured"
                                                            toolbar="[format#bold,format#italic,format#underline,#justify,#lists,links#modifylink,links#unlink,#paraformat]">
                                                            <popovers jcr:primaryType="nt:unstructured">
                                                                <justify
                                                                    jcr:primaryType="nt:unstructured"
                                                                    items="[justify#justifyleft,justify#justifycenter,justify#justifyright]"
                                                                    ref="justify"/>
                                                                <lists
                                                                    jcr:primaryType="nt:unstructured"
                                                                    items="[lists#unordered,lists#ordered,lists#outdent,lists#indent]"
                                                                    ref="lists"/>
                                                                <paraformat
                                                                    jcr:primaryType="nt:unstructured"
                                                                    items="paraformat:getFormats:paraformat-pulldown"
                                                                    ref="paraformat"/>
                                                            </popovers>
                                                        </inline>
                                                        <dialogFullScreen
                                                            jcr:primaryType="nt:unstructured"
                                                            toolbar="[format#bold,format#italic,format#underline,justify#justifyleft,justify#justifycenter,justify#justifyright,lists#unordered,lists#ordered,lists#outdent,lists#indent,links#modifylink,links#unlink,table#createoredit,#paraformat,image#imageProps]">
                                                            <popovers jcr:primaryType="nt:unstructured">
                                                                <paraformat
                                                                    jcr:primaryType="nt:unstructured"
                                                                    items="paraformat:getFormats:paraformat-pulldown"
                                                                    ref="paraformat"/>
                                                            </popovers>
                                                        </dialogFullScreen>
                                                        <tableEditOptions
                                                            jcr:primaryType="nt:unstructured"
                                                            toolbar="[table#insertcolumn-before,table#insertcolumn-after,table#removecolumn,-,table#insertrow-before,table#insertrow-after,table#removerow,-,table#mergecells-right,table#mergecells-down,table#mergecells,table#splitcell-horizontal,table#splitcell-vertical,-,table#selectrow,table#selectcolumn,-,table#ensureparagraph,-,table#modifytableandcell,table#removetable,-,undo#undo,undo#redo,-,table#exitTableEditing,-]"/>
                                                    </cui>
                                                </uiSettings>
                                            </caption>
                                        </items>
                                    </column>
                                </items>
                            </columns>
                        </items>
                    </properties>
                </items>
            </tabs>
        </items>
    </content>
</jcr:root>
 
 

4. Now go ahead and check the authoring dialog for the maxlength validation for the richtext. It should look something like below:

NOTE: This is tested for AEMaaCs and should work for AEM TouchUI dialogs in other versions too. Also this works perfectly fine with the richtext in multifield too.

Thank you for reading.
Happy Coding!

Fetching Multifield data of AEM Dialog in HTL using Single Java Class

If you are looking for an article to create a multifield and fetch it’s data in HTL using just single Java class then you are at the right place. So let’s go ahead and start the creation of a multifield in dialog and then use a java class to fetch the data and then render it on the HTML.

Below is the dialog.xml for the multifield which is of type composite which means the data that you enter in the fields of multifield will be saved in different nodes in content hierarchy i.e, item 0, item 1, and so on.

Data saved as part of content
cq:dialog structure in crx/de
<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:sling="http://sling.apache.org/jcr/sling/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
    jcr:primaryType="nt:unstructured"
    jcr:title="Multifield"
    sling:resourceType="cq/gui/components/authoring/dialog"
    helpPath="https://www.adobe.com/go/aem_cmp_text_v2">
    <content
        jcr:primaryType="nt:unstructured"
        sling:resourceType="granite/ui/components/coral/foundation/container">
        <items jcr:primaryType="nt:unstructured">
            <tabs
                jcr:primaryType="nt:unstructured"
                sling:resourceType="granite/ui/components/coral/foundation/tabs"
                maximized="{Boolean}true">
                <items jcr:primaryType="nt:unstructured">
                    <details
                        cq:showOnCreate="{Boolean}false"
                        jcr:primaryType="nt:unstructured"
                        jcr:title="Details"
                        sling:resourceType="granite/ui/components/foundation/container">
                        <items jcr:primaryType="nt:unstructured">
                            <container
                                jcr:primaryType="nt:unstructured"
                                sling:resourceType="granite/ui/components/foundation/container">
                                <items jcr:primaryType="nt:unstructured">
                                    <cards
                                        jcr:primaryType="nt:unstructured"
                                        jcr:title="Details"
                                        sling:resourceType="granite/ui/components/coral/foundation/form/multifield"
                                        composite="{Boolean}true"
                                        fieldLabel="Details">
                                        <field
                                            jcr:primaryType="nt:unstructured"
                                            sling:resourceType="granite/ui/components/coral/foundation/container"
                                            name="./details">
                                            <items jcr:primaryType="nt:unstructured">
                                                <title
                                                    jcr:primaryType="nt:unstructured"
                                                    sling:resourceType="granite/ui/components/coral/foundation/form/textfield"
                                                    fieldLabel="Title"
                                                    name="./title"/>
                                                <link
                                                    jcr:primaryType="nt:unstructured"
                                                    sling:resourceType="granite/ui/components/coral/foundation/form/pathfield"
                                                    fieldLabel="Link"
                                                    name="./link"/>
                                            </items>
                                        </field>
                                    </cards>
                                </items>
                            </container>
                        </items>
                    </details>
                </items>
            </tabs>
        </items>
    </content>
</jcr:root>

Now lets create our Model Class and try to fetch the values of the multifield. Also follow the comments mentioned in the Java class to identify how fields are fetched and used.

package com.myproject.core.models;

import javax.annotation.PostConstruct;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.sling.api.resource.Resource;

import org.apache.sling.api.SlingHttpServletRequest;

import org.apache.sling.models.annotations.Model;
import org.apache.sling.models.annotations.DefaultInjectionStrategy;

import org.apache.sling.models.annotations.injectorspecific.SlingObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Model(adaptables = SlingHttpServletRequest.class, defaultInjectionStrategy = DefaultInjectionStrategy.OPTIONAL)
public class MultiDataFetcher {

	private static final Logger log = LoggerFactory.getLogger(SupportCarousel.class);

	@SlingObject
	private Resource componentResource;     //Used to get the current resource of the component

	private List<Map<String, String>> details = new ArrayList<>();

	public List<Map<String, String>> getMultiDataMap() {

		return details;

	}

	@PostConstruct
	protected void init() {

		Resource supportPoints = componentResource.getChild("details");  //now we will get the details resource which holds the data in different item node.
		if (supportPoints != null) {
			for (Resource supportPoint : supportPoints.getChildren()) {

				Map<String, String> detailsMap = new HashMap<>();
				detailsMap.put("title",
						supportPoint.getValueMap().get("title", String.class));     // Saving the property into a map, which will be fetched in HTML.
				detailsMap.put("link",
						supportPoint.getValueMap().get("link", String.class));

				details.add(detailsMap);
			}
		}

	}

}

Now once we are ready with out List which holds the data of the multifield, we will now go ahead and render the data in the HTML

<div data-sly-use.multiDataFetcher="${'com.myproject.core.models.MultiDataFetcher'}">
                <sly data-sly-list.item="${multiDataFetcher.multiDataMap}">
                                ${item.title}
        ${item.link}
                </sly>
</div>
  1. Initially we are calling the Java Sling Model using data-sly-use and creating an object of the class.
  2. Then we are using data-sly-list to get the items of the List.
  3. Now we can print out the specific field that we want to render using item.title or item.link.

NOTE: title and link are the two fields which are part of the multifield in dialog.

Try using itemList.index to render the position of the data in the list and this counter starts from 0 similar to arrays in Java.

Thank you for reading.
Happy Coding!