Using the database introduced in Grails 2.3, I came up with the following solution for converting query parameters to enumeration collection. For example, given these listings
enum Gender { MALE, FEMALE } enum Season { SPRING, SUMMER, AUTUMN, WINTER }
and this command object
class MyCommand { Collection<Gender> genders Collection<Season> seasons }
and suppose we want to convert strings like "MALE,FEMALE" and "SPRING,SUMMER,WINTER" to the corresponding collection of enumerations. First, provide an implementation of FormattedValueConverter that does the conversion
class EnumCollectionConverter implements FormattedValueConverter { private static final List<Class<Enum>> convertableEnums = [Gender, Season] @Override Object convert(value, String format) { Class<Enum> targetEnumClass = convertableEnums.find { it.simpleName == format } if (targetEnumClass) { List<String> enumConstantNames = value.toString().tokenize(',') return enumConstantNames.collect { targetEnumClass.valueOf(it) } } value } @Override Class<?> getTargetType() {
Then register the EnumCollectionConverter as a Spring bean in resources.groovy - it doesn't matter which name you choose for the bean. Then, to use the class above to convert a comma-separated string to a num collection, annotate the corresponding properties with
class MyCommand { @BindingFormat('Gender') Collection<Gender> genders @BindingFormat('Season') Collection<Season> seasons }
The value passed to @BindingFormat must be a simple name of the enumeration type that will be stored in the associated collection.
Dónal source share