I am using a selectOneMenu in a JSF 2 applicaiton to allow users to select a day in a month. For some reason I can’t get the label, “Select Day” to show up. This is what I am doing:
<h:selectOneMenu id="startDay" value="#{bean.day}">
<f:selectItem itemLabel="Select Day" itemValue=""/>
<f:selectItems value="#{bean.days}"/>
</h:selectOneMenu>
The code in the bean is like this:
private int day;
private List<Integer>days;
Which I’m instantiating in a @PostConstruct init method:
days = new LinkedList<Integer>();
for(int i=1; i<=31; i++) {
days.add(i);
}
Everything works fine, but the value displayed in “1” and not “Select Day.” I tried different variations on the tags above but nothing works. What am I missing?
EDIT: I also have a similar widget displaying years, which is initialized in the same way but with the loop starting at 2012. Like this:
years = new LinkedList<Integer>();
for(int i=2012; i<=2020; i++) {
years.add(i);
}
This works fine, showing “Select Year” as expected. So is the issue with the instantiating loop starting at 1? And if so, what’s the workaround?
Your code looks fine so far. The “problem” as you described will occur if you have preinitialized the
<h:selectOneMenu value>with exactly the item value. In your case, most likely you’ve set the value ofdayto1somewhere in your real code. For example,or
Etcetera.
Update: as per your comment:
Put the bean in the view scope instead of the session scope. The session scope is the wrong scope for input forms. It should be used for session specifid data only, such as the logged-in user, its preferences and so on. See also Communication in JSF2 – Managed bean scopes.