Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select all in PrimeFaces TreeTable?

I have a PrimeFaces tree table and would like to add a check box which allows the user to select/unselect all.

Here is an extract from my xhtml

<p:selectBooleanCheckbox
        itemLabel="Select all"                                      
        value="#{mainViewBean.selectAll}">
        <p:ajax listener="#{mainViewBean.onSelectAll}"
            update="@this :mainForm" />
    </p:selectBooleanCheckbox>  

    <p:treeTable id="treeToAssign"
        value="#{mainViewBean.treeValue}" var="vh"
        selectionMode="checkbox"
        selection="#{mainViewBean.treeSelection}">
        <f:facet name="header">
            Tree Table                                                  
        </f:facet>                                                              
        <p:column>                                      
            <h:outputText value="#{vh.name}" />
        </p:column>                                 
    </p:treeTable>

and here is my bean method

private TreeNode treeValue;
private TreeNode[] treeSelection;
private boolean selectAll;

public void onSelectAll() {             
    List<TreeNode> selection = new ArrayList<>();
    for (TreeNode node : treeValue.getChildren()) {
    node.setSelected(selectAll);
        selection.add(node);
    }

    treeSelection = selection.toArray(new TreeNode[selection.size()]);
}

I had initially tried just setting NODE.setSelected(selectAll);, but that didn't work so I tried manually manually filling treeSelection as well.

I feel like this should be straightforward, but have been unable to figure it out, any suggestions?

Thanks

like image 379
hello123 Avatar asked Oct 19 '22 22:10

hello123


1 Answers

  • Make your bean at least @ViewScoped
  • Create additional field private Set<TreeNode> selectedNodesSet = new HashSet<>();
  • Use recursion for selecting/deselecting
public void onSelectAll() {
    for (TreeNode node : treeValue.getChildren()) {
        recursiveSelect(node);
    }

    treeSelection = new TreeNode[selectedNodesSet.size()];
    Iterator<TreeNode> iterator = selectedNodesSet.iterator();
    int index = 0;

    while (iterator.hasNext()) {
        treeSelection[index++] = iterator.next();
        iterator.remove();
    }
}

private void recursiveSelect(TreeNode node) {
    node.setSelected(selectAll);

    if (selectAll) {
        selectedNodesSet.add(node);
    } else {
        selectedNodesSet.remove(node);
    }

    for (TreeNode n : node.getChildren()) {
        recursiveSelect(n);
    }
}
like image 160
Geinmachi Avatar answered Oct 29 '22 05:10

Geinmachi