You set the user ID as the value of the selection items, but it looks like you are trying to bind value to a full User property in a bean. You need to bind it as a user id.
<h:selectOneMenu id="users" value="#{MyBean.userId}"> <f:selectItems value="#{MyBean.userList}" var="user" itemLabel="#{user.userName}" itemValue="#{user.userId}" /> </h:selectOneMenu>
If your only intention is to be able to select and set User instead of just an identifier, then you will need Converter to convert between User and String . This is because HTTP / HTML does not understand Java objects. He understands only lines. Here is an example run:
<h:selectOneMenu id="users" value="#{MyBean.user}"> <f:selectItems value="#{MyBean.userList}" var="user" itemLabel="#{user.userName}" itemValue="#{user}" /> </h:selectOneMenu>
with
@FacesConverter(forClass=User.class) public class UserConverter implements Converter { @Override public Object getAsObject(FacesContext context, UIComponent component, String value) { try { return userService.findById(Long.valueOf(value)); } catch (SomeException e) { throw new ConverterException(new FacesMessage(String.format("Cannot convert %s to User", value)), e); } } @Override public String getAsString(FacesContext context, UIComponent component, Object value) { return String.valueOf(((User) value).getId()); } }
However, this is a rather expensive job. I would advise sticking with the ID code and getting a valid user in the bean action method only once, instead of letting the converter do this for each individual element.
source share