How to get value of selectOneListbox - jsf

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)

Related

Error with two selectOneMenu nested [duplicate]

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.

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()/>

Weird mark questions between Class members

I have a separate module project setup to load from jar(this is working as expected) but when I try to load a List of objects in datatable or h:selectOneMenu then Class member are shown instead values i.e
public class Client implements Serializable {
private BigInteger idclient;
private String name;
public BigInteger getIdclient() {
return this.idclient;
}
public void setIdclient(BigInteger idclient) {
this.idclient = idclient;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
in controller i have List listClient;
<h:selectOneMenu styleClass="select-input"
id="registerzoneClient"
valueChangeListener="#{managerZoneController.listCountries}"
onchange="this.form.submit();">
<f:selectItem itemLabel="Client" itemValue="-1" />
<f:selectItems value="#{managerZoneController.listClients}"
var="client" itemLabel="#{client.name}"
itemValue="#{client.idclient}" itemDescription="#{client.name}" />
</h:selectOneMenu>
selectOneMenu label is ???name??? and value is ???idclient???

Passing parameters in JSF and PrimeFaces

I am studying a PrimeFaces AutoComplete demo. I shortenied it from the full showcase demo. http://www.primefaces.org/showcase/ui/input/autoComplete.xhtml
AutoCompleteBean.java
#ManagedBean
public class AutoCompleteBean {
private Query query;
private List<Query> queries = new ArrayList<Query>();
#PostConstruct
public void init() {
queries.add(new Query(0, "Afterdark", "afterdark"));
queries.add(new Query(1, "Afternoon", "afternoon"));
queries.add(new Query(2, "Afterwork", "afterwork"));
queries.add(new Query(3, "Aristo", "aristo"));
}
public List<Query> completeQuery(String query) {
List<Query> filteredQueries = new ArrayList<Query>();
for (int i = 0; i < queries.size(); i++) {
Query skin = queries.get(i);
if(skin.getName().toLowerCase().contains(query)) {
filteredQueries.add(skin);
}
}
return filteredQueries;
}
public void onItemSelect(SelectEvent event) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Item Selected", event.getObject().toString()));
}
public Query getQuery() {
return query;
}
public void setQuery(Query query) {
this.query = query;
}
}
Query.java
public class Query {
private int id;
private String displayName;
private String name;
public Query() {}
public Query(int id, String displayName, String name) {
this.id = id;
this.displayName = displayName;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return name;
}
}
I omitted a Convert class, which I think is not that relevant.
search.xhtml
<h:form>
<p:growl id="msgs" showDetail="true" />
<h:panelGrid columns="2" cellpadding="5">
<p:autoComplete id="queryPojo" value="#{autoCompleteView.query}"
completeMethod="#{autoCompleteView.completeQuery}" var="query"
itemLabel="#{query.displayName}" itemValue="#{query}"
converter="queryConverter" forceSelection="true" />
<p:commandButton value="search" oncomplete="PF('dlg').show()"/>
</h:panelGrid>
</h:form>
I have three questions for this:
1) completeMethod="#{autoCompleteView.completeQuery}": completeQuery method is called without passing a parameter, but it's defined as completeQuery(String query). How does this work?
2) value="#{autoCompleteView.query}". Query is an object defined in AutoCompleteBean. How can this Query object take user input string as its value? Usually InputText's value is good for taking user's input, which is a String value.
3) Can I still add an attribute "action=..." to the p:autoComplete componenet?
The converter class that you omitted here plays the real game.... Lets see your questions
As you see converter class overrides 2 methods
getAsString and getAsObject
1)the value
completeMethod="#{autoCompleteView.completeQuery}
gets refactred to
autoCompleteView.completeQuery(autoCompleteView.query);
as you can find to string method in Query class.
2).as converter is defined for autocomplete it calls getAsString method to render on screen. when selected getAsObject method is called to convert string value to object(Query).
3)you can use ajax select event
<p:ajax event="select" listener="#{autoCompleteView.someMethod}">
or call a remoteCommand by onSelect attribute in p:autoComplete
<p:autoComplete id="queryPojo" value="#{autoCompleteView.query}" onSelect="someRemoteCommand();"
completeMethod="#{autoCompleteView.completeQuery}" var="query"
itemLabel="#{query.displayName}" itemValue="#{query}"
converter="queryConverter" forceSelection="true" />
<p:remoteCommand name="someRemoteCommand" update="queryPojo" actionListener="#{autoCompleteView.execute}" />

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);
}

Resources