Tuesday April 22, 2008 Michael Bevels
A JSF project that I've been working on required a dynamic tree. Not just a tree that loads dynamically, but a tree that a user can perform CRUD operations on and instantly see the changes they've made. I'm going to walk through an example of how to accomplish this.
The basic setup:
- A “tree” structure that is made up of “node” objects. Each node has a parent node as well as a list of child nodes. Root nodes have a null parent. The tree object takes a list of root nodes. (see code below)
- A JSF Tree. I used the RichFaces tree because RichFaces was already being used throughout the application, but this can be applied to other JSF trees as well. (see code below)
- A JSF managed backing bean with ActionListeners and DAO access. ActionListeners are used for the CRUD operations on nodes. DAO access is used for directly updating the objects in the database. (see code below)
The node:
import javax.persistence.*;
import java.util.List;
import org.hibernate.annotations.GenericGenerator;
@Entity
@GenericGenerator(
name = "hibernate-uuid", strategy = "uuid"
)
public class Node {
@Id
@GeneratedValue(generator = "hibernate-uuid")
private String id;
@Column(nullable = false)
private String label;
@OneToMany(mappedBy = "parent", cascade = {CascadeType.ALL})
private List children;
@ManyToOne
@JoinColumn(name = "fk_parent_id")
private Node parent;
// Getters and Setters...
}
The tree:
<rich:tree id="tree" ajaxSubmitSelection="true" switchType="client" onselected="return false;"> <rich:recursiveTreeNodesAdaptor var="node" roots="#{treeCreator.rootNodes}" nodes="#{node.getChildren}"> <rich:treeNode data="#{node.id}"> <!--Node Name--> <h:outputText value="#{node.label}" /> <!-- Control Buttons --> <!--Button used to toggle addNode Div --> <input type="image" value="Add Child" title="Add Child" onclick="toggleLayer('addNode#{node.id}');return false;" src="resources/images/controls_addlevel.gif"/> <!--Button used to toggle editNode Div --> <input type="image" value="Edit Node" title="Edit Node" onclick="toggleLayer('editNode#{node.id}');return false;" src="resources/images/controls_edit.gif"/> <!--Button for Deleting node --> <a4j:commandButton actionListener="#{treeCreator.deleteNode}" data="#{node.id}" value="Delete Node" reRender="tree" image="/resources/images/controls_delete.gif" title="Delete Node" onclick="if(!confirm('Delete Node?')){ return; };"/> <!-- Divs for name entry/edit--> <div id="addNode#{node.id}" style="display:none;"> <h:outputText value="Node Name: "/> <h:inputText binding="#{treeCreator.nodeAdd}"/> <a4j:commandButton value="Save and Create" title="Save and Create" actionListener="#{treeCreator.addNode}" data="#{node.id}" onclick="toggleLayer('addNode#{node.id}');" image="/resources/images/icon_small_save.gif" reRender="tree"/> <input type="image" src="resources/images/icon_small_cancel.gif" value="Cancel" onclick="toggleLayer('addNode#{node.id}');return false;" title="Cancel"/> </div> <!--Div for Editing an Org --> <div id="editNode#{node.id}" style="display:none;"> <h:outputText value="New Node Name: "/> <h:inputText binding="#{treeCreator.editNode}"/> <a4j:commandButton value="Save Changes" title="Save Changes" actionListener="#{treeCreator.editNode}" data="#{node.id}" onclick="toggleLayer('editNode#{node.id}');" image="/resources/images/icon_small_save.gif" reRender="tree"/> <input type="image" src="resources/images/icon_small_cancel.gif" value="Cancel" onclick="toggleLayer('editNode#{node.id}');return false;" title="Cancel"/> </div> </rich:treeNode> </rich:recursiveTreeNodesAdaptor> </rich:tree>*Note that toggleLayer() is a javascript function that hides/unhides the contents of a given div tag.
*Note that the inputText fields have bindings to the backing bean.
The ActionListeners:
public void addNode(ActionEvent event) { //get the button that fired the event HtmlAjaxCommandButton button = (HtmlAjaxCommandButton) event.getComponent(); //get ID of the parent Node - it's stored in the data attribute of the add button String parentNodeId = (String) button.getData(); //get parent node object Node parentNode = nodeDao.getById(parentNodeId); //create new node object and set label, parent, children, etc Node nodeToAdd = new Node(); nodeToAdd.setLabel((String) addNode.getValue()); nodeToAdd.setParent(parentNode); nodeToAdd.setChildren(new HashSetThe managed bean within faces config:
<managed-bean> <description> Backing bean for the tree </description> <managed-bean-name>treeCreator</managed-bean-name> <managed-bean-class>path.to.the.TreeCreator</managed-bean-class> <managed-bean-scope>request</managed-bean-scope> <managed-property> <property-name>nodeDao</property-name> <value>#{nodeDao}</value> </managed-property> </managed-bean>
Here's how it all fits together using the “Add Child” operation as an example:
- A user visits the tree page and sees the tree with a single root node:
- The user clicks the “Add Child” button on the root node:
-
The “addNode
” div is unhidden (via javascript) which displays an input text box, a save button, and a cancel button to the right of the root node. - The user types in a name for the node and clicks the save button. Note that the save button has a few attributes including actionListener=”treeCreator.addNode” and data=”#{node.id}”.
-
The “addNode
” div is hidden again (via javascript). - The addNode ActionListener is called. See the addNode ActionListener.
- The save button is retrieved from the ActionEvent that was passed to this ActionListener. The “data” attribute stored on this save button is retrieved which contains the ID of the soon-to-be-parent node. The parent node object is loaded via dao access. A new node (with user specified name which is retrieved via binding of the inputText box to backing beans) is added to the parent's children list. The parent node is saved which also saves the new child object to the database.
- The tree is refreshed and the new node appears. Note that the tree “switchType” can be set to client, server, or ajax. This will effect how the page refreshes and the tree loads.
Edit and delete follow a similar process with slightly different implementations in their ActionListeners.

