Rocky
Rocky

Reputation: 527

Programmatically arranging contents in aem 6.4

everyone. I'm new in working with aem. I'm using aem 6.4. My task is to programmatically sort the order of the contents of a cq:project in aem depending on the content of a JSON file. The content of the JSON file should be set as the initial child instead of the children sorted by their creation date.

This is the current structure of my cq:page. If the child2 is the one indicated in the JSON file, it should be the first one to be displayed. The content of the JSON file is just the name of one child so even though there are 10 children, the content of the JSON file should always be the first one in the list.

enter image description here

I've spent hours researching on how I can implement this although I still can't find any solution. Any insights on how should I create this? Thanks!

Upvotes: 2

Views: 1505

Answers (2)

Ahmed Musallam
Ahmed Musallam

Reputation: 9753

As I understand it, you want a way to order a named child of a cq:Page to be first in the list.

This is possible because cq:Page is an orderable node. This would not be possible otherwise. you chan check any nodetype in CRX Explorer.

I think adding the bit about JSON complicates the question. You just need a simple method such as the following:

private void orderAsFirstChild(String childName, Node parentNode) throws RepositoryException {
    if (parentNode.hasNode(childName)) {

      // find current first child name
      String firstChildName = Optional.ofNullable(parentNode.getNodes())
          .map(NodeIterator::nextNode)
          .map(node -> {
            try {
              node.getName();
            } catch (RepositoryException e) {
              e.printStackTrace();
            }
            return (String) null;
          }) //
          .orElse(null);
      parentNode.orderBefore(childName, firstChildName);
    }
  }

You should probably clean this up a little, but this is the general idea using Node#orderBefore

Upvotes: 2

raju muddana
raju muddana

Reputation: 154

This may helps -

  1. Get the children from the parent node.(you will get 'iterator' convert it to list here-Convert Iterator to ArrayList)
  2. Delete all child nodes now. And keep the back up of above list. iterate through the list , identify the node which you want place first(by title or some other property) add that to a separate set(LinkedHashSet- to maintain order).
  3. Now add the remaining items/nodes in the same order after your specific node in the above set.(you may need to iterate through again)
  4. Now this Set has nodes/Resources in the order which you want, iterate , create nodes and save your changes.

Upvotes: 1

Related Questions