Difference between useQuery and useQueries in React.JS to read data from AEM

In React JS useQuery and useQueries are two different hooks that serve distinct purposes when for fetching and managing data.

useQuery:

  • useQuery is used to fetch and manage data for a single query.
  • It takes a single query key as its primary argument and an optional configuration object.
  • You use useQuery when you want to fetch data for a specific resource or endpoint.
  • It automatically manages caching, fetching, and re-fetching based on your configuration settings.

Below is an example of useQuery: (Where url is dam json path)

import {useQuery} from "@transtack/react-query";

export default function ReadData{

let url = "/content/dam/myproject/profile.json";

let {data, error, isError, isLoading, isState, ...otherParams} = useQuery ( 
[url],
fetchUrlSynchronously
);

if (isLoading) {
    return <div>Loading...</div>;
  }

  if (error) {
    return <div>Error: {error.message}</div>;
  }

  return (
    <div>
      {/* Display data */}
    </div>
  );
}

useQueries:

  • useQueries is used to fetch multiple queries simultaneously.
  • It takes an array of query objects as its primary argument. Each query object includes a query key and a fetching function.
  • You use useQueries when you need to fetch data for multiple resources or endpoints in parallel.
  • It returns an array of query result objects, each containing data, loading status, and errors for the corresponding query.

Below is an example of useQueries:

import {useQueries} from "@transtack/react-query";

export default function ReadData{

const urls = [
    { url: 'content/dam/myproject/profileOne.json' },
    { url: '/content/dam/myproject/profileTwo.json' }
  ];


let {data, error, isError, isLoading, isState, ...otherParams} = useQuery ( 
[url],
fetchUrlSynchronously
);


let queryResults: any []= useQueries({
 queries: Object.keys(urls).map((key)  => {
  return {
    queryKey: [urls[key].url],
    queryFn: fetchUrlAsynchronously,
    ...{ enabled: true}
}
  })
});

return (
    <div>
      {queryResults.map((result, index) => (
        <div key={index}>
          {result.isLoading ? 'Loading...' : null}
          {result.error ? `Error: ${result.error.message}` : null}
          {result.data ? /* Display data */ : null}
        </div>
      ))}
    </div>
  );

}

In summary, the key difference lies in the purpose and scope of these hooks. useQuery is for fetching data for a single query, while useQueries is for handling multiple queries concurrently. Depending on your use case, you can choose the hook that best fits your requirements. React Query’s documentation provides comprehensive information on both hooks and how to configure them for optimal use.

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

Configuring Maven in MacOS for AEM Build

In this article we will see how we can setup java and maven in our MacOS so that we can give a successful build of our AEM Archetype project.

As we know we can easily setup the Environmental variables in windows but the process in MacOS is bit different.

Firstly we need to simple install the Java 11 using the .dmg file installer which you can get at https://www.oracle.com/java/technologies/javase/jdk11-archive-downloads.html.



And once you are done installing the Java 11 successfully you can check for the Java version in your terminal using java -version and check if it shows the correct Java version.

Now download the latest or required maven version from https://maven.apache.org/download.cgi and unzip it at any of your local system location. (In my case I have kept it at /Users/NikhilKumar/Downloads/apache-maven-3.9.0).




Now once you are done with the above placement of the unzipped apache-maven-3.9.0 folder, you can open a new terminal which point to the users location (in my case it’s /Users/NikhilKumar).


Now next thing is to check for /.bash_profile file in the users path or you can simply open the terminal of macOs and type vi ~/.bash_profile. Now you will get an empty vi editor and now just add the below set of lines which will set the maven path to the path of the dowloaded maven version.

export M2_HOME="/Users/NikhilKumar/Downloads/apache-maven-3.9.0"
PATH="${M2_HOME}/bin:${PATH}"
export PATH

Now once you are done adding the above code just press Esc then Shift + Colon(:) and then type wq and press enter. (This means we are saving the piece of lines that we have added in bash_profile).

Once you are done with above steps you can either re-open a new terminal to check for maven version or just do source .bash_profile and then check for maven version and it should show you the corresponding maven version.

Now we can go ahead to our AEM Maven project and give a maven build and it should successfully download the dependencies and build should be success.

Thank you for reading.
Happy Coding!

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!