Thursday, September 12, 2013

PrimeFaces horizontal tree - expand all, collapse all

I'm working as a consultant on a project that is using PrimeFaces, namely the horizontal tree component.

It's a great tool, but took some custom javascript to make it fit our needs. As expected, the client requested an "Expand All" button. I was hoping I could use the PrimeFaces javascript object to call a pre-built function, but I didn't find any information on it.

I quickly threw this together. I won't do much explaining, because the code should explain itself. This should also work on the vertical tree, but you will have to modify the class names to match your tree's expand and collapse icons.

treeController.collapse = function() {
 // I wanted to keep the root expanded, but this part can be
 // removed or changed to select the tree div by ID
 var treeExcludingRoot = $(".ui-treenode-children-container").first();
 // find all of the minus icons, and trigger their onclick event
 $(".ui-tree-toggler.ui-icon-minus", treeExcludingRoot).click();
}

treeController.expand = function() {
 // this works the same way, but with the plus icon
 var treeExcludingRoot = $(".ui-treenode-children-container").first();
 $(".ui-tree-toggler.ui-icon-plus", treeExcludingRoot).click();
}

You could write it yourself, but why bother? Hope somebody gets to copy and paste it.

No comments:

Post a Comment