Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF . SelectOneMenu and SelectItems

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

like image 658
andreaxi Avatar asked Oct 07 '22 14:10

andreaxi


2 Answers

Add <f:ajax/> to your <h:selectOneMenu value="#{MyBean.user}">

like this

<h:selectOneMenu value="#{MyBean.user}">
    <f:ajax/>
    <f:selectItems value="#{MyBean.userList}" var="currentUser" itemValue="#{currentUser.username}" itemLabel="#{currentUser.username}"/>
</h:selectOneMenu>

this will submit your selection to the server each time you will choose a value from the dropdown...

OR

add <f:ajax execute="@form"/> to your button so it will submit the selection of your dropdown menu before the call to insertItem

<h:commandButton value="Insert" action="#{AuctionBean.insertItem}">
    <f:ajax execute="@form"/>
</h:commandButton> 
like image 29
Daniel Avatar answered Oct 13 '22 09:10

Daniel


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

See also:

  • Our selectOneMenu wiki page

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:

  • Migrating from JSF 1.2 to JSF 2.0
like image 169
BalusC Avatar answered Oct 13 '22 11:10

BalusC