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
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>
The <f:selectItems>
doesn't support Collection
. You need a List
or Map
or Object[]
.
selectOneMenu
wiki pageUpdate: 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With