users@glassfish.java.net

Re: JSF, selectOneMenu, enum and EnumConverter

From: Ryan Lubke <Ryan.Lubke_at_Sun.COM>
Date: Fri, 13 Oct 2006 09:24:17 -0700

Antonio Goncalves wrote:
> Thanks for the example. It works great and it's quite simple.
>
> But I need a little extra to make it pretty. Instead of displaying the
> enumeration value, I want to display a String representation.... but I
> can't make it work :o(
>
> Imagine that you change your enum into :
>
> public enum VALUE {
> VALUE1("Value 1"),
> VALUE2("A second value"),
> VALUE3("And a third one");
>
> private String name;
>
> VALUE(String name) {
> this.name <http://this.name> = name;
> }
>
> public String toString() {
> return name;
> }
> }
>
> With that you can get a nice list with
> "Value 1"
> "A second value"
> "And a third one"
>
> The problem is then it tries to converter the String into an Enum.
> I've tried to change the getter and the setter to take a String as a
> parameter but it doesn't work either :
>
> public void setSelectedValue(String selectedValue) {
> for (VALUE value : VALUE.values()) {
> if (value.toString().equals(selectedValue)) {
> this.selectedValue = value;
> }
> }
> }
>
> public String getSelectedValue() {
> if (selectedValue == null)
> return "";
> return selectedValue.toString();
> }
>
>
>
> Any idea ? Should the EnumConverter be used in this case ?
Instead of overriding toString() in your enum, I'd suggest renaming the
method to getLabel().
Then when constructing the SelectItem instances you would do: new
SelectItem(enum, enum.getLabel());

This way the EnumConverter still does its thing when converting between
the view and model and you
get the desired label.

>
> Thanks,
>
> Antonio
> 2006/10/11, Ryan Lubke <Ryan.Lubke_at_sun.com <mailto:Ryan.Lubke_at_sun.com>>:
>
> Antonio Goncalves wrote:
> > Hi,
> >
> > I'm using GLassfish v2b19 (JSF 1.2 then) and I want to fill a
> > selectOneMenu component with an enumeration. The Unified EL is
> > supposed to support enums but I couldn't make it work. I had a
> look at
> > the class EnumConverter but don't really know how to use it.
> >
> > Does anybody know how to fill a selectOneMenu with a enum ?
> >
> > Thanks,
> >
> > Antonio
> Hello Antonio,
>
> I've attached a simple example using a selectOneMenu with Enums. No
> need to worry about
> the converter, the framework takes care of that for you.
>
> Unjar the attached file to obtain the source and the packaged WAR
> file.
>
> To invoke the sample, deploy the WAR, and issue the following
> request: http://localhost:8080/enumselect/faces/Enum.jsp
>
> Hope this helps.
>
> -rl
>
>
> ---------------------------------------------------------------------
> To unsubscribe, e-mail: users-unsubscribe_at_glassfish.dev.java.net
> <mailto:users-unsubscribe_at_glassfish.dev.java.net>
> For additional commands, e-mail: users-help_at_glassfish.dev.java.net
> <mailto:users-help_at_glassfish.dev.java.net>
>
>
>