ENUM in Grails with i18n support

Enums are pretty usefull Java feature. However, developers often encounter problems with two things – reflecting enum in database and i18n. Database is often a easy thing – store enum value in character column or even in specialised column type (eg. in MySQL). Internationalization is a little bit harder but fortunately Grails makes it so easy. The goal of this tutorial is to show how Grails can present enum values in a view layer with translated values.

The key interface is MessageSourceResolvable  which comes of course from Spring. We can have simple enum like this:

 

enum WarriorLevel implements org.springframework.context.MessageSourceResolvable {

    BEGGINER, NOVICE, APPRENTICE, MASTER

    // Methods inherited from interface
    public Object[] getArguments() { [] as Object[] }
    public String[] getCodes() { [ name() ] }
    public String getDefaultMessage() { name() }
}

Nothing new except implementation of methods inherited from interface. They are very simple, just for demonstration purposes.
Another thing to be done are internationalization entries. Grails keeps them in i18n folder with separate files for every language that can be supported. I come from Poland therefore my filename is messages_pl.properties. For given enum entries look like that (prefix is just for clearance):

com.wordpress.chlebik.BEGGINER=nowy
com.wordpress.chlebik=nowicjusz
com.wordpress.chlebik=adept
com.wordpress.chlebik=mistrz

Now the only thing is to put everything in motion – in a view layer we naturally use Grails tags to create select element:

<g:select name="chlebikTest" from="${WarriorLevel?.values()}" keys="${WarriorLevel .values()*.name()}" value="${warrior?.level?.name()}" valueMessagePrefix="com.wordpress.chlebik" />

And that’s all folks. Here are some links about it:

Grails page (check out last entry)
Enum in Grails domain from StackOverflow
Enum in GSP view from StackOverflow

Advertisements

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