Search code examples
jsfjsf-2primefaces

Sorting tree nodes in Primefaces


I am working with JSF 2.1 and Primefaces 3.3. I am using the primefaces tree component for crating the tree from Database. I wanted to sort the tree nodes in alphabetical order at all levels. Please help me on this.


Solution

  • You would have to sort Primefaces DefaultTreeNode objects at the ManagedBean using Collections.sort and a Comparator class.

    public TreeNodeComparator() implements Comparator<TreeNode> {
      public int compare(TreeNode n1, TreeNode n2) {
        // This assumes the tree node data is a string
        return n1.getData().compareTo(n2.getData());
      }
    }
    

    In your managed bean you will need to assemble your child lists without adding their parents yet. That can come later. For right now build your child lists out for each level and set the parent to null;

    TreeNode node1 = new DefaultTreeNode("node1", null);
    TreeNode node2 = new DefaultTreeNode("node2", null);
    TreeNode child1node1 = new DefaultTreeNode("zgnagn", null);
    TreeNode child2node1 = new DefaultTreeNode("vvnieeianag", null);
    TreeNode child1node2 = new DefaultTreeNode("cajkgnagair", null);
    TreeNode child2node2 = new DefaultTreeNode("ajaavnagwokd", null);
    rootNodeChildren.add(node1);
    rootNodeChildren.add(node2);
    node1Children.add(child1node1);
    node1Children.add(child2node1);
    node2Children.add(child1node2);
    node2Children.add(child2node2);
    

    The reason why we are setting everything to null is because when the parent is set on the DefaultTreeNode it is added to the parents child list. The order in which you set a nodes parents determines the order they will appear in the Tree component.

    Knowing that we can use our comparator to sort each list individually.

    Collections.sort(rootNodeChildren, new TreeNodeComparator());
    Collections.sort(node1Children, new TreeNodeComparator());
    Collections.sort(node2Children, new TreeNodeComparator());
    

    Now all of the lists are sorted so we can loop through and the appropriate parents one at a time. You can probably write an algorithm to determine this or you can keep a separate data stucture that builds the tree hierarchy without adding to the list.

    Another way, and probably easier overall, is to just override the DefaultTreeNode class and give it a sort method:

    public SortableDefaultTreeNode extends DefaultTreeNode {
    
      public void sort() {
        TreeNodeComparator comparator = new TreeNodeComparator();
        Collections.sort(this.children, comparator);
        for (TreeNode child : children) {
          child.sort();
        }
      }
    }
    

    Now you can just build your TreeNodes out and then call root.sort() and it will recursively sort all of its children at each level alphabetically.