Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to delete a node in <p: tree of primefaces?

I am using private TreeNode root; to create a dynamycal tree.

and I used

<p:tree value="#{bean.root}" var="node">
    <p:treeNode>
        h:outputText value="#{node}" />
    </p:treeNode>
</p:tree>

to display it in my page.

my question is how to remove the nodes that are empty (doesn't contain a child)

exemple :

node1
   child 1
   child 2
node2 
node3
  child 1

(node 2 is empty, how to remove it?)

like image 981
Karim Oukara Avatar asked Oct 03 '12 15:10

Karim Oukara


1 Answers

You can first get all the childs looping the tree:

List<TreeNode> nodes = this.root.getChildren();

Then you can maybe do something like this:

List<TreeNode> nodes = ....
Iterator<TreeNode> i = nodes.iterator();
while (i.hasNext()) {
   TreeNode = i.next(); 
   // Use isLeaf() method to check doesn't have childs.
   i.remove();
}

It would be the correct version of the next code because I guess you can't remove collection elements in a loop.

for (TreeNode treeNode : nodes) {
   if(treeNode.isLeaf()){
       TreeNode parent = treeNode.getParent();
       parent.getChildren().remove(treeNode);
   }
}

Hope it helps.

Regards.

like image 64
dcalap Avatar answered Sep 19 '22 12:09

dcalap