Question

I have a component that needs to fetch properties from another component on the same page.

Is there a way to get a component's NODE object from currentPage ?

I have the name of the node I need to fetch available in the code.

Was it helpful?

Solution

Assuming the node you need is in Page/jcr:content/yournode:

the Page object has a method getContentResource() which returns you the jcr:content resource node by default. You can also use page.getContentResource("yournode") to get a specific node below jcr:content.

If your node, for some reason is sibling to jcr:content (it shouldn't btw), you can your iterate the children of a resource using resource.listChildren().

Remember, this is all Sling API, so you are managing resources, not nodes. You can get a JCR Node from a resource using resource.adaptTo(Node.class)

OTHER TIPS

Usually every Page class has a method for retrieving nodes within jcr:content that’s a little cleaner:

Node node = CurrentPage.getContentResource("COMPONENTNAME").adaptTo(Node.class);

Developers should check for a resource's existence before adapting it to a Node.

Now that we have a node, we can extract properties from that node.

String title = node.getProperty("jcr:title").getString();

This way you can fetch any properties of a component.

I would like to add that this can be solved in more clean way by delegating request to a servlet provided the problem being solved requires separation of concerns - separate the view from the controller logic. LINK EXPLAINING IN DETAIL HOW VALIDATION IS DONE USING SLING SERVLETS

Adds validator to a form using below logic that calls the sling servlet hosted

  var url = CQ.HTTP.addParameter(dialog.path + '.validator.json', 'value', value);
  var result = CQ.HTTP.eval(url);

 and in the servlet we access the node and its parents using below logic
   final Node currentNode = request.getResource().adaptTo(Node.class);
   try {
        final Node par = currentNode.getParent();

        final NodeIterator nodes = par.getNodes();

        // get all form names for the current paragraph system
        while (nodes.hasNext()) { //and the business logic
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top