Close

PrimeFaces - Tree Filter Example

[Last Updated: Aug 31, 2017]

PrimeFaces Tree can be filtered by providing 'filterBy' attribute of tree tag. Let's see an example how to do that.

JSF page

src/main/webapp/index.xhtml

<h:form>
    <p:tree value="#{treeBean.treeNode}" var="node" filterBy="#{node}">
        <p:treeNode>
            <h:outputText value="#{node}"/>
        </p:treeNode>
    </p:tree>
</h:form>

The manage bean

@ManagedBean
@ViewScoped
public class TreeBean {
  private TreeNode treeNode;

  public TreeBean() {
      treeNode = new DefaultTreeNode("Employees", null);
      DataFactory dataFactory = new DataFactory();
      for (int i = 0; i < 5; i++) {
          String[] employees = new String[10];
          for (int j = 0; j < 10; j++) {
              employees[j] = dataFactory.getName();
          }
          String company = dataFactory.getBusinessName();
          addNode(treeNode, company, employees);
      }
  }

  private void addNode(TreeNode parentNode, String nodeName, String... children) {
      TreeNode node = new DefaultTreeNode(nodeName, parentNode);
      node.setExpanded(true);
      if (children != null) {
          for (String child : children) {
              addNode(node, child, null);
          }
      }
  }

  public TreeNode getTreeNode() {
      return treeNode;
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output


Example Project

Dependencies and Technologies Used:

  • primefaces 6.1 primefaces
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • datafactory 0.8: Library to generate data for testing.
  • JDK 1.8
  • Maven 3.3.9

Tree Filter Example Select All Download
  • tree-filtering-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • index.xhtml

    See Also