May 26, 2020
Estimated Post Reading Time ~

How to Change Data Type in AEM | Typecast Using @TypeHint

Problem Statement:
How to convert a variable from one data type to another data type in AEM. This process is also known as typecast in AEM.

For a use case where a number field is used in dialog and further data will be utilized in Sightly (HTL) for numeric comparison operations. Problem can come up as data will be stored in String format and comparison can only be made on same data type elements.

Solution:

Using @TypeHint, which is used to forcefully define the data type of a property. The following are the steps and scenarios for the application of the same to change data type in AEM.

Scenario:
I have a number field in my dialog with name ‘sponsoredPosition’. By default its value is stored in String format and I wanted it to be stored in Long format instead of String format.

Steps to Change Data Type in AEM using @TypeHint
In the component, add a node parallel to the ‘sponsoredPosition’ node (for which data type needs to be changed) of the type nt:unstructured.

In the new node add the following properties:
ignoreData{Boolean} = true
value{String} = Long
Name{String} =sponsoredPosition@TypeHint
sling:resourceType{String} = granite/ui/components/foundation/form/hidden.
Here,

(a) ignoreData, as the name suggests, it tells the value of this field should not be stored.

(b) In value field you must define the data type in which you want your data to be stored.

(c) In Name, field add ‘@TypeHint’ suffix to the property name of the original node whose value was stored in string format (by default).

(d) Resource type hidden is used for hiding it in dialog.

<sponsoredPosition
jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/foundation/form/numberfield"
fieldLabel="Sponsored Content Position"
max="{Long}3"
min="{Long}2"
value="3"
name="./sponsoredPosition"/>
<sponsoredPositionTypeHint
jcr:primaryType="nt:unstructured"
sling:resourceType="granite/ui/components/foundation/form/hidden"
ignoreData="{Boolean}true"
name="./sponsoredPosition@TypeHint"
value="Long"/>


This article is intended to provide technical AEM users a solution and tactical training on the topic: How to change the data type in AEM or how to typecast in AEM.

Conclusion

Adding @TypeHint solved the issue, now the value is being stored in Long format instead of String.


By aem4beginner

No comments:

Post a Comment

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