Blogs

How to Change Data Type (Typecast) in AEM, Use @TypeHint
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.

  1. In the new node add the following properties:
  2. ignoreData{Boolean} = true
  3. value{String} = Long
  4. Name{String} [email protected]
  5. 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 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="./[email protected]"
    value="Long"/>

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

Conclusion

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

Interested in more AEM CMS training and support for your organisation? Request a consultation to discuss Argil DX managed services.

Share it:

Arpit Rathi

August 3, 2018

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Comment

Related Posts