I am developing an application in JSF in which I use a <h:selectOneListbox .../>
. for which I have defined a Converter
.
Below I show a simplified block of said control, which contains a panelGrid
with a button Guardar
and a list selector:
<h:panelGrid cellpadding = "5" columns = "4" >
<p:commandButton value="Guardar"
update=":dmContadoresConsumoForm:edicionContadorConsumoPnl"
disabled="#{!contadoresConsumoBean.contadorCentroEditable}"
actionListener="#{contadoresConsumoBean.guardarContador}"/>
<h:outputText value = "Producto" />
<h:selectOneListbox
id = "productoSel"
size = "1"
value = "#{contadoresConsumoBean.productoSeleccionado}"
disabled = "#{!contadoresConsumoBean.contadorCentroEditable}"
style = "width:100%" >
<f:selectItem itemValue = "0"
itemLabel = "" / >
<f:selectItems
value = "#{contadoresConsumoBean.productos}"
var = "producto"
itemValue = "#{producto.id}"
itemLabel = "#{producto.nombre}" />
</h:selectOneListbox>
<!-- ... -->
</h:panelGrid>
I have defined a Converter
for objects of type Producto
, whose code is as follows:
@ManagedBean(name = "productoConverter")
@SessionScoped
@FacesConverter(forClass = Producto.class)
public class ProductoConverter implements Converter {
@Override
public Object getAsObject(FacesContext context, UIComponent component, String value) {
long id = -1;
try{
id = Long.parseLong(value);
}
catch(Exception e){
return null;
}
Transaction t = HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
try{
Producto e = new ProductoServiceImpl().find(id);
t.commit();
return e;
}
catch(Exception e){
t.rollback();
e.printStackTrace();
return null;
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value instanceof Producto){
return ((Producto)value).getId().toString();
}
return null;
}
}
The problem is that when I press the button to save changes, I get the error:
dmContadoresConsumoForm:productoSel: Error de validación: el valor no es válido
I've tried debugging Converter
it and it seems to work fine.
Apparently, the error occurs because you have to override the
equals(Object object)
and methodshashCode()
in the bean on which the Converter is applied.On the other hand, in the xhtml file, I have modified the value of the attribute
itemValue="#{producto}"
, so that the solution is as follows:xhtml:
ProductConverter.java
The converter didn't have any errors, so it's still the same:
Product.java
In this class I override the methods
equals(Object object)
andhashCode()