Grails: populate a g:select from an enum

As easy as it is to hard-code a list into a selection drop down box in grails, it is a pretty big violation of the Don’t Repeat Yourself principle and is best avoided. I struggled to find an answer for a neat way to do this, so here is how I recommend doing it:

Step 1: Define an enum

If you’re using the domain layer you can obviously put your enum in you domain objects and refer to them there in the later steps but for this example I’ll assume you don’t have or can’t change your domain layer.

In src/groovy/myPackage we’ll create a new enum with some values and the pretty standard enum methods.

package com.adamwhittingham.grails.examples.SearchableField:

public enum SearchableField {
    USERNAME(“Username”), FIRSTNAME(“First Name”),SURNAME(“Display Name”),EMAIL("Email")

    final String value
    SearchableField(String value){ this.value = value }

    @Override
    String toString(){ value }
    String getKey() { name() }
}

Step 2: Import it and use it in the GSP

In our GSP, the first thing we need is to know about the enum.

<%! import com.adamwhittingham.grails.examples.SearchableField %>

With that done we can now get to defining the using the enum

<g:select name=”searchBy” from”${SearchableField.values()}” value=”${SearchableField}” optionKey=”key”/>

And that’s it, you can now use the enum in your controllers and views without needing to edit a hard coded lists. Much better!

About these ads

2 thoughts on “Grails: populate a g:select from an enum

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s