Archit Arora
Archit Arora

Reputation: 2626

Pass data from one component to another in adobe CQ

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? How can I make two components interact with each other?

Thanks in advance.

Upvotes: 3

Views: 9252

Answers (3)

kmb
kmb

Reputation: 871

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");
}

Upvotes: 0

shsteimer
shsteimer

Reputation: 28810

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", "");
}

Upvotes: 2

anotherdave
anotherdave

Reputation: 6754

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>

Upvotes: 3

Related Questions