JSF . SelectOneMenu and SelectItems

andreaxi picture andreaxi · Jun 10, 2012 · Viewed 40.7k times · Source

I'm trying to let user select an item of a collection from a dropdown list in JSF. This is the code I'm using:

<f:view>
 <h:form id="insert">
    <h:selectOneMenu value="#{MyBean.user}">
        <f:selectItems value="#{MyBean.userList}" var="currentUser" itemValue="#{currentUser.username}" itemLabel="#{currentUser.username}"/>
     </h:selectOneMenu>
     <h:commandButton value="Insert" action="#{AuctionBean.insertItem}"/><br>
 </h:form>
</f:view>

And this is MyBean's code:

@ManagedBean
public class MyBean{
    private String user;
    private Collection<User> userList;

    @PostConstruct
    public void init() {
                this.userList = UserRepository.getInstance().findAllUsers();
    }
    ...
    public String insertItem() {
         System.out.println("The selected user is " + this.user);
         ...
         return ("successfulInsertion");
    }
...
}

And if needed my getter and setter for user:

public String getUser() {
        return this.user;
    }

    public void setUser(String user) {
        this.user = user;
    }

My problem is that when it prints "The selected user is " there's not written the user.toString(), but userList.toString()! It's like the selectOneMenu it's not correctly setted, but I've searched a lot about it. Anyone can help? Thanks, AN

Answer

BalusC picture BalusC · Jun 10, 2012

The <f:selectItems> doesn't support Collection. You need a List or Map or Object[].

See also:


Update: it turns out that you're using JSP instead of Facelets. The new JSF 2.x tags and attributes are not available for JSP. This includes the <f:selectItems var>. Only the old JSF 1.x tags and attributes are available for JSP. Since JSF 2.0, JSP has been deprecated and succeeded by Facelets. You should be using Facelets instead.

See also: