Search code examples
javaadobeaemaem-6

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!


Solution

  • 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