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)?
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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With