Grails Fields Plugin: select with internationalized labels

If you are using the Fields Plugin and want to have a select box with internationalized labels you have two options:

Assuming you have a Weekday enumeration com.mycompany.Weekday

package com.mycompany

enum Weekday {
	MONDAY,
	TUESDAY,
	WEDNESDAY,
	THURSDAY,
	FRIDAY
}

and the following messages

com.mycompany.Weekday.MONDAY = Monday
com.mycompany.Weekday.TUESDAY = Tuesday
com.mycompany.Weekday.WEDNESDAY = Wednesday
com.mycompany.Weekday.THURSDAY = Thursday
com.mycompany.Weekday.FRIDAY = Friday

1. Pass the valueMessagePrefix to the field tag.

<f:field property="weekday" 
         input-valueMessagePrefix="com.mycompany.Weekday" 
         input-noSelection="['':'- choose weekday -']" />

Please note the input- prefix which is used to pass attributes to the underlying tag.

2. Customize field rendering for all enumerations

Create the following GSP in grails-app/views/_fields/enum/_input.gsp

<g:select name="${property}"
		from="${type?.values()}"
 		keys="${type?.values()*.name()}"
 		value="${value}"
 		valueMessagePrefix="${type.name}" />

I prefer the 2nd option because you have to do it only once for all enumerations and the labels for an are probably the same whereever you use it.

Update 20.2.2013
The above code snippet doesn’t work if you are using a prefix, so I adjusted the name attribute. You can omit the keys attribute if you don’t override toString() of the enum.

<g:select name="${(prefix ?: '') + property}"
		from="${type?.values()}"
 		value="${value}"
 		valueMessagePrefix="${type.name}" />
Advertisements
Posted in Grails. Tags: . 1 Comment »

One Response to “Grails Fields Plugin: select with internationalized labels”

  1. cdeszaq Says:

    This would be a fantastic contribution to the documentation for the Fields plugin. I have opened an issue to add documentation around this issue (https://github.com/robfletcher/grails-fields/issues/96), and this article does a great job of it. Please consider submitting a pull request :)


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

%d bloggers like this: