I think, therefore I blog

Using Enums in EL

By , 21 January 2009

Using Enums in EL

Unfortunately EL has no special support for enums. That makes it especially hard when you need to input enum values (for example from a dropdown box). One simple solution is to add a getter and setter to your bean to marshall the String value to and from an enum:

enum Status { A, B, C, D}

/* EL convenience getters and setters */
public String getStatus_() {
    return (status == null) ? null : status.name();
}
public void setStatus_(String status) {
    this.status = Status.valueOf(status);
}

Now you can build your dropdowns easily like this:

<h:outputText value="Status:"/>
<h:selectOneMenu value="${bean.status_}">
  <f:selectItem itemValue="A" itemLabel="Asleep"/>
  <f:selectItem itemValue="B" itemLabel="Bored"/>
  <f:selectItem itemValue="C" itemLabel="Creative"/>
  <f:selectItem itemValue="D" itemLabel="Dead"/>
</h:selectOneMenu>

In this example I use the underscore on the method name to distinguish it from the regular getter and setter which are not shown.

Using Enums in EL
 

About Roger Keays

Using Enums in EL

Roger Keays is an artist, an engineer, and a student of life. Since he left Australia in 2009, he has been living as a digital nomad in over 40 different countries around the world. Roger is addicted to surfing. His other interests are music, psychology, languages, and finding good food. Click here to subscribe to his weekly blog, or stalk him on Facebook and Twitter.

Leave a Comment

Please visit https://RogerKeays.com/blog/using-enums-in-el to add your comments.

Join 3,559 People Who Think Outside The Box

I write every Sunday about travel, psychology, technology, and all sorts of interesting stuff. It's completely free, and you can subscribe for as long as you like. Do it now, so you don't miss a single post.

Chat For A While

Your Vote Matters

Which animal will take over when humans go extinct?
Lions
Dogs
Pigs
Octopuses
Cockroaches
Rats
Dolphins
Sharks
Jellyfish
Cows

Read a Good Book

“A spellbinding true story of love, passion and adventure. One can’t help but be swept away by 100% Love Guaranteed.” —Dr Tammie Matson, author of Elephant Dance.