JSF combobox: display items from Collection

sergionni picture sergionni · Aug 28, 2011 · Viewed 24.6k times · Source

I can't populate a JSF combo box with predefined data from a Java collection.

Backend, simple stub for collection:

PriceRecord pr = new PriceRecord();
pr.setTypeCode(Arrays.asList(123L,456L));

This doesn't work, the combo box remains empty:

<h:selectOneMenu value="#{price.typeCode}" var="code">
    <f:selectItem value="#{code}"/>
</h:selectOneMenu>

Answer

Arjan Tijms picture Arjan Tijms · Aug 28, 2011

The code you've given doesn't seem to make a lot of sense. The idiom is more like this:

<h:selectOneMenu value="#{backingBean.typeCode}">               
    <f:selectItems value="#{backingBean.typeCodes}" var="typeCode" itemLabel="#{typeCode}" itemValue="#{typeCode}" />
</h:selectOneMenu>

Here, #{backingBean.typeCode} is the property that initially returns the single value that represents the default selected value. If it's empty, no value is initially selected. After the user submits the form, it will receive the value the user selected. For your code this would be of type Long.

#{backingBean.typeCodes} is the property that returns a collection of all the values a user can choose between. For your code this would be List<Long>.

Because your values are simple longs, the label and value is the same here. If it was a more complex object like e.g. a User, you could use something like #{user.name} for the itemLabel and #{user.id} for the itemValue. Whatever is rendered for itemValue is what is pushed into the value binding of the selectOneMenu component.

One other hint: in general you should try to avoid using the type SelectItem in your backing beans. Prefer simple domain objects and collections of them instead of JSF specific types.