I\'m using Adobe CQ5. I have made two components that are independent of each other. However, I want to use data from one component in the other one. How do I achieve this?
There are a number of options, depending on how closely the components are coupled (e.g. will both always be placed on the page at the same time? Are they hard-wired into the template, or placed by the editors, etc.)
If both components are on the same page, the simplest is probably to set a variable within one component & read it in another, e.g.:
foo.jsp
<c:set var="globalFooTitle" value="${properties.title}" scope="request"/>
bar.jsp
<c:out value="${globalFooTitle}">[Optional fallback value]</c:out>
You can use javax.jcr.Node
and javax.jcr.Property
interface to get properties of another component. For example, you have added component1 and component2 to page1. In the repository you should have structure similar to this:
/content
/project
/page1
/jcr:content
/parsys
/component1
/...some properties
/component2
/...some properties
If you want to get properties of component2 while in component1, you can use something like:
Node parsys = currentNode.getParent();
if(parsys.hasNode("component2")) {
Node component2 = parsys.getNode("component2");
if(component2.hasProperty("someProperty"))
Property someProperty = component2.getProperty("someProperty");
}
While there is nothing wrong with @kmb's answer, I almost always prefer to use higher level Apis than lower level ones. In the case of CQ, this means using the sling resource API instead of the JCR node API.
That would look something like this, assuming the same structure of the 2 components on a single page as he laid out.
Resource r = resourceResolver.getResource(currentResource, "../component2");
if(r != null) {
ValueMap props = r.adaptTo(ValueMap.class);
String somePropertyValue = props.get("someProperty", "");
}