JSF 2.0: use Enum values for selectOneMenu

Ok, here is the final way: - Register the standard enum converter in faces-config.xml (optional):

<converter>
  <converter-for-class>java.lang.Enum</converter-for-class>
  <converter-class>javax.faces.convert.EnumConverter</converter-class>
</converter>

Add a function for example to a managed bean which converts the Enum values to an array of SelectItems:

@ManagedBean
public class GenderBean {
  public SelectItem[] getGenderValues() {
    SelectItem[] items = new SelectItem[Gender.values().length];
    int i = 0;
    for(Gender g: Gender.values()) {
      items[i++] = new SelectItem(g, g.getLabel());
    }
    return items;
  }
}

Then bind this function to the selectOneMenu in JSF:

<h:selectOneMenu id="gender" value="#{person.gender}">
  <!-- use property name not method name -->
  <f:selectItems value="#{genderBean.genderValues}" />
</h:selectOneMenu>

That's it! Not the first explanation for this problem on the net. But i think it's the easiest & shortest one ;)


After looking at my own Seam example for a minute I created a method in a managed bean like this :

@ManagedBean
public class MyManagedBean {
  public Gender[] getGenderValues() {
    return Gender.values;
  }
}   

And in my markup I put

<h:selectOneMenu id="gender" value="#{person.gender}">
  <f:selectItems value="#{myManagedBean.genderValues}" var="g" 
    itemValue="#{g}" itemLabel="#{g.label}"/>
</h:selectOneMenu>

Now I'll have to see if the enum is saved correctly in my entity when the form is sent. I'll see if I can do this myself - anyway, I would appreciate tips or best practices on this!