Herzog
Herzog

Reputation: 953

Item Lable in JSF2 selectOneMenu

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?

Upvotes: 0

Views: 1116

Answers (1)

BalusC
BalusC

Reputation: 1109875

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 of day to 1 somewhere in your real code. For example,

private int day = 1; // Instead of default 0.

or

public Bean() {
    setDay(1);
}

Etcetera.


Update: as per your comment:

I had it this way because I'm using the page both for editing, and entering a new auction and I wanted to make sure that when coming back to the page to enter a new auction, once another auction was edited, we remove the edited auction's values. But that's besides the point, I'll figure out what to do with it.

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.

Upvotes: 1

Related Questions