Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSF 2.0: use Enum values for selectOneMenu [duplicate]

I'm using JSF 2.0 and want to fill a selectOneMenu with the values of my Enum. A simple example:

// Sample Enum
public enum Gender {
  MALE("Male"),
  FEMALE("Female");

  private final String label;

  private Gender(String label) {
    this.label = label;
  }

  public String getLabel() {
    return this.label;
  }
}

Unfortunately, i can't use Seam for my current project, which had a nice <s:convertEnum/> Tag that did most of the work. In Seam, to use the values of the Enum, i had to write the following markup (and create a factory that provides the #{genderValues}:

<!-- the Seam way -->
<h:selectOneMenu id="persongender" value="#{person.gender}">
  <s:selectItems var="_gender" value="#{genderValues}"" label="#{_gender.label}"/>
  <s:convertEnum/>
</h:selectOneMenu>

The result is that i don't have to declare the Enum values explicitely anymore inside the markup. I know that this is not very easy in JSF <2.0, but is there any new in JSF2 to help with this issue? Or does Weld help here somehow? If there is nothing new in JSF2, what's the easiest way to do it in JSF 1.2?

Or can i even integrate the Seam JSF tag and the corresponding classes of Seam to get the same feature in a JavaEE6-App (without the Seam container)?

like image 735
Wolkenarchitekt Avatar asked May 19 '10 19:05

Wolkenarchitekt


2 Answers

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!

like image 70
Wolkenarchitekt Avatar answered Oct 24 '22 06:10

Wolkenarchitekt


Here's a simpler method which uses a simple getter and setter to marshal strings to enums.

https://rogerkeays.com/blog/using-enums-in-el

like image 5
Roger Keays Avatar answered Oct 24 '22 06:10

Roger Keays