Question

Primefaces TreeTable nodes seems to work in a reverse way.

You create a parent, then you create a child, than you tell the child what parent it belongs to. The parents should know their children, not the other way.

So... my problem is:

I need to load an undefined ammount of data from my database(grandparents, parents, children and grand children).

How to dinamically load them into the TreeTable? I can't think of a way inside my for-each to create TreeNodes and set it`s parents.

Anyone can give me and idea?

Was it helpful?

Solution

I haven't tested out this solution yet, but I think it should work. the examples on the primefaces showcase are all hard coded. To make it dynamic, You'll have to work with Arrays.
So for example the section of hardcoded code below:

 TreeNode documents = new DefaultTreeNode(new Document("Documents", "-", "Folder"), root);  
 TreeNode pictures = new DefaultTreeNode(new Document("Pictures", "-", "Folder"), root);  
 TreeNode music = new DefaultTreeNode(new Document("Music", "-", "Folder"), root);

Can be replaced with:

 Map<String, TreeNode> rootNodes = new HashMap<String, TreeNode>();

 //Retrieve the list of root Nodes. eg Tables in the database.
 for(Table table : databaseTables){

    //table.getTableName() will be the name of the node, it could be something like "music" or "documents"
    rootNodes.add(table.getTableName(), new DefaultTreeNode(table.getTableName(), new Document......, root);
 }

The reason I add them to the map is so that if you want to refer to them, you can use the key as a reference. now If you want to add nodes to the pictures node for example

 //Create a new map
 Map<String, TreeNode> pictureNodes = new HashMap<String, TreeNode>();

 //now loop through your picture objects
for(picture : pictures){
    pictureNode.add(new DefaultTreeNode(picture.getName(), ......., root.get("pictures"));
}

Using this method, you can recursively loop through as many hierarchies as possible. I haven't been able to test this code (just notepad++) because I'm currently at the office. but try it out, if you're still stuck I can do something more detailed when I get home in a few hours.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top