Created

Feb 01, 2013

ValueMap and his friends

Posted by Feike Visser

In this article I will give you some examples on how to use the ValueMap functionality in your CQ5 application.

And I will introduce two good friends of the ValueMap that are really useful.

By default you already have a few ValueMaps available in your components, these are created via the cq:defineObjects tag.

This is located in the global.jsp that is by default in the "/libs/foundation" folder. One of the most commonly used one is "properties", this will expose the properties of your component.

You can use this like this in your component:

When you want to get the value of a property:

${properties.yourproperty}

<%= properties.get("yourproperty", "default value") %>

${properties["yourproperty"]

In case you have a few nested nodes you can do the following:

${properties["node1/node2/myproperty"]}

<%= properties.get("node1/node2/myproperty", "default value") %>

When the property isn't found an empty String will be returned.

So there is no need to do checks within the Node.class like you see often:

node1.hasNode("node2") && node1.getNode("node2").hasProperty("myproperty")

Getting a ValueMap

If you want to get a ValueMap from a Resource you have, you can do this via .adaptTo(), or use ResourceUtil.getValueMap().
ResourceUtil has some safety checks that will make sure an empty ValueMap is returned in case the Resource can't be adapted.

ValueMap vm = resource.adaptTo(ValueMap.class);

ValueMap vm = ResourceUtil.getValueMap(resource);

Friend 1: ValueMapDecorator

The first friend of the ValueMap is the ValueMapDecorator, this class can be used to create a custom ValueMap that is not based on a resource.
Also this instance of a ValueMap allows you to call the put-method. When you do this on a ValueMap that is based on a resource you will get an UnsupportedOperation-exception.

Here is an example on how you can do this:

ValueMap props = new ValueMapDecorator(new HashMap());
	
props.put("test", "value");

Friend 2: InheritanceValueMap

The second friend of the ValueMap is the InheritanceValueMap, this is a ValueMap that can be used if you have properties defined at multiple-levels and you want to retrieve the correct one. This will avoid you to code a loop that goes through all the parents and checks for a certain property.

For example if you have a page-tree whereby at every level you can set the color, at page-level you just want to get the color that need to be used for this page. 

This is how you can create an instance of the InheritanceValueMap:

InheritanceValueMap inVM = new HierarchyNodeInheritanceValueMap(page.getContentResource());

To get an value by inheritance simply call this method:

inVM.getInherited("myproperty", "default");

COMMENTS

ADD A COMMENT