Error with two selectOneMenu nested [duplicate] - jsf

This question already has answers here:
JSF java.lang.IllegalArgumentException: Cannot convert 5 of type class java.lang.Integer to class
(1 answer)
How to populate options of h:selectOneMenu from database?
(5 answers)
Closed 5 years ago.
I am trying to make two selectOneMenu nested, one contains the provinces and the second the cities of those provinces, but I haves a mistake, when I select the province, and I can not find out what I did wrong !. If anyone can give me a hand with deciphering the error, already very grateful!
The error itself:
SEVERE [javax.enterprise.resource.webcontainer.jsf.context] (default
task-22) javax.faces.component.UpdateModelException:
java.lang.IllegalArgumentException:
Cannot convert 2 of type class java.lang.Integer to class
ar.com.kompass.model.Provincia
at javax.faces.component.UIInput.updateModel(UIInput.java:866)
at javax.faces.component.UIInput.processUpdates(UIInput.java:749)
at com.sun.faces.context.PartialViewContextImpl$Phase
AwareVisitCallback.visit(PartialViewContextImpl.java:577)
at com.sun.faces.component.visit.PartialVisitContext.invoke
VisitCallback(PartialVisitContext.java:183)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1689)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
at javax.faces.component.UIComponent.visitTree(UIComponent.java:1700)
If I do not understand, the message "Can not convert 2 of ...." refers to the value selected, in this case the value of 2 provinces, and that does not manage to "convert" to a province object? .... how to solve this? The piece of view code that generates the error:
<p:row>
<p:column>
<p:outputLabel value="Provincia " />
<p:selectOneMenu id="cboProvincia"
value="#{cuentaBean.cuenta.provincia}" required="true"
requiredMessage="Debe seleccionar una provincia"
converter="omnifaces.SelectItemsConverter">
<f:selectItem itemLabel="--Seleccione--" itemValue="#{null}"
noSelectionOption="true" />
<f:selectItems value="#{cuentaBean.lstProvincias}" var="prov"
itemLabel="#{prov.nombre}" itemValue="#{prov.id}" />
<f:ajax event="change"
listener="#{cuentaBean.listarLocalidades()}"
execute="cboProvincia" render="cboLocalidad" />
</p:selectOneMenu>
</p:column>
<p:column>
<p:outputLabel value="Localidad " />
<p:selectOneMenu id="cboLocalidad"
value="#{cuentaBean.cuenta.localidad}" required="true"
requiredMessage="Debe seleccionar una Localidad"
converter="omnifaces.SelectItemsConverter">
<f:selectItem itemLabel="--Seleccione--" itemValue="#{null}"
noSelectionOption="true" />
<f:selectItems value="#{cuentaBean.lstLocalidades}" var="loca"
itemLabel="#{loca.nombre}" itemValue="#{loca}" />
</p:selectOneMenu>
</p:column>
</p:row>
and this is the bean:
#Named
#ViewScoped public class CuentaBean implements Serializable {
#Inject
private ICuentaService cuentaService;
#Inject
private Cuenta cuenta;
#Inject
private IProvinciaService provinciaService;
#Inject
private ILocalidadService localidadService;
private List<Cuenta> lstCuentas;
private List<Provincia> lstProvincias;
private List<Localidad> lstLocalidades;
private int codigoProvincia;
public int getCodigoProvincia() {
return codigoProvincia;
}
public void setCodigoProvincia(int codigoProvincia) {
this.codigoProvincia = codigoProvincia;
}
public Cuenta getCuenta() {
return cuenta;
}
public void setCuenta(Cuenta cuenta) {
this.cuenta = cuenta;
}
#PostConstruct
public void init(){
lstCuentas = new ArrayList<>();
lstProvincias = new ArrayList<>();
lstLocalidades = new ArrayList<>();
this.listarProvincias();
}
public List<Cuenta> getLstCuentas() {
return lstCuentas;
}
public void setLstCuentas(List<Cuenta> lstCuentas) {
this.lstCuentas = lstCuentas;
}
public List<Provincia> getLstProvincias() {
return lstProvincias;
}
public void setLstProvincias(List<Provincia> lstProvincias) {
this.lstProvincias = lstProvincias;
}
public List<Localidad> getLstLocalidades() {
return lstLocalidades;
}
public void setLstLocalidades(List<Localidad> lstLocalidades) {
this.lstLocalidades = lstLocalidades;
}
public void listarProvincias() {
try {
//lstCuentas = cuentaService.listar();
lstProvincias= provinciaService.listar();
//lstLocalidades= localidadService.listar(idProv);
} catch (Exception e) {
}
}
public void listarLocalidades
System.out.print(this.codigoProvincia);
lstLocalidades= localidadService.listar(this.codigoProvincia);
} catch (Exception e) {
}
}
}
And finally the Model Cuenta, that perhaps could be the reason for the error:
#Entity #Table(name = "cuenta") public class Cuenta implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "nombre", length = 30, nullable = false)
private String nombre;
#Column(name = "domicilio", length = 30, nullable = false)
private String domicilio;
private short altura;
#OneToOne
#JoinColumn(name="idprov" , nullable = false)
private Provincia provincia;
#OneToOne
#JoinColumn(name="idloca" , nullable = false)
private Localidad localidad;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getDomicilio() {
return domicilio;
}
public void setDomicilio(String domicilio) {
this.domicilio = domicilio;
}
public short getAltura() {
return altura;
}
public void setAltura(short altura) {
this.altura = altura;
}
public Localidad getLocalidad() {
return localidad;
}
public void setLocalidad(Localidad localidad) {
this.localidad = localidad;
}
public Provincia getProvincia() {
return provincia;
}
public void setProvincia(Provincia provincia) {
this.provincia = provincia;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Cuenta other = (Cuenta) obj;
if (id != other.id)
return false;
return true;
}
}

You have it wrong:
<f:selectItems value="#{cuentaBean.lstProvincias}" var="prov"
itemLabel="#{prov.nombre}" itemValue="#{prov.id}" />
It should be:
<f:selectItems value="#{cuentaBean.lstProvincias}" var="prov"
itemLabel="#{prov.nombre}" itemValue="#{prov}" />
Explanation: You are trying to set the id of provincia which is int to provincia which is object.

Related

nested <p:selectOneMenu does not update value

I have two selectOneMenu one update the other, but the second one do not update its value, and still remains with the first value, despite in any code, this two variables are equal so themselves. Even the valueEventChangeListener returns the estados_eam value. Thanks guys, any help will be very appreciate. Best regards.
<h:outputText value="ESTADO:" />
<p:selectOneMenu id="estados_eam" value="#{estadosMB.clave}"
style="width:200px;" required="true">
<f:selectItem itemLabel="Seleccione un estado" itemValue="#{null}" noSelectionOption="true" />
<f:selectItems value="#{estadosMB.estadosMap}" />
<p:ajax listener="#{municipiosMB.handleEstadosChange}" update="municipios_eam"/>
</p:selectOneMenu>
<p:message for="estados_eam" />
<h:outputText value="MUNICIPIO:" />
<p:selectOneMenu id="municipios_eam" valueChangeListener="#{municipiosMB.selectOneMenuListener}"
value="#{municipiosMB.idMunicipio}" label="Municipios"
converter="javax.faces.Integer" style="width:200px;" required="true">
<f:selectItem itemLabel="Seleccione un Municipio"
itemValue="#{null}" />
<f:selectItems value="#{municipiosMB.municipiosMap}" />
<p:ajax listener="#{municipiosMB.handleMunicipioSelectedChange}" />
</p:selectOneMenu>
<p:message for="municipios_eam" />
Bean code:
#ManagedBean(name = "municipiosMB")
#ViewScoped
public class MunicipiosMB implements Serializable {
/**
*
*/
private static final long serialVersionUID = 112312323213445L;
private static Logger logger = LoggerFactory.getLogger(MunicipiosMB.class);
#ManagedProperty(value = "#{MunicipiosService}")
private MunicipiosService municipioService;
#ManagedProperty(value = "#{estadosMB}")
private EstadosMB estadosMB;
private Map<String, String> municipiosMap;
private Municipio selectedMunicipio;
private String clave;
private Estados estado;
private Integer id;
private String nombre;
private String siglas;
private String estado_clave;
private Municipio municipio;
private Integer idMunicipio;
public void updateMunicipio(Municipio municipio) {
this.clave = municipio.getIdEstado().getClave();
this.id = municipio.getId();
this.nombre = municipio.getNombre();
this.setMunicipio(municipio);
}
public Municipio getMunicipio() {
return municipio;
}
public void setMunicipio(Municipio municipio) {
this.municipio = municipio;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
public Estados getEstado() {
return estado;
}
public void setEstado(Estados estado) {
this.estado = estado;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getSiglas() {
return siglas;
}
public void setSiglas(String siglas) {
this.siglas = siglas;
}
public Municipio getSelectedMunicipio() {
return selectedMunicipio;
}
public void setSelectedMunicipio(Municipio selectedMunicipio) {
this.selectedMunicipio = selectedMunicipio;
}
public MunicipiosService getMunicipioService() {
return municipioService;
}
public void setMunicipioService(MunicipiosService municipioService) {
this.municipioService = municipioService;
}
public Map<String, String> getMunicipiosMap() {
return municipiosMap = municipioService.getMunicipiosByClaveEstado(estadosMB.getClave());
}
public void setMunicipiosMap(Map<String, String> municipiosMap) {
this.municipiosMap = municipiosMap;
}
public EstadosMB getEstadosMB() {
return estadosMB;
}
public void setEstadosMB(EstadosMB estadosMB) {
this.estadosMB = estadosMB;
}
public Integer getIdMunicipio() {
return idMunicipio;
}
public void setIdMunicipio(Integer idMunicipio) {
this.idMunicipio = idMunicipio;
}
public void handleEstadosChange() {
try {
if (estadosMB.getClave() != null || !estadosMB.getClave().equals("77")) {
this.idMunicipio=0;
logger.info(" valor muncipio "+ this.idMunicipio);
logger.info("La clave seleccionada es "+estadosMB.getClave());
this.setMunicipiosMap(municipioService.getMunicipiosByClaveEstado(estadosMB.getClave()));
logger.info("Clave Estado Seleccionado: " + estadosMB.getClave());
logger.info("Clave Municipio Seleccionado: " + this.idMunicipio);
} else {
this.idMunicipio=0;
this.setMunicipiosMap(new HashMap<String, String>());
}
} catch (NullPointerException e) {
logger.info("EstadosMB Null");
this.setMunicipiosMap(new HashMap<String, String>());
}
}
public void handleMunicipioSelectedChange() {
logger.info("municipio seleccionado:::::: "+this.getIdMunicipio());
logger.info("municipio seleccionado2:::::: "+this.getId());
}
public Municipio selectedMunicipio() {
return municipioService.getMunicipiosById(this.getId());
}
public void selectOneMenuListener(ValueChangeEvent event) {
//This will return you the newly selected
//value as an object. You'll have to cast it.
Object newValue = event.getNewValue();
logger.info("valor nuevo"+ newValue.toString());
//The rest of your processing logic goes here...
}
}
I don't have any idea, why it is happending here...My EstadosMB
#ManagedBean(name="estadosMB")
#ViewScoped
public class EstadosMB implements Serializable {
#ManagedProperty(value="#{EstadosService}")
private EstadosService estadosService;
private String clave = "";
private Map<String,String> estadosMap;
public EstadosService getEstadosService() {
return estadosService;
}
public void setEstadosService(EstadosService estadosService) {
this.estadosService = estadosService;
}
public Map<String, String> getEstadosMap() {
return estadosMap = estadosService.getEstadosMap();
}
public void setEstadosMap(Map<String, String> estadosMap) {
this.estadosMap = estadosMap;
}
public String getClave() {
return clave;
}
public void setClave(String clave) {
this.clave = clave;
}
}
There are two solutions:
Update the menu in the listener method in the bean by adding this line:
RequestContext.getCurrentInstance().update("municipios_eam");
Use a p:remoteCommand to update the 2nd menu, so instead of:
<p:ajax listener="#{municipiosMB.handleEstadosChange}" update="municipios_eam"/>
use:
//the remoteCommand should be placed before the first menu
<p:remoteCommand name="updateMuncipios_eam" update="municipios_eam"/>
<h:outputText value="ESTADO:" />
//some more code
<p:ajax listener="#{municipiosMB.handleEstadosChange}" oncomplete="updateMuncipios_eam()/>

How to get value of selectOneListbox

I have the following select items to be loaded dynamically:-
<f:selectItems value="#{clientBean.onlineList}" var="user"
itemLabel="#{user.nick}" itemValue="#{user.id}" />
onlineList itself is a list of a bean:-
List<OnlineList> onlineList=new ArrayList<OnlineList>();
public class OnlineList {
Integer id;
String nick;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;
}
}
When user clicks on a row, how do I get the selected object (the bean)?
lets supposed that you have
<h:selectOneListbox value="#{clientBean.selectedObject}">
<f:selectItems value="#{clientBean.onlineList}" var="user"
itemLabel="#{user.nick}" itemValue="#{user.id}" />
</h:selectOneListbox>
The value of your selectOneListbox is being set to selectedObject (object of type OnlineList in your clientBean)

How can I use multiple value in Input text field JSF

In my xhtml there are 3 input field which calculate remaining day of two <p:calendar> dates. In next step I want to store calculated remaining day to MY DB.
<p:dataTable styleClass="vtable" editable="true" var="user"
editMode="cell" value="#{userBean.employeeList}">
<p:column styleClass="columntd" headerText="#{text['user.startedDate']}">
<p:calendar widgetVar="fromCal" value="#{vacationBean.vacation.beginDate}">
<p:ajax event="dateSelect" listener="#{dayDiffBean.fromSelected}"
update="diff" />
</p:calendar>
</p:column>
<p:column styleClass="columntd"
headerText="#{text['user.finishedDate']}">
<p:calendar widgetVar="toCal" value="#{vacationBean.vacation.endDate}">
<p:ajax event="dateSelect" listener="#{dayDiffBean.toSelected}"
update="diff" />
</p:calendar>
</p:column>
<p:column styleClass="columntd"
headerText="#{text['employee.remainingdays']}">
<p:inputText id="diff" styleClass="daysNumber"
value="#{dayDiffBean.diff}" />
</p:column>
</p:dataTable>
<h:commandButton styleClass="sndbutton1"
value="#{text['employee.send']}" action="#{vacationBean.addVac}"/>
I used value="#{dayDiffBean.diff} to get remaining day and now I also want to use my vacationbean to store remaingday to my db using like this : value="#{vacationBean.vacation.balanceDay}"
But I cant use 2 value in inputtext field like this:
<p:inputText value="dayDiffBean.diff" value1="vacationBean.vacation.balanceDay">
How can i solve this problem?
This is my vacation bean code:
#ManagedBean(name="vacationBean")
#ViewScoped
public class VacationBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private Date vEndDate;
private boolean selected;
private Date vStartDate;
private Date createdDate;
private String isNobody;
Requestrelax vacation;
Employee e;
Calendar javaCalendar = null;
private short balanceDay;
#EJB
VacationLocal vacations;
#ManagedProperty(value="#{loginBean.userId}")
Integer userId;
#EJB
EmployeesLocal employees;
#PostConstruct
public void init(){
System.out.println("0");
//System.out.println("STATrtsg >> . "+ diff.getDiff());
vacation=new Requestrelax();
e=employees.getEmployee(userId);
vacation.setEmployee(e);
System.out.println("balanday is:"+balanceDay);
}
public void addVac(){
System.out.println("1");
javaCalendar = Calendar.getInstance();
Date currenDate=Calendar.getInstance().getTime();
vacation.setCreatedDate(currenDate);
vacation.setBalanceDay(balanceDay);
vacations.addEmployeeVacation(vacation);
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Employee getE() {
return e;
}
public void setE(Employee e) {
this.e = e;
}
public Requestrelax getVacation() {
return vacation;
}
public void setVacation(Requestrelax vacation) {
this.vacation = vacation;
}
public Date getvEndDate() {
return vEndDate;
}
public void setvEndDate(Date vEndDate) {
this.vEndDate = vEndDate;
}
public Date getvStartDate() {
return vStartDate;
}
public void setvStartDate(Date vStartDate) {
this.vStartDate = vStartDate;
}
public short getBalanceDay() {
return balanceDay;
}
public void setBalanceDay(short balanceDay) {
this.balanceDay = balanceDay;
}
public Date getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Date createdDate) {
this.createdDate = createdDate;
}
public String getIsNobody() {
return isNobody;
}
public void setIsNobody(String isNobody) {
this.isNobody = isNobody;
}
}
And daydiffbean code :
#ManagedBean(name="dayDiffBean")
#SessionScoped
public class DayDiffBean implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Date from;
private Date to;
private String diff="";
private final long oneDay=1000*60*60*24;
public void fromSelected(SelectEvent event){
from=(Date) event.getObject();
calDiff();
}
public void toSelected(SelectEvent event){
to=(Date) event.getObject();
calDiff();
}
public void calDiff(){
if(from==null||to==null){
diff="N/A";
return;
}
diff=(to.getTime()-from.getTime())/oneDay+"";
}
public String getDiff() {
return diff;
}
public void setDiff(String diff) {
this.diff = diff;
}
public void setFrom(Date from) {
this.from = from;
}
public Date getFrom() {
return from;
}
public Date getTo() {
return to;
}
public void setTo(Date to) {
this.to = to;
}
}
From the code, one way to add balanceDay to your vacationBean is by passing the diff string as a parameter to addVac() method (notice action in the second line):
<h:commandButton styleClass="sndbutton1" value="#{text['employee.send']}"
action="#{vacationBean.addVac(dayDiffBean.diff)}"/>
Then, for your VacationBean.addVac():
// 'diff' is now being passed in as a parameter
public void addVac(String diff) {
System.out.println("1");
javaCalendar = Calendar.getInstance();
Date currenDate=Calendar.getInstance().getTime();
vacation.setCreatedDate(currenDate);
vacation.setBalanceDay(balanceDay);
// UPDATED
// so now you can set balanceDay
setBalanceDay(Short.parseShort(diff));
vacations.addEmployeeVacation(vacation);
}

Primefaces p:orderList java backing list does not update

I am currently implementing a orderable list using PrimeFaces' component, embedded inside a . I was able to get the list to appear properly with my items. However, when I saved the list and submitted it back to the server, the rearranged items did not get reflected in the backing bean for some reason. Since the Primefaces showcase was able to see the changes, what am I doing wrong?
XHTML Snippet:
<h:form id="confirmDialogForm">
<p:confirmDialog id="arrangeProjDialog" widgetVar="arrangeDlg" width="600"
header="Meeting Order"
appendToBody="true" message="Drag and drop to rearrange meeting order">
<p:orderList id="arrangeProjDialogList"
value="#{adminMeetingListBean.orderProjList}"
converter="#{adminMeetingListBean.rowConverter}"
var="po"
controlsLocation="left"
styleClass="wideList"
itemLabel="#{po.projectTitle}"
itemValue="#{po}"
>
<f:facet name="caption">Proposals</f:facet>
</p:orderList>
<p:commandButton value="Save" ajax="true" process="arrangeProjDialogList #this"
actionListener="#{adminMeetingListBean.updateProposalMeetingOrder}" onclick="arrangeDlg.hide();">
</p:commandButton>
<p:button value="Cancel" onclick="arrangeDlg.hide(); return false;" />
</p:confirmDialog>
</h:form>
Backing Bean:
public void updateProposalMeetingOrder() {
if (selectedMeeting != null) {
orderProjTitles.get(0);
meetingService.updateMeetingProjSequence(orderProjList, selectedMeeting.getMeetingId());
}
}
The List is a list of POJO "ProposalOrderRow" objects. This has the definition:
public class ProposalOrderRow implements Serializable {
private static final long serialVersionUID = -5012155654584965160L;
private int dispSeq;
private int appId;
private int assignmentId;
private String refNo;
private String projectTitle;
public int getDispSeq() {
return dispSeq;
}
public void setDispSeq(int dispSeq) {
this.dispSeq = dispSeq;
}
public int getAppId() {
return appId;
}
public void setAppId(int appId) {
this.appId = appId;
}
public String getRefNo() {
return refNo;
}
public void setRefNo(String refNo) {
this.refNo = refNo;
}
public String getProjectTitle() {
return projectTitle;
}
public void setProjectTitle(String projectTitle) {
this.projectTitle = projectTitle;
}
public int getAssignmentId() {
return assignmentId;
}
public void setAssignmentId(int assignmentId) {
this.assignmentId = assignmentId;
}
}
Converter:
#FacesConverter("proposalOrderRowConverter")
public class ProposalOrderRowConverter implements Converter {
private List<ProposalOrderRow> orderRows;
#Override
public Object getAsObject(FacesContext context, UIComponent component, String newValue) {
if (newValue.isEmpty()) {
return null;
}
for (ProposalOrderRow item : orderRows) {
String refNo = item.getRefNo();
if (refNo.equals(newValue)) {
return item;
}
}
return null;
}
#Override
public String getAsString(FacesContext context, UIComponent component, Object value) {
if (value == null) {
return "";
}
ProposalOrderRow row = (ProposalOrderRow) value;
String output = row.getRefNo();
return output;
}
public List<ProposalOrderRow> getOrderRows() {
return orderRows;
}
public void setOrderRows(List<ProposalOrderRow> orderRows) {
this.orderRows = orderRows;
}
}
This problem is caused by appendToBody="true" in the confirm dialog. Setting it to false solved the problem.
See link here: link

Catching PrimeFaces's spinner value inside repeat structure

I'm using Primefaces and spinner component. My problem is that the spinner value is not set in the bean, if it's inside an iteration structure. My spinner is inside ui:repeat.
In the end, the problem is how to deal with different form controls mapping to the same property in bean.
<h:form>
<ui:repeat var="item" value="#{myBean.items}">
<p:spinner size="2" min="1" max="50" style="width:75px" value="#{cartBean.quantityToOrder}"/>
<p:commandButton value="Add to cart" action="#{cartBean.saveItemToCart(item)}" ajax="false"/>
</ui:repeat>
</h:form>
and my bean
#ManagedBean
#SessionScoped
public class CartBean extends BaseBean {
private int quantityToOrder;
//setter, getter...
//When called quantityToOrder = 0 always
public void saveItemToOrder(Item item) {
quantityToOrder IS 0.
}
}
I suspect it has to do with form submission, I have tried a form enclosing all elements in the collection and also a form enclosing any of the spinners + button. The generated client IDs are distinct for all spinners.
Any help would be appreciated.
Put a System.out.println("quantity: " + quantityToOrder) on your setQuantityToOrder(int quantityToOrder) method and will will see the problem. The value of the last spinner will prevail over the others because all the spinners are pointed to the same property (cartBean.quantityToOrder).
Try moving the quantityToOrder to the Item as follows:
<h:form id="mainForm">
<ui:repeat value="#{cartBean.items}" var="item">
<p:outputLabel value="#{item.name}: " for="sp" />
<p:spinner id="sp" size="2" min="1" max="50" style="width:75px" value="#{item.quantityToOrder}" />
<p:commandButton value="Add to cart" action="#{cartBean.saveItemToOrder(item)}" process="#this, sp" update=":mainForm:total" />
<br />
</ui:repeat>
Total: <h:outputText id="total" value="#{cartBean.quantityToOrder}" />
</h:form>
The cartBean:
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
#SessionScoped
public class CartBean implements Serializable {
private List<CartItem> items;
private int quantityToOrder;
#PostConstruct
public void setup() {
items = new ArrayList<CartItem>();
items.add(new CartItem(1, "A"));
items.add(new CartItem(2, "B"));
items.add(new CartItem(3, "C"));
}
public void saveItemToOrder(CartItem item) {
//do whatever you want to do with the item quantity.
System.out.println("Qtd of " + item.getName() + ": " + item.getQuantityToOrder());
//to calculte the qtd of items on the cart.
quantityToOrder = 0;
for (CartItem cartItem : items) {
quantityToOrder += cartItem.getQuantityToOrder();
}
}
public List<CartItem> getItems() {
return items;
}
public void setItems(List<CartItem> items) {
this.items = items;
}
public int getQuantityToOrder() {
return quantityToOrder;
}
public void setQuantityToOrder(int quantityToOrder) {
this.quantityToOrder = quantityToOrder;
}
}
The CartItem:
import java.io.Serializable;
public class CartItem implements Serializable {
private Integer id;
private Integer quantityToOrder;
private String name;
public CartItem(Integer id, String name) {
this.id = id;
this.name = name;
quantityToOrder = 0;
}
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 Integer getQuantityToOrder() {
return quantityToOrder;
}
public void setQuantityToOrder(Integer quantityToOrder) {
this.quantityToOrder = quantityToOrder;
}
#Override
public int hashCode() {
int hash = 7;
hash = 67 * hash + (this.id != null ? this.id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CartItem other = (CartItem) obj;
if (this.id != other.id && (this.id == null || !this.id.equals(other.id))) {
return false;
}
return true;
}
}

Resources