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}" />
Posted in Grails. Tags: . 1 Comment »