Add and delete nodes in primefaces treeTable

Luermo Source

I have This:

<p:treeTable id="#{treeTableId}" value="#{tableBeanRoot}" var="element"
    resizableColumns="true"
    selection="#{budgetTemplateElementBean.selectedNode}"
    selectionMode="single" widgetVar="#{treeTableId}widget">

    <f:facet name="header">

    </f:facet>

    <p:column style="width:150px"> 
             .....
    </p:column>
             .....
    <f:facet name="footer">
        <p:commandButton value="#{msg.addChildNode}"
            actionListener="#{actionBean.addChildNodeAction}"
            process="@this,#{treeTableId}" update="#{treeTableId} :growl" />
        <p:commandButton value="#{msg.deleteNode}"
            actionListener="#{actionBean.deleteNodeAction}"
            process="@this,#{treeTableId}" update="#{treeTableId} :growl" />
    </f:facet>
</p:treeTable>

How to add and delete treeNodes in Primefaces treeTable? What can I put into back bean?

Thanks

jsfprimefaces

Answers

answered 5 years ago Eric Garcia #1

One solution for adding the delete nodes can be like this:

public boolean removeElemetOfTreeNode(TreeNode rootNode,
        TreeNode nodeToDelete) {
    if (rootNode.getChildren().remove(nodeToDelete)) {
        return true;
    } else {
        for (TreeNode childNode : rootNode.getChildren()) {
            if (childNode.getChildCount() > 0) {
                return removeElemetOfTreeNode(childNode, nodeToDelete);
            }

        }
        return false;
    }
}

public void addNodeAction(ActionEvent event) {
    if (selectedNode == null) {
        // TODO: añadir excepcion no seleccionado
    }
    Random randomGenerator = new Random();
    TreeNode pepe = new DefaultTreeNode(new Configuration("new node"
            + randomGenerator.nextInt(100), false, "new node"
            + randomGenerator.nextInt(100), false),
            selectedNode.getParent());
    return;
}

public void addChildNodeAction(ActionEvent event) {
    if (selectedNode == null) {
        // TODO: añadir excepcion no seleccionado
    }
    Random randomGenerator = new Random();
    TreeNode pepe = new DefaultTreeNode(new Configuration("new node"
            + randomGenerator.nextInt(100), false, "new node"
            + randomGenerator.nextInt(100), false), selectedNode);
    return;
}

answered 10 months ago János #2

I think there is no need to traverse the tree with BFS when deleting a node as the node itself knows its parent:

public void removeElemetOfTreeNode(TreeNode nodeToDelete) {
    TreeNode parent = nodeToDelete.getParent();
    if(parent == null){
        // throw exception or handle case of root node differently 
    }
    parent.getChildren().remove(nodeToDelete);
}

If you need to check whether the nodeToDelete is a descendant of rootNode it is also more efficient to start at nodeToDelete and go up until you reach its root and then compare it to rootNode instead of traversing the whole tree with BFS.

comments powered by Disqus