I recently needed to create a "JSF Editable Datatable" where all fields (or a subset) could be edited at once. Here's what I came up with...
My requirements:
- Use a standard JSF datatable.
- When user clicks the Edit Button, all fields (or a subset) become editable inputText components.
- When a user clicks the Save Button, the changes will be saved to the affected objects and persisted to the DB.
My implementation involves the following:
- IceFaces, Hibernate, Spring.
- 1 jspx page with an ice:datatable component.
- 1 backing bean with edit and save actions for the datatable.
The jspx:
<jsp:root
xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:ice="http://www.icesoft.com/icefaces/component"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
version="2.0">
<jsp:directive.page contentType="text/html"/>
<jsp:output omit-xml-declaration="no"
doctype-root-element="html"
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>
<ice:dataTable id="editableDatatable" value="#{backingBean.elements}" var="element">
<ice:column>
<f:facet name="header">
<ice:outputText value="Value 1"/>
</f:facet>
<h:inputText disabled="#{backingbean.elementsDisabled}"
value="#{element.value1}"/>
</ice:column>
<ice:column>
<f:facet name="header">
<ice:outputText value="Value 2"/>
</f:facet>
<h:inputText disabled="#{backingbean.elementsDisabled}"
value="#{element.value2}"/>
</ice:column>
</ice:dataTable>
<br/>
<!--Buttons will be hidden or visible based on whether the table is in edit mode or display mode-->
<div id="editElement" style="display:block;">
<!--Put the table in edit mode by enabling the inputtext components-->
<ice:commandButton value="Edit Element" partialSubmit="true"
onclick="toggleLayerOn('updateElement');toggleLayerOff('editElement');">
<f:setPropertyActionListener value="#{false}" target="#{backingBean.elementsDisabled}"/>
</ice:commandButton>
</div>
<div id="updateElement" style="display:none;">
<!--Save the changes and return to display mode-->
<ice:commandButton action="#{backingBean.updateElementValues}" value="Update Element Values"
partialSubmit="true"
onclick="toggleLayerOn('editElement');toggleLayerOff('updateElement');"/>
<!--Cancel the changes and return to display mode-->
<ice:commandButton value="Cancel Changes" partialSubmit="true"
onclick="toggleLayerOn('editElement');toggleLayerOff('updateElement');">
<f:setPropertyActionListener value="#{true}" target="#{backingBean.elementsDisabled}"/>
</ice:commandButton>
</div>
</jsp:root>
The backing bean. Please note the upateElementValues() method. This gets the editableDataTable from the FacesContext, casts it to an HtmlDataTable, loops over the rows of this datatable, and casts each row to an Element. These Elements contain the updated values entered by the user. You must then load the original Elements via Id and make the necessary changes before persisting the updates back to the database. Make sure to set your datatable rowIndex back to -1 (see code) or there will be JSF errors.
import com.icesoft.faces.component.ext.HtmlDataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.faces.component.UIComponent;
import javax.faces.component.UIData;
import javax.faces.context.FacesContext;
import java.util.*;
public class BackingBean {
public static final Logger log = LoggerFactory.getLogger(BackingBean.class);
private ElementDao elementDao;
private boolean elementsDisabled = true;
private List<Element> elements = new ArrayList<Element>();
public BackingBean() {
>//get all the elements from the database
elements = elementDao.getAllElements();
}
public void setElementDao(ElementDao elementDao) {
this.elementDao = elementDao;
}
public void updateElementValues() {
>//get the datatable as a UI component
UIComponent comp = FacesContext.getCurrentInstance().getViewRoot().findComponent("editableDataTable");
if (comp != null) {
UIData uIData = (UIData) comp;
HtmlDataTable myTable = (HtmlDataTable) uIData;
for (int i = 0; i < myTable.getRowCount(); i++) {
>//loop over the rows
myTable.setRowIndex(i);
>//get the values that the user edited for this row
Element modifiedElement = (Element) myTable.getRowData();
>//print the values to verify they are correct
log.info("Value 1 " + modifiedElement.getValue1());
log.info("Value 2 " + modifiedElement.getValue2());
>//load the element from the database
Element originalElement = elementDao.load(modifiedElement.getId());
originalElement.setValue1(modifiedElement.getValue1());
originalElement.setValue2(modifiedElement.getValue2());
>//update the values in the database for the given element
elementDao.update(originalElement);
}
>//make sure to set the row Index back to -1!!!
myTable.setRowIndex(-1);
}
>//disable the inputtext components, they should only be enabled during "edit mode"
setElementsDisabled(true);
}
public boolean isElementsDisabled() {
return elementsDisabled;
}
public void setElementsDisabled(boolean elementsDisabled) {
this.elementsDisabled = elementsDisabled;
}
public List<Element> getElements() {
return elements;
}
public void setElements(List<Element> elements) {
this.elements = elements;
}
}
The object:
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.Column;
public class Element {
@Id
@GeneratedValue(generator = "hibernate-uuid")
private String id;
@Column(nullable = false)
private String value1;
@Column(nullable = false)
private String value2;
public Element(String value1, String value2) {
this.value1 = value1;
this.value2 = value2;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getValue1() {
return value1;
}
public void setValue1(String value1) {
this.value1 = value1;
}
public String getValue2() {
return value2;
}
public void setValue2(String value2) {
this.value2 = value2;
}
}
Here's a quick and easy way to dynamically add JSF components to a page. You'll need a jsp, a backing bean, and a jsf component library. On the jsp, you will need a button and "container component" (I used a PanelGrid) with a binding to a backing bean. The button will call a method on the backing bean. The method will add child UI components to the bound container component.
1. The jsp. Notice the container component (PanelGrid) has a binding to the backing bean. The button calls the "addComponents" method on the backing bean.
<html xmlns:jsp="http://java.sun.com/JSP/Page"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:c="http://java.sun.com/jstl/core"
xmlns:ice="http://www.icesoft.com/icefaces/component"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns="http://www.w3.org/1999/xhtml">
<jsp:directive.page contentType="text/html"/>
<ui:composition>
<ice:panelGrid binding="#{backingBean.containerComponent}"/>
<br/>
<ice:commandButton value="Add UI Components" action="#{backingBean.addComponents}" partialSubmit="true"/>
</ui:composition>
</html>
2. The backing bean. The addComponents method makes a call to a database to determine what/how many fields need to be added to the container component.
import com.icesoft.faces.component.ext.HtmlPanelGrid;
import com.icesoft.faces.component.ext.UIColumn;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.HtmlInputText;
public class BackingBean {
private HtmlPanelGrid containerComponent;
public void addComponent() {
//clean previous component
containerComponent.getChildren().clear();
List<Node> nodes = nodeDao.getAllNodes();
//dynamically add Child Components to Container Component
for (Node node : nodes) {
UIColumn col = new UIColumn();
HtmlOutputText ot = new HtmlOutputText();
ot.setValue(node.getLabel() + ": ");
col.getChildren().add(ot);
HtmlInputText it = new HtmlInputText();
it.setValue("");
it.setId(node.getLabel());
col.getChildren().add(it);
if (containerComponent == null) {
containerComponent = new HtmlPanelGrid();
}
containerComponent.getChildren().add(col);
}
}
public HtmlPanelGrid getContainerComponent() {
return containerComponent;
}
public void setContainerComponent(HtmlPanelGrid containerComponent) {
this.containerComponent = containerComponent;
}
}
That's it!
Another JSF project I've been working on required another dynamic JSF tree. However, this time the component library being used was IceFaces. If you recall, the last time I used RichFaces. I have to say that using IceFaces made this task MUCH easier.
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. IceFaces was used this time. (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)
- A great place to start is with one of IceFaces tree examples. I used this one: IceFaces Sample Tree Application
All of this sounds very familiar, right?
Here's where it starts to get different.
The Tree UI:
<ice:panelGroup style="border: 1px solid gray;">
<ice:tree id="tree"
value="#{tree.model}"
var="item"
hideRootNode="false"
hideNavigation="false"
>
<ice:treeNode>
<f:facet name="content">
<ice:panelGroup style="display: inline">
<ice:commandLink
actionListener="#{item.userObject.nodeClicked}"
value="#{item.userObject.label}"/>
</ice:panelGroup>
</f:facet>
</ice:treeNode>
</ice:tree>
</ice:panelGroup>
Note that "tree.model" is passed in. Also note that there is a commandLink with actionListener. This sets the selected node id on the backing bean. Both of these things can be seen in the IceFaces sample tree application referenced above.
What you'll need to do to make this truly dynamic is add some controls to your tree display page and some backing bean methods. I'll use adding a node as an example.
Add the code below to the page that displays the tree. newNodeName is a field on the backing bean. addChildToSelectedNode is the method on the backing bean that takes "newNodeName", creates a node, and persists it to the database.
<div id="addNode">
<table width="100%">
<tr>
<td><ice:outputText value="Name:"/></td>
<td><ice:inputText value="#{nodeManagement.newNodeName}"/></td>
</tr>
<tr>
<td>
<ice:commandButton
value="Add Child to Selected Node"
action="#{nodeManagement.addChildToSelectedNode}"
partialSubmit="true"/>
</td>
</tr>
</table>
</div>
<ice:outputText
value="Selected Node: #{tree.selectedNodeObject.label}"
escape="false" style="font-weight:bold;"/>
The method that add a node to the tree is shown below. Note the last line (tree.buildTreeModel()). This rebuilds the tree model that used to display the tree. If this method is not implemented on the Tree bean, you will have to refresh the page manually to see the node that was just created.
public void addNodeToSelectedNode() {
//you'll probably want to handle errors here
//selectedNodeId can't be blank or null
//newNodeName shouldn't be blank or null
Node newNode = new Node();
//load the selectedNode using the selectedNodeId
Node selectedNode = nodeDao.load(selectedNodeId);
//get the selected node's Set of children
Set<Node> childrenOfParent = selectedNode.getChildren();
//create node to be added
newNode.setChildren(null);
newNode.setLabel(newNodeName);
newNode.setParent(selectedNode);
//add new node to selectedNode
childrenOfParent.add(newNode);
//saving selected node saves selectedNode as well as newNode
nodeDao.save(selectedNode);
//rebuild tree
tree.buildTreeModel();
}
The node: (more of the same from last time)
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...
}
I think is a much more straight forward way of creating a dynamic JSF tree. Using the IceFaces Sample Application is a good starting point. Adding the few snippets of code I've provided above should get you the rest of the way.
Here's what I wanted to accomplish:
A user performs a search. The user sees a list of results. The user clicks on a "details" link for a single record in the list of results. The action of clicking on the details link launches a popup window that displays the details of the record selected.
Here's how I thought it should work:
The page with the list of results and the details popup page would share the same backing bean. Each "details" link (commandLink, commandButton, outputLink...doesn't matter) in the list of results would use f:setPropertyActionListener to set the "selectedRecordId" on the backing bean. An onclick event on the details link would launch a popup window. The popup window would get the "selectedRecordId" from the shared backing bean along with other data relating to the selected record.
Sounds pretty straight forward, right? Wrong. The problem is that any javascript events are executed before the form is submitted. So in the situation described above, the popup launches first and THEN the setProperty ActionListener sets selectedRecordId on the backing bean. When the popup window loads, it can't retrieve selectedRecordId because it hasn't been set yet.
A Solution!
Here's a high level overview of how it works. The javascript on the details link passes the recordId on the URL. When the details popup page accesses the "selectedRecordId" on the backing bean, the getter for this field calls a method which retrieves the value of "recordId" that was passed on the URL. This value can then be set to "selectedRecordId" on the backing bean. Both the page with the dataTable results and the details popup page now have access to "selectedRecordId".The Code!
I used icefaces in the example code below.
The dataTable with details popup link:
<ice:dataTable id="searchResults" value="#{basicSearch.records}" var="item">
<ice:column>
<f:facet name="header">
<ice:commandSortHeader
columnName="#{basicSearch.labelColumnName}"
arrow="true">
<ice:outputText value="#{basicSearch.labelColumnName}"/>
</ice:commandSortHeader>
</f:facet>
<ice:outputText value="#{item.label}"/>
</ice:column>
<ice:column>
<f:facet name="header">
<ice:outputText value="Details"/>
</f:facet>
<ice:commandButton image="/resources/images/icon_small_info.gif"
onclick="doPopup('#{request.contextPath}/recordDetails/details.jspx?recordId=#{item.recordId}'); ">
</ice:commandButton>
</ice:column>
</ice:dataTable>
The important stuff from the backing bean:
private String selectedRecordId;
public String getSelectedRecordId() {
selectedRecordId = (String) getParamValue("#{param.recordId}");
return selectedRecordId;
}
public void setSelectedRecordId(String selectedRecordId) {
this.selectedRecordId = selectedRecordId;
}
public Object getParamValue(String s) {
FacesContext facesContext = FacesContext.getCurrentInstance();
Object value = facesContext.getApplication().createValueBinding(s).getValue(facesContext);
return value;
}
The javascript:
function doPopup(source) {
popup = window.open(source, "popup", "height=600,width=900)");
popup.focus();
}
Accessing the recordId from the popup window:
<ice:outputText value="#{metadataView.selectedRecordId}"/>
Concurrent DOM Access so both windows can access the same backing bean: (web.xml)
<context-param>
<param-name>com.icesoft.faces.concurrentDOMViews</param-name>
<param-value>true</param-value>
</context-param>
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 HashSet());
parentNode.getChildren().add(nodeToAdd);
//save node to DB
nodeDao.saveOrUpdate(parentNode);
}
public void editNode(ActionEvent event) {
//get the button that fired the event
HtmlAjaxCommandButton button = (HtmlAjaxCommandButton) event.getComponent();
//get ID of Node to edit - it's stored in the data attribute of the edit button
String nodeId = (String) button.getData();
//load node from DB
Node nodeToEdit = nodeDao.getById(nodeId);
//update node label from UI input
nodeToEdit.setLabel((String) editNode.getValue());
//update node label in DB
nodeDao.update(nodeToEdit);
}
public void deleteNode(ActionEvent event) {
//get ID of Node to delete - it's stored in the data attribute of the delete button
HtmlAjaxCommandButton button = (HtmlAjaxCommandButton) event.getComponent();
String nodeId = (String) button.getData();
//get node object via Dao
Node nodeToDelete = nodeDao.getById(nodeId);
//set reference from parent to null
Node parentNode = nodeToDelete.getParent();
//don't delete the Root Node
if (parentNode != null) {
Set childNodes = parentNode.getChildren();
childNodes.remove(nodeToDelete);
//put updated list of childNodes on parentNode
parentNode.setChildren(childNodes);
//save parentNode to DB
nodeDao.save(parentNode);
//set parent to null
nodeToDelete.setParent(null);
//delete the node from the DB
nodeDao.delete(nodeToDelete);
}
}
The 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.

