In this article I will give you some examples on how to use the ValueMap functionality in your CQ5/AEM6 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. In case you use Sightly the same objects are available in your component, this without including anything extra.
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.get(“yourproperty”, “default value”) %>
In case you have a few nested nodes you can do the following:
<%= 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.
In AEM6 you now also have the method getValueMap() on the Resource.
ValueMap vm = resource.adaptTo(ValueMap.class);
ValueMap vm = resource.getValueMap();
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());
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.
When you use Sightly there is the object “inheritedPageProperties” available.
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:
In this next article I will introduce the ModifiableValueMap, that makes changing of properties really easy.