April 3, 2020
Estimated Post Reading Time ~

How to read properties values on a certain node in CQ5

While working with CQ5 you will always see nodes that have properties configured over them which can contain values. The values are of different format. Some can be in String or String [] or may be Date at some time. If you have resolved the resource at certain path and the resource name is resolvedResource. Then you can simply fetch the values like

ValueMap valueMap = resolvedResource.adaptTo(ValueMap.class); // Refer to sling adapters in Felix console to know more.
String propValue = valueMap.get(“propertyName”,String.class); // The second parameter can be String array or date, otherwise the default value is always string, if you retrieve a string then you will have to do conversion on your own. The other alternative is to do iteration over the Node.

Node nodeName = resolvedResource.adaptTo(Node.class);

Refer to this post here to read the properties

How to read properties from a node in CQ5?

So, you have resolved to a node and want to read the properties that exist on that node. This is a pretty easy task. You should read properties with multiple values separately, if you just choose to put the below else if condition in your code, then the first value of the properties with multiple values would be fetched. If you don’t expect multiple value properties on your node then you can skip the first if.

 Node node = resource.adaptTo(Node.class);
 for (PropertyIterator propeIterator = node.getProperties(); propeIterator.hasNext();) {
  Property prop = propeIterator.nextProperty();
  if (prop.isMultiple()) // This condition checks for properties whose type is String[](String array)  
  {
   Property propVal = node.getProperty(prop.getName());
   Value[] values = propVal.getValues();
   for (Value val: values) {
    log.debug(val.getString()); // this will output the value in string format  
   }
  } else if (!prop.getDefinition().isMultiple()) {
   log.debug(prop.getName());
   log.debug(prop.getValue().getString());
  }
 }



By aem4beginner

No comments:

Post a Comment

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