Using enum in selectOneMenu fails with: 'Male' must be convertible to an enum

user1540625 picture user1540625 · Feb 15, 2013 · Viewed 11.5k times · Source

I am about developing a small jsf project and I arrived to a state that I have to store a value in an enumeration type but couldn't figure out how to deal with

so I post here a small description of my problem:

here is the enumeration type:

 package com.enumeration;

 import java.io.Serializable;


 public enum Gender implements Serializable{

    Male('M'), Female('F');

    private char description;

   private Gender(char description) {
     this.description = description;
   }

   public char getDescription() {
     return description;
   }

}

the xhtml page:

    <h:panelGrid columns="2">
                <h:outputLabel value="Nom:" for="nom" />
                <h:inputText id="nom" value="#{employee.newEmployee.nom}" title="Nom" />

                <h:outputLabel value="Gender:" for="gender" />
                <h:selectOneMenu value="#{employeeBean.newEmployee.gender}" id="gender">
                     <f:selectItem itemLabel="Male" itemValue="Male" />
                    <f:selectItem itemLabel="Female" itemValue="Female"/>
                </h:selectOneMenu>

            </h:panelGrid>
            <h:commandButton value="ajouter" action="index.xhtml" actionListener="#{employeeBean.ajouter}" />
        </h:form>

the problem is that when I try to add a new row to the database, and error is thrown by jsf: j_idt7:gender: 'Male' must be convertible to an enum.

I did some search on the net but couldn't understand the solutions please help thanks

Answer

Kawu picture Kawu · Feb 15, 2013

Your problem is that your <f:selectItem> specify strings, while in the <h:selectItem value="#{employeeBean.newEmployee.gender}"> seems to return one of the two Gender enums.

Enums are AFAIK directly convertible without converter as long as you stick the same values into both.

Here's the/a pattern:

<h:selectOneMenu value="#{employeeBean.newEmployee.gender}" id="gender">
    <f:selectItems value="#{enumValuesProvider.genders}"
                   var="gender"
                   itemValue="#{gender}"
                   itemLabel="#{gender.name()}" />
</h:selectOneMenu>

Note, I'm using <f:selectItems> here. The problem is, you can't simply get the values from a JSF page directly. You will need a dedicated bean to do the job:

@Named      // or @ManagedBean if you're not using CDI
@ViewScoped // or @RequestScoped
public EnumValuesProvider implements Serializable
{
    public Gender[] getGenders()
    {
        return Gender.values();
    }
}

This is just written down without any testing. No warranties.