How to add row in JSF dataTable
Published: October 22, 2010 , Updated: November 18, 2010 , Author: mkyong
This example is enhancing previous delete dataTable row example, by adding a “add” function to add a row in dataTable.
Here’s a JSF 2.0 example to show you how to add a row in dataTable.
1. Managed Bean
A managed bean named “order”, self-explanatory.
package com.mkyong; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Arrays; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name="order") @SessionScoped public class OrderBean implements Serializable{ private static final long serialVersionUID = 1L; String orderNo; String productName; BigDecimal price; int qty; //getter and setter methods private static final ArrayList<Order> orderList = new ArrayList<Order>(Arrays.asList( new Order("A0001", "Intel CPU", new BigDecimal("700.00"), 1), new Order("A0002", "Harddisk 10TB", new BigDecimal("500.00"), 2), new Order("A0003", "Dell Laptop", new BigDecimal("11600.00"), 8), new Order("A0004", "Samsung LCD", new BigDecimal("5200.00"), 3), new Order("A0005", "A4Tech Mouse", new BigDecimal("100.00"), 10) )); public ArrayList<Order> getOrderList() { return orderList; } public String addAction() { Order order = new Order(this.orderNo, this.productName, this.price, this.qty); orderList.add(order); return null; } public String deleteAction(Order order) { orderList.remove(order); return null; } public static class Order{ String orderNo; String productName; BigDecimal price; int qty; public Order(String orderNo, String productName, BigDecimal price, int qty) { this.orderNo = orderNo; this.productName = productName; this.price = price; this.qty = qty; } //getter and setter methods } }
2. JSF page
JSF page to display the data with dataTable tag, and a entry form to key in the order data.
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:ui="http://java.sun.com/jsf/facelets" > <h:head> <h:outputStylesheet library="css" name="table-style.css" /> </h:head> <h:body> <h1>JSF 2 dataTable example</h1> <h:form> <h:dataTable value="#{order.orderList}" var="o" styleClass="order-table" headerClass="order-table-header" rowClasses="order-table-odd-row,order-table-even-row" > <h:column> <f:facet name="header">Order No</f:facet> #{o.orderNo} </h:column> <h:column> <f:facet name="header">Product Name</f:facet> #{o.productName} </h:column> <h:column> <f:facet name="header">Price</f:facet> #{o.price} </h:column> <h:column> <f:facet name="header">Quantity</f:facet> #{o.qty} </h:column> <h:column> <f:facet name="header">Action</f:facet> <h:commandLink value="Delete" action="#{order.deleteAction(o)}" /> </h:column> </h:dataTable> <h3>Enter Order</h3> <table> <tr> <td>Order No :</td> <td><h:inputText size="10" value="#{order.orderNo}" /></td> </tr> <tr> <td>Product Name :</td> <td><h:inputText size="20" value="#{order.productName}" /></td> </tr> <tr> <td>Quantity :</td> <td><h:inputText size="5" value="#{order.price}" /></td> </tr> <tr> <td>Price :</td> <td><h:inputText size="10" value="#{order.qty}" /></td> </tr> </table> <h:commandButton value="Add" action="#{order.addAction}" /> </h:form> </h:body> </html>
3. Demo
From top to bottom, shows a row record being added.



Download Source Code
Download It – JSF-2-DataTable-Add-Example.zip (10KB)
Note : You can find more similar articles at - JSF 2 Tutorials








There is a BIG error in the default.xhtml page :
The “price” property has the “Quantity” label
The “qty” property has the “Price” label
in your code (to add row in datatable) the datatable don’t gets refreshed we refresh the page.Can you help me for how to refresh the datatable when the page is refreshed.
Thank You.
Everything works fine for me : did you have a correct web.xml file ? I don’t use Maven, but Ant, NetBeans 7.11 and not Eclipse, GlassFish 3.12 and not TomCat 7.x.
Superb MK Yong…good example
If we create a SeesionScoped manged bean, one adds/updates a record in db, then it won’t be visible to another session in progress…What is the solution on it?
Most cases don’t need real-time data. If you insists, add ajax or thread check within every specified seconds, or implements the observer design pattern – http://en.wikipedia.org/wiki/Observer_pattern
THanks so much for your nice work.
I have a question.
Why didn’t you divide your classes ?
Because your writing twice Order Class. Or else it wouldn’t be working.
Isn’t another way to add rows ?
I have been working but doesn’t work T_T.
here it is:
============
index.xhtml
============
#{msgs.windowTitle}
============
com.mkyong.TableData.java
============
package com.mkyong;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import javax.faces.bean.ManagedBean;
// or import javax.inject.Named;
import javax.faces.bean.SessionScoped;
// or import javax.enterprise.context.SessionScoped;
@ManagedBean // or @Named(“user”)
@SessionScoped
public class TableData implements Serializable {
private Name name;
private ArrayList names = new ArrayList(Arrays.asList(
new Name(“Anna”, “Keeney”),
new Name(“John”, “Wilson”),
new Name(“Mariko”, “Randor”),
new Name(“William”, “Dupont”)
));
public void setName(Name name) {
this.name = name;
}
public Name getName() {
return this.name;
}
public void setNames(ArrayList names) {
this.names = names;
}
public ArrayList getNames() {
return names;
}
public String deleteRow(Name nameToDelete) {
names.remove(nameToDelete);
return null;
}
public String save() {
for (Name name : names) name.setEditable(false);
return null;
}
public String addRow() {
names.add(new Name(this.name.getFirst(), this.name.getLast()));
return null;
}
}
============
com.mkyong.Name.java
============
package com.mkyong;
import java.io.Serializable;
public class Name implements Serializable {
private String first;
private String last;
private boolean editable;
public Name(String first, String last) {
this.first = first;
this.last = last;
}
public void setFirst(String newValue) { first = newValue; }
public String getFirst() { return first; }
public void setLast(String newValue) { last = newValue; }
public String getLast() { return last; }
public void setEditable(boolean editable) { this.editable = editable; }
public boolean isEditable() { return editable; }
}
I get the following message:
=============================
/index.xhtml @60,58 value=”#{tableData.name.first}”: Target Unreachable, ‘null’ returned null
===============================
I will be waiting for an answer.
THANK YOU so much :D
Another try with html entities
<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN”
“http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>
<html xmlns=”http://www.w3.org/1999/xhtml”
xmlns:f=”http://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:ui=”http://java.sun.com/jsf/facelets”>
<h:head>
<title>JSF 2.0: Example dynamic form</title>
<link href=”./css/styles.css” rel=”stylesheet” type=”text/css”/>
</h:head>
<h:body>
<fieldset>
<legend>Example of a dynamic form</legend>
<h:form id=”classForm”>
<h:dataTable var=”field” value=”#{formBean.fields}” border=”0″ id=”outerdatatable”>
<h:column>
<h:outputText value=”#{field.descr}” rendered=”#{field.type != 'MULTIFIELD2'}”/>
</h:column>
<h:column>
<h:inputText value=”#{field.value}” size=”100″/>
</h:column>
<h:column>
<h:commandButton value=”+” action=”#{formBean.addField(field)}” rendered=”#{field.type == 'MULTIFIELD'}”>
<f:ajax execute=”@form” render=”@form”/>
</h:commandButton>
</h:column>
</h:dataTable>
<h:commandButton value=”submit” action=”#{formBean.submit}”>
<f:ajax execute=”@form” render=”classForm”/>
</h:commandButton>
</h:form>
</fieldset>
</h:body></html>
it doesn’t work to include the xhtml code, please contact me to get the source
The contents of the form disappeared, don’t know why. Here it is again.
JSF 2.0: Example dynamic form
Example of a dynamic form
I solved it, creating a complete dynamic form where it is possible to add fields using JSF 2.0 / datatable. Necessary requirement: use of JUEL 2.2, see also http://weblogs.java.net/blog/cayhorstmann/archive/2009/12/29/jsf-20-and-tomcat.
I have a dynamic form with fields consisting of one field, and some with more, where the user can add fields when needed.
contents of dynamic_form.xhtml:
JSF 2.0: Example dynamic form
Example of a dynamic form
Contents of my bean:
package coreservlets;
import java.io.Serializable;
import java.util.logging.Logger;
import javax.faces.bean.*;
import java.util.ArrayList;
import java.util.Iterator;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewScoped
public class FormBean implements Serializable {
private static final long serialVersionUID = 1L;
private static final Logger logger = Logger.getLogger(FormBean.class.getName());
private ArrayList fields = new ArrayList();
//constructor
public FormBean() {
fields.add(new Field(Field.FieldType.SINGLEFIELD, “Name”));
fields.add(new Field(Field.FieldType.SINGLEFIELD, “Family name”));
fields.add(new Field(Field.FieldType.MULTIFIELD, “Brothers”));
fields.add(new Field(Field.FieldType.MULTIFIELD, “Sisters”));
}
//getters and setters
public ArrayList getFields() {
return fields;
}
public void setFields(ArrayList fields) {
this.fields = fields;
}
//others
public void addField(Field field) {
logger.info(“adding Field. Fields content below. “);
this.logFields();
int fieldnr = fields.indexOf(field);
//add a field after current row, with same description, and of type MULTIFIELD2
fields.add(fieldnr+1,new Field(Field.FieldType.MULTIFIELD2, fields.get(fieldnr).getDescr()));
}
public void submit() {
this.logFields();
}
private void logFields() {
Iterator entries = fields.iterator();
while (entries.hasNext()) {
Field field = entries.next();
logger.info(“field – ” + field.getDescr() + “: ” + field.getValue());
} //while
}
} //class
and contents of Field:
package coreservlets;
public class Field {
public enum FieldType {SINGLEFIELD, MULTIFIELD, MULTIFIELD2};
private FieldType type;
private String descr;
private String value;
public Field(FieldType type, String descr) {
super();
this.type = type;
this.descr = descr;
}
public Field(FieldType type, String descr, String value) {
super();
this.type = type;
this.descr = descr;
this.value = value;
}
//getters and setters
public FieldType getType() {
return type;
}
public void setType(FieldType type) {
this.type = type;
}
public String getDescr() {
return descr;
}
public void setDescr(String descr) {
this.descr = descr;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
Can you also add a row after each field by adding a commandlink at each row?
Sorry, don’t get you, mind to elaborate in detail?