Grails Cookbook - A collection of tutorials and examples

Grails Select Enum Values

It is more convenient that we use Enums in our domain classes rather than String, when we are really sure that Enum is the best representation of a property. Maintaining Strings and constants is just a pain. But it is common problem on how to create a form that accepts Enum values. Below is an example on how to use Select Tag inGrails to choose from Enum values.

I usually prefer placing the Groovy file for the Enum on the same package as the domain. I don't place it under <project-root>/src folder. I place both on <project-root>/grails-app/domain. This could be the contents of Person.groovy

class Person {
    String firstName, lastName
    ECareer career
}
And this could be the contents of ECareer.groovy
enum ECareer {
    ACCOUNTING_AND_FINANCE,
    BUSINESS_DEVELOPMENT,
    RETAIL,
    SALES,
    OTHER;
}

Here is an example on how to use the Select Tag to accept Enum values.

<%@ page import="some.package.ECareer" %>
<g:select name="career" from="${ECareer.values()}" optionKey="key" value="${personInstance?.career?.key}"/>

We can control the label by adding valueMessagePrefix, for example:
<%@ page import="some.package.ECareer" %>
<g:select name="career" from="${ECareer.values()}" optionKey="key" value="${personInstance?.career?.key}" valueMessagePrefix="Enum.ECareer"/>

Then we can add these to our resource bundle:

Enum.ECareer.ACCOUNTING_AND_FINANCE=Accounting and Finance
Enum.ECareer.BUSINESS_DEVELOPMENT=Business Development
Enum.ECareer.RETAIL=Retail
Enum.ECareer.SALES=Sales
Enum.ECareer.OTHER=Others