I am facing some problem to select multiple rows of h:dataTable. My code is below:
<h:dataTable value="#{reportBean.lstchalan}" var="chalan" >
<h:column >
<f:facet name="header">
<h:outputText value="Select" />
</f:facet>
<h:selectBooleanCheckbox value="#{reportBean.checked[chalan.issueNo]}" />
</h:column>
...
</h:dataTable>
<h:commandButton value="submit" action="#{reportBean.submit()}" />
and Below is my backing bean:
public class ReportBean {
List<ChalanVo> checkedItems = new ArrayList<ChalanVo>();
private Map<String, Boolean> checked = new HashMap<String, Boolean>();
........
public List<ChalanVo> getCheckedItems() {
return checkedItems;
}
public void setCheckedItems(List<ChalanVo> checkedItems) {
this.checkedItems = checkedItems;
}
public Map<String, Boolean> getChecked() {
return checked;
}
public void setChecked(Map<String, Boolean> checked) {
this.checked = checked;
}
public String submit() {
checkedItems = new ArrayList<ChalanVo>();
for (ChalanVo dataItem : lstchalan) {
if (checked.get(dataItem.getIssueNo())) {
checkedItems.add(dataItem);
checked.remove(dataItem.getIssueNo());
}
}}
}
But I am getting an exception when execute the line for (ChalanVo dataItem : lstchalan) . lstchalan is giving null.Could you please help me to understand where I am doing wrong?
Here is a working, simplified example:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
#Named("test")
#ViewScoped
public class TestBean implements Serializable{
private static final long serialVersionUID = -1064219566884774973L;
private List<ChalanVo> lstChalans;
private Map<ChalanVo, Boolean> checkedItems = new HashMap<TestBean.ChalanVo, Boolean>();
public TestBean() {
lstChalans = new ArrayList<TestBean.ChalanVo>();
lstChalans.add(new ChalanVo("test1"));
lstChalans.add(new ChalanVo("test2"));
lstChalans.add(new ChalanVo("test3"));
}
public List<ChalanVo> getLstChalans() {
return lstChalans;
}
public void setLstChalans(List<ChalanVo> lstChalans) {
this.lstChalans = lstChalans;
}
public Map<ChalanVo, Boolean> getCheckedItems() {
return checkedItems;
}
public void setCheckedItems(Map<ChalanVo, Boolean> checkedItems) {
this.checkedItems = checkedItems;
}
public void save() {
System.out.println("save");
for (Entry<ChalanVo, Boolean> e : checkedItems.entrySet()) {
if (e.getValue()) {
System.out.println("checked: " + e.getKey().getIssueNo());
}
}
}
public class ChalanVo {
private String issueNo;
public ChalanVo(String issueNo) {
setIssueNo(issueNo);
}
public String getIssueNo() {
return issueNo;
}
public void setIssueNo(String issueNo) {
this.issueNo = issueNo;
}
}
}
With this xhtml:
<!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://xmlns.jcp.org/jsf/html"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head />
<h:body>
<h:form>
<h:dataTable value="#{test.lstChalans}" var="chalan">
<h:column>
<f:facet name="header">
<h:outputText value="Select" />
</f:facet>
<h:selectBooleanCheckbox value="#{test.checkedItems[chalan]}" />
</h:column>
<h:column>
<f:facet name="header">
<h:outputText value="Issue No" />
</f:facet>
<h:outputText value="#{chalan.issueNo}"/>
</h:column>
</h:dataTable>
<h:commandButton action="#{test.save()}" value="Submit" />
</h:form>
</h:body>
</html>
The save() method is able to list the selected items. I think your NullPointerException is unrelated to the checkbox thing. But anyway, you can do the selection like this.
Related
So, i have this piece of code, which basically performs CRUD on a database and displays the results in a <h:dataTable>. The problem is, my code is able to generate an edit action, when I provide a fixed ArrayList. But, if i populate the ArrayList from a database, the rendered property does not provide an editable option from the form. I am able to perform delete functionality, so it's not a matter of the object not being read properly in the action method's parameter. In short, the rendered attribute doesn't work when my data source is a table from a database.
Here's the page:
index.xhtml
<?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: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>
<h:inputText value="#{o.orderNo}" size="10" rendered="#
{o.editable}" />
<h:outputText value="#{o.orderNo}" rendered="#{not o.editable}" />
</h:column>
<h:column>
<f:facet name="header">Product Name</f:facet>
<h:inputText value="#{o.productName}" size="20" rendered="#
{o.editable}" />
<h:outputText value="#{o.productName}" rendered="#{not o.editable}"
/>
</h:column>
<h:column>
<f:facet name="header">Price</f:facet>
<h:inputText value="#{o.price}" size="10" rendered="#{o.editable}"
/>
<h:outputText value="#{o.price}" rendered="#{not o.editable}" />
</h:column>
<h:column>
<f:facet name="header">Quantity</f:facet>
<h:inputText value="#{o.qty}" size="5" rendered="#{o.editable}"
/>
<h:outputText value="#{o.qty}" rendered="#{not o.editable}" />
</h:column>
<h:column>
<f:facet name="header">Action</f:facet>
<h:commandButton value="Edit" action ="#{order.editAction(o)}">
<f:setPropertyActionListener
target = "#{Orders}" value = "#{o}" />
</h:commandButton>
</h:column>
<h:column>
<f:facet name ="header">Action</f:facet>
<h:commandButton value ="Delete" action="#
{order.delete(o)}"/>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
The orderBean.java:
import java.io.Serializable;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
#ManagedBean(name="order")
#RequestScoped
public class orderBean implements Serializable{
private static final long serialVersionUID = 1L;
private static ArrayList<Orders> orderList;
public ArrayList<Orders> getOrderList() {
try{
orderBean.orderList = new ArrayList();
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/orders","root","");
PreparedStatement ps = conn.prepareStatement("Select *
from Orders");
ResultSet rs = ps.executeQuery();
while(rs.next())
{
Orders orders = new
Orders(rs.getString("orderNo"),rs.getString("productName"),
rs.getBigDecimal("price"),rs.getInt("qty"));
orderList.add(orders);
}
}
catch(Exception e)
{
}
return orderList;
}
public void delete(Orders order)
{
try{
orderBean.orderList = new ArrayList();
Class.forName("com.mysql.jdbc.Driver");
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/orders","root","");
PreparedStatement ps = conn.prepareStatement("Delete
from orders where orderNo=?");
ps.setString(1,order.orderNo);
int rs = ps.executeUpdate();
}
catch(Exception e)
{
}
}
public void editAction(Orders order) {
order.setEditable(true);
}
public static class Orders{
String orderNo;
String productName;
BigDecimal price;
int qty;
boolean editable;
public Orders(String orderNo, String productName, BigDecimal price, int
qty) {
this.orderNo = orderNo;
this.productName = productName;
this.price = price;
this.qty = qty;
}
public void setOrderNo(String orderNo)
{
this.orderNo = orderNo;
}
public void setProductName(String productName)
{
this.productName = productName;
}
public void setPrice(BigDecimal price)
{
this.price = price;
}
public void setQty(int qty){
this.qty = qty;
}
public String getOrderNo()
{
return this.orderNo;
}
public String getProductName()
{
return this.productName;
}
public BigDecimal getPrice()
{
return this.price;
}
public int getQty()
{
return this.qty;
}
public boolean isEditable() {
return this.editable;
}
public void setEditable(Boolean editable) {
this.editable = editable;
}
//getter and setter methods
}
}
I am basing my example on the PrimeFaces showcase example for the p:dataTableContextMenu example
The difference being I am trying to delete via a p:confirmDialog but the selected item is always null.
Here's a cut down example
The XHTML
<!DOCTYPE html>
<html xmlns="http://www.w3c.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>Example</title>s
</h:head>
<h:body>
<h:form>
<p:confirmDialog widgetVar="cd" severity="alert" header="Confirmation"
message="Are you sure you wish to delete this car?">
<p:commandButton value="Yes" action="#{carTableView.deleteCar}"
update=":dataForm" oncomplete="PF('cd').hide();" />
<p:commandButton value="No" onclick="PF('cd').hide();" type="button" />
</p:confirmDialog>
</h:form>
<h:form id="dataForm">
<p:contextMenu for="cars">
<p:menuitem value="Delete" icon="ui-icon-close"
onclick="PF('cd').show(); return false;" />
<!-- action="#{formsView.deleteForm}" update=":dataForm" /> -->
</p:contextMenu>
<p:dataTable id="cars" var="car" value="#{carTableView.cars}"
rowKey="#{car.id}" selection="#{carTableView.selectedCar}"
selectionMode="single">
<f:facet name="header">
RightClick to View Options
</f:facet>
<p:column headerText="Id">
<h:outputText value="#{car.id}" />
</p:column>
<p:column headerText="Name">
<h:outputText value="#{car.name}" />
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
The Model
public class Car
{
private String id;
private String name;
public Car(String id, String name)
{
this.id = id;
this.name = name;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
}
And the bean
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#SuppressWarnings("serial")
#ManagedBean
#ViewScoped
public class CarTableView implements Serializable
{
private List<Car> cars;
private Car selectedCar;
#PostConstruct
public void init()
{
cars = createCars();
}
private List<Car> createCars()
{
List<Car> list = new ArrayList<Car>();
for (int i = 0; i < 10; i++)
{
list.add(new Car(UUID.randomUUID().toString().substring(0, 8), "Car " + String.valueOf(i + 1)));
}
return list;
}
public void deleteCar()
{
cars.remove(selectedCar);
selectedCar = null;
}
public List<Car> getCars()
{
return cars;
}
public void setCars(List<Car> cars)
{
this.cars = cars;
}
public Car getSelectedCar()
{
return selectedCar;
}
public void setSelectedCar(Car selectedCar)
{
this.selectedCar = selectedCar;
}
}
Now it seems to me that it's the involvement of running the deleteCar action from the p:confirmDialog that is the issue.
I say this as if I change
<p:menuitem value="Delete" icon="ui-icon-close"
onclick="PF('cd').show(); return false;" />
To
<p:menuitem value="Delete" icon="ui-icon-close"
action="#{formsView.deleteForm}" update=":dataForm" />
Then it works. In the p:confirmDialog example the selectedCar in the deleteCar method is always null. Despite specifying a rowKey attribute in p:dataTable
Since you have two forms, enclose <h:setPropertyActionListener > to your <p:menuitem>
Answer: The p:confirmDialog needs to be part of the same h:form as the p:dataTable
The functionality I need is as follows:
I have a datatable with 4 columns(already works well, for the purpose of explanation I provided just one column "Price") and in the last column I have a "modify" icon. When I click on "modify" icon I would like inputText to pop-up where I can do my modifications for each column in the row.
From technical perspective I'm doing it:
In JSF:
<h:dataTable value="#{item.getItemList()}" var="c"
styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row">
<h:column>
<f:facet name="header"> Price </f:facet>
<h:inputText value="#{c.price}" size="5" rendered="#{c.editable}" />
<h:outputText value="#{c.price}" rendered="#{not c.editable}" />
</h:column>
<h:column>
<f:facet name="header"> Operation </f:facet>
<h:form>
<h:commandLink action="#{item.editAction(c)}">
<h:graphicImage library="images"
name="modifyIcon.png"
width="20"
rendered="#{not c.editable}"/>
</h:commandLink>
</h:form>
<h:form>
<h:commandLink action="#{item.removeItem(c)}">
<h:graphicImage value="resources/images/deleteIcon.png" width="20" />
</h:commandLink>
</h:form>
</h:column>
</h:dataTable>
In bean:
public String editAction(Item item) {
item.setEditable(true);
return null;
}
and in Item class:
public boolean isEditable() {
return this.editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
Then when I click on modifyIcon.png nothing happends. I would expect input fields from the other columns to show up, but they don't. Do you have any idea where I could made a mistake?
since you don't show us where and how you load the list of items, we cannot give you one absolute answer. but here is a working example:
import java.io.Serializable;
public class TestItem implements Serializable{
private static final long serialVersionUID = -2725423502616632442L;
private int id;
private double price;
private boolean editable;
public TestItem(int id, double price, boolean editable) {
super();
this.id = id;
this.price = price;
this.editable = editable;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public boolean isEditable() {
return editable;
}
public void setEditable(boolean editable) {
this.editable = editable;
}
}
Controller:
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
#ManagedBean(name="testBean")
#SessionScoped
public class Test implements Serializable{
private static final long serialVersionUID = 2010307013874058143L;
private List<TestItem> items;
public Test(){
}
#PostConstruct
public void init(){
items = new ArrayList<TestItem>();
items.add(new TestItem(0,20.99,false));
items.add(new TestItem(1,30.90,false));
items.add(new TestItem(2,23.00,false));
items.add(new TestItem(3,15.50,false));
}
public final String setEditable(TestItem selectedItem){
selectedItem.setEditable(true);
return null;// null or your view-id
}
public final String save(){
for(TestItem i: this.getItems()){
System.out.println(i.getPrice());
i.setEditable(false);
}
return null;// null or your view-id
}
public List<TestItem> getItems() {
return items;
}
public void setItems(List<TestItem> items) {
this.items = items;
}
}
xhtml:
<h:form>
<h:dataTable id="DATA-TABLE" var="c" value="#{testBean.items}">
<h:column>
<f:facet name="header"> Name </f:facet>
<h:inputText value="#{c.price}" size="5" rendered="#{c.editable}" />
<h:outputText value="#{c.price}" rendered="#{not c.editable}" />
</h:column>
<h:column>
<f:facet name="header"> Operation </f:facet>
<h:commandButton action="#{testBean.setEditable(c)}" value="EDIT"
rendered="#{not c.editable}">
</h:commandButton>
<h:commandButton action="#{testBean.save}" value="SAVE"
rendered="#{c.editable}">
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
I have the following files in my application but I can't get the values from the selectOneMenu on file elementoUpdateDialog.xhtml to update the dataTable on gerirElementos.xhtml and sql table.
Where is my error?
elementoUpdateDialog.xhtml
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:body>
<p:dialog widgetVar="elementoUpdateDialogWidget"
id="elementoUpdateDialogId" height="300" width="500" modal="true"
closable="true" draggable="false" resizable="false">
<h:form id="elementoUpdateDialogForm" prependId="false">
<h:panelGrid columns="2">
<h:outputText value="elementoID" />
<h:inputText value="#{elementoMB.elemento.elementoId}"
required="true" label="elementoID" />
<h:outputText value="Posto" />
<h:outputText value="#{elementoMB.elemento.posto.postoId}" />
<h:selectOneMenu value="#{postoMB.posto.postoId}">
<f:selectItems value="#{postoMB.allPostos}" var ="posto"
itemLabel="#{postoMB.posto.posto}" itemValue="# {elementoMB.elemento.posto.postoId}"/>
</h:selectOneMenu>
<br />
<h:outputText value="Classe" />
<h:outputText value="#{elementoMB.elemento.classe.classeId}" />
<h:selectOneMenu value="# {elementoMB.elemento.classe.classeId}">
<f:selectItems value="#{classeMB.allClasses}"/>
<f:selectItem itemValue="# {elementoMB.elemento.classe.classeId}" itemLabel="#{elementoMB.elemento.classe.classeId}"/>
</h:selectOneMenu>
<br/>
<h:outputText value="Nome" />
<h:inputText value="#{elementoMB.elemento.nome}" required="true"
label="Nome" />
<h:outputText value="NII" />
<h:inputText value="#{elementoMB.elemento.NII}" required="true"
label="NII" />
<p:commandButton value="Gravar" icon="ui-icon-plus"
action="#{elementoMB.updateElemento()}"
update=":messageGrowl :elementosForm:elementosTable"
oncomplete="closeDialogIfSucess(xhr, status, args, elementoUpdateDialogWidget, 'elementoUpdateDialogId')" />
<p:commandButton value="Cancelar" icon="ui-icon-cancel"
actionListener="#{elementoMB.resetElemento()}"
onclick="elementoUpdateDialogWidget.hide();" type="button" />
</h:panelGrid>
</h:form>
</p:dialog>
</h:body>
</html>
gerirElementos.xhtml
<!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:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<ui:composition template="/pages/protected/templates/master.xhtml">
<ui:define name="divMain">
<p:menubar>
<p:submenu label="Elementos" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/defaultUser/gerirElementos.xhtml" />
</p:submenu>
<p:submenu label="Classes" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/admin/gerirClasses.xhtml" />
</p:submenu>
<p:submenu label="Postos" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/admin/gerirPostos.xhtml" />
</p:submenu>
<p:submenu label="RegistoSarPerm" icon="ui-icon-contact">
<p:menuitem value="Listar"
url="/pages/protected/defaultUser/gerirRegistoSarPerm.xhtml" />
</p:submenu>
</p:menubar>
<h:form id="elementosForm">
<p:dataTable id="elementosTable" var="elemento"
value="#{elementoMB.allElementos}" paginator="true" rows="10"
selepaginatorTemplate="{CurrentPageReport} {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
rowsPerPageTemplate="1,5,10">
<f:facet name="header">
Lista de Elementos
</f:facet>
<p:column headerText="NII" sortBy="nii" id="nii">
#{elemento.NII}
</p:column>
<p:column headerText="Posto" sortBy="posto" id="posto">
#{elemento.posto.posto}
</p:column>
<p:column headerText="Classe" sortBy="classe" id="classe">
#{elemento.classe.classe}
</p:column>
<p:column headerText="Nome" sortBy="nome" id="nome">
#{elemento.nome}
</p:column>
<p:column>
<p:spacer width="10px" />
<p:commandButton value="Editar" icon="ui-icon-pencil"
update=":elementoUpdateDialogForm"
onclick="elementoUpdateDialogWidget.show();">
<f:setPropertyActionListener target="#{elementoMB.elemento}"
value="#{elemento}" />
</p:commandButton>
<p:spacer width="10px" />
<p:commandButton value="Eliminar" icon="ui-icon-trash"
update=":elementoDeleteDialogForm"
onclick="elementoDeleteDialogWidget.show();">
<f:setPropertyActionListener target="#{elementoMB.elemento}"
value="#{elemento}" />
</p:commandButton>
<p:spacer width="10px" />
</p:column>
</p:dataTable>
<p:commandButton value="Novo Elemento" icon="ui-icon-plus"
actionListener="#{elementoMB.resetElemento()}"
onclick="elementoCreateDialogWidget.show();" />
</h:form>
<ui:include
src="/pages/protected/defaultUser/dialogs/elementoCreateDialog.xhtml" />
<ui:include
src="/pages/protected/defaultUser/dialogs/elementoUpdateDialog.xhtml" />
<ui:include
src="/pages/protected/defaultUser/dialogs/elementoDeleteDialog.xhtml" />
</ui:define>
</ui:composition>
</h:body>
</html>
Elemento.java
package com.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="Elemento")
public class Elemento implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="elementoId")
private int elementoId;
#ManyToOne
#JoinColumn(name = "classeId")
private Classe classe;
#ManyToOne
#JoinColumn(name="postoID")
private Posto posto;
#Column(name="NII")
private String NII;
#Column(name="nome")
private String nome;
public Elemento(){
}
public Elemento(String NII, String nome){
this.NII = NII;
this.nome = nome;
}
//Getters and Setters
public int getElementoId() {
return elementoId;
}
public void setElementoId(int elementoId) {
this.elementoId = elementoId;
}
public String getNII() {
return NII;
}
public void setNII(String nII) {
NII = nII;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Classe getClasse() {
return classe;
}
public void setClasse(Classe classe) {
this.classe = classe;
}
public Posto getPosto() {
return posto;
}
public void setPosto(Posto posto) {
this.posto = posto;
}
#Override
public int hashCode() {
return elementoId;
}
#Override
public boolean equals(Object obj) {
if (obj instanceof Elemento) {
Elemento elemento = (Elemento) obj;
return elemento.getElementoId() == elementoId;
}
return false;
}
}
ElementoMB.java
package com.mb;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import com.facade.ElementoFacade;
import com.model.Classe;
import com.model.Elemento;
import com.model.Posto;
#ViewScoped
#ManagedBean
public class ElementoMB extends AbstractMB implements Serializable {
private static final long serialVersionUID = 1L;
private Posto posto;
private Classe classe;
private Elemento elemento;
private List<Elemento> elementos;
private ElementoFacade elementoFacade;
public void createElemento() {
try {
getElementoFacade().createElemento(elemento);;
closeDialog();
displayInfoMessageToUser("Created With Sucess");
loadElementos();
resetElemento();
} catch (Exception e) {
keepDialogOpen();
displayErrorMessageToUser("Ops, we could not create. Try again later");
e.printStackTrace();
}
}
public void updateElemento() {
try {
getElementoFacade().updateElemento(elemento);
closeDialog();
displayInfoMessageToUser("Updated With Sucess");
loadElementos();
resetElemento();
} catch (Exception e) {
keepDialogOpen();
displayErrorMessageToUser("Ops, we could not create. Try again later");
e.printStackTrace();
}
}
public void deleteElemento() {
try {
getElementoFacade().deleteElemento(elemento);
closeDialog();
displayInfoMessageToUser("Deleted With Sucess");
loadElementos();
resetElemento();
} catch (Exception e) {
keepDialogOpen();
displayErrorMessageToUser("Ops, we could not create. Try again later");
e.printStackTrace();
}
}
public List<Elemento> getAllElementos(){
if (elementos == null){
loadElementos();
}
return elementos;
}
public ElementoFacade getElementoFacade() {
if (elementoFacade == null) {
elementoFacade = new ElementoFacade();
}
return elementoFacade;
}
public Elemento getElemento() {
if (elemento == null) {
elemento = new Elemento();
}
return elemento;
}
public void setElemento(Elemento elemento) {
this.elemento = elemento;
}
private void loadElementos() {
elementos = getElementoFacade().listAll();
}
public void resetElemento() {
elemento = new Elemento();
}
public Posto getPosto() {
if (posto == null){
posto = new Posto();
}
return posto;
}
public void setPosto(Posto posto) {
this.posto = posto;
}
public Classe getClasse() {
if (classe == null) {
classe = new Classe();
}
return classe;
}
public void setClasse(Classe classe) {
this.classe = classe;
}
public void resetClasse() {
classe = new Classe();
}
}
ElementoFacade.java
package com.facade;
import java.io.Serializable;
import java.util.List;
import com.dao.ElementoDAO;
import com.model.Elemento;
public class ElementoFacade implements Serializable {
private static final long serialVersionUID = 1L;
private ElementoDAO elementoDAO = new ElementoDAO();
public void createElemento(Elemento elemento) {
elementoDAO.beginTransaction();
elementoDAO.save(elemento);
elementoDAO.commitAndCloseTransaction();
}
public void updateElemento(Elemento elemento) {
elementoDAO.beginTransaction();
Elemento persistedElemento = elementoDAO.find(elemento.getElementoId());
persistedElemento.setNome(elemento.getNome());
persistedElemento.setNII(elemento.getNII());
elementoDAO.commitAndCloseTransaction();
}
public void deleteElemento(Elemento elemento){
elementoDAO.beginTransaction();
Elemento persistedElementoWithIdOnly = elementoDAO.findReferenceOnly(elemento.getElementoId());
elementoDAO.delete(persistedElementoWithIdOnly);
elementoDAO.commitAndCloseTransaction();
}
public Elemento findElemento(int elementoId) {
elementoDAO.beginTransaction();
Elemento elemento = elementoDAO.find(elementoId);
elementoDAO.closeTransaction();
return elemento;
}
public List<Elemento> listAll() {
elementoDAO.beginTransaction();
List<Elemento> result = elementoDAO.findAll();
elementoDAO.closeTransaction();
return result;
}
}
Here,
<f:selectItems value="#{postoMB.allPostos}" var="posto"
itemLabel="#{postoMB.posto.posto}" itemValue="#{elementoMB.elemento.posto.postoId}"/>
Your itemLabel and itemValue attributes, representing the current option label and value, are wrong. They're for some unclear reason referencing a backing bean property instead of the currently iterated option object as definied in var="posto".
Fix it accordingly:
<f:selectItems value="#{postoMB.allPostos}" var="posto"
itemLabel="#{posto.postoId}" itemValue="#{posto}"/>
This should display the items correctly.
And here,
<h:selectOneMenu value="#{postoMB.posto.postoId}">
the selected item is wrong. This would only cause problems during submitting and during displaying a preselected item. You should refer the very same type as itemValue itself, not some ID (otherwise you're changing only the id of an entity instead of the entity itself, resulting in major potential trouble as those are references):
<h:selectOneMenu value="#{postoMB.posto}">
Supply if necessary a converter in case you don't have a #FacesConverter(forClass=Posto.class).
Apply the same lesson learnt on the other <h:selectOneMenu> you've there.
See also:
Our <h:selectOneMenu> wiki page
How to populate options of h:selectOneMenu from database?
I don't know if I complicate things so much but I can't figure out how to update a single row from my datatable, here's my code:
listado.xhtml
<?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">
<h:head>
<title>Facelet Title</title>
</h:head>
<h:body>
<h:form>
<h:dataTable border="1" value="#{guardarBean.listaCustomer}" var="o">
<h:column>
<f:facet name="header">Customer ID</f:facet>
#{o.customerId}
</h:column>
<h:column>
<f:facet name="header">Discount Code</f:facet>
#{o.discountCode.discountCode}
</h:column>
<h:column>
<f:facet name="header">Zip</f:facet>
#{o.zip.zipCode}
</h:column>
<h:column>
<f:facet name="header">Name</f:facet>
<h:inputText value="#{o.name}" rendered="#{guardarBean.isEditable}"/>
<h:outputText value="#{o.name}" rendered="#{not guardarBean.isEditable}"/>
</h:column>
<h:column>
<f:facet name="header">Address 1</f:facet>
<h:outputText value="#{o.addressline1}" />
</h:column>
<h:column>
<f:facet name="header">Address 2</f:facet>
#{o.addressline2}
</h:column>
<h:column>
<f:facet name="header">City</f:facet>
#{o.city}
</h:column>
<h:column>
<f:facet name="header">State</f:facet>
#{o.state}
</h:column>
<h:column>
<f:facet name="header">Phone</f:facet>
#{o.phone}
</h:column>
<h:column>
<f:facet name="header">Fax</f:facet>
#{o.fax}
</h:column>
<h:column>
<f:facet name="header">Email</f:facet>
#{o.email}
</h:column>
<h:column>
<f:facet name="header">Credit Limit</f:facet>
#{o.creditLimit}
</h:column>
<h:column>
<f:facet name="header">Edit</f:facet>
<h:commandButton action="#{guardarBean.editAction()}" value="Editar" />
</h:column>
<h:column>
<f:facet name="header">Save</f:facet>
<h:commandButton value="Save Changes" action="#{guardarBean.editar(o)}">
<f:ajax render="#form" execute="#form"/>
</h:commandButton>
</h:column>
<h:column>
<f:facet name="header">Delete</f:facet>
<h:commandButton action="#{guardarBean.borrar(o)}" value="Borrar">
<f:ajax render="#form" />
</h:commandButton>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
guardarBean.java
import app.dao.CustomerFacadeLocal;
import app.dao.DiscountCodeFacadeLocal;
import app.dao.MicroMarketFacadeLocal;
import app.entity.Customer;
import app.entity.DiscountCode;
import app.entity.MicroMarket;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
#ManagedBean
#RequestScoped
public class GuardarBean {
#EJB
private CustomerFacadeLocal customerFacade1;
#EJB
private MicroMarketFacadeLocal microFacade;
#EJB
private DiscountCodeFacadeLocal discFacade;
public Integer getId(){
return id;
}
public void setId(Integer id){
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Integer getCredit_limit() {
return credit_limit;
}
public void setCredit_limit(Integer credit_limit) {
this.credit_limit = credit_limit;
}
public String getDiscount() {
return discount;
}
public void setDiscount(String discount) {
this.discount = discount;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
private Integer id;
private String name;
private String address1;
private String address2;
private String city;
private String state;
private String phone;
private String fax;
private String email;
private Integer credit_limit;
private String discount;
private String zip;
private boolean isEditable;
private List<DiscountCode> listaDiscount;
private List<Customer> listaCustomer;
public List<Customer> getListaCustomer() {
//FacesContext.getCurrentInstance().getExternalContext().getSession(true);
listaCustomer =(List<Customer>)customerFacade1.findAll();
return listaCustomer;
}
public void setListaCustomer(List<Customer> listaCustomer) {
this.listaCustomer = listaCustomer;
}
public List<DiscountCode> getListaDiscount() {
listaDiscount = (List<DiscountCode>)discFacade.findAll();
return listaDiscount;
}
public void setListaDiscount(List<DiscountCode> listaDiscount) {
this.listaDiscount = listaDiscount;
}
/**
* Creates a new instance of GuardarBean
*/
public GuardarBean() {
}
public void insertar(){
Customer customer = new Customer();
DiscountCode dc = discFacade.find(discount.toCharArray()[0]);
customer.setDiscountCode(dc);
MicroMarket mm = microFacade.find(zip);
customer.setZip(mm);
customer.setName(name);
customer.setCustomerId(id);
customer.setAddressline1(address1);
customer.setAddressline2(address2);
customer.setCity(city);
customer.setCreditLimit(credit_limit);
customer.setEmail(email);
customer.setFax(fax);
customer.setPhone(phone);
customer.setState(state);
customerFacade1.create(customer);
}
public boolean isIsEditable() {
return isEditable;
}
public void setIsEditable(boolean isEditable) {
this.isEditable = isEditable;
}
public void editAction() {
setIsEditable(true);
}
public void editar(Customer customer){
customerFacade1.edit(customer);
setIsEditable(false);
}
public void borrar(Customer c)
{
customerFacade1.remove(c);
}
}
It's simply, via "getListaCustomer" retrieve a list of customers that it's render in datatable, this datatable has an edit column that's when is pressed calls editAction() that set isEditable variable to true for show an inputText for modify the name value in his correspondent column as you can see, the value it's binding to his attribute of the element of the list so when I click in save changes button calls editar function but debugging I can see that customer passed as parameter to this functions has no value in set attribute so it's not doing properly well the caption of data in order to set up in his attribute, what I'm doing wrong?
Regards!
Replacing #RequestScoped with #ViewScoped does the trick.
Consult this thread, precious as it is, it includes a link toward a good tuto (of the immense BalusC ) about Managed Bean Scopes, here.
Best of luck :).