JSF 2.0 selctOneMenu with SelectItems

I am new to JSF technology, we are currently using JSF 2.0 with spring and sleep integration in our project. I have one doubt regarding h: selectOneMenu and f: selectItems. From the database, I get a list of UserBeans. I use as

<h:selectOneMenu id="users" value="#{MyBean.user}"> <f:selectItems value="#{MyBean.userList}" var="user" itemLabel="#{user.userName}" itemValue="#{user.userId}" /> </h:selectOneMenu> 

Here the user is of type UserBean, and userList is a list of UserBeans. On the browse page, it displays correctly, but in the backup bean, when I select one item and press the submit button, it shows the selected user as NULL.

My doubt is that I can only pass List of SelectItem for f: selectItems or any other beans list .. ??

Is there any other way to populate the UserBeans otherthan SelectItem list for selectItems.

Thanks Anil

+4
source share
1 answer

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.

+6
source

All Articles