12

Example:

batchTag is an enumerated type attribute of a batchRange, with values like so:

JAN1 "January Biweekly 1",
JAN2 "January Biweekly 2",

etc.

I want to display the VALUE of the batchTag in the select, IOW, the select should contain

"January Biweekly 1"
"January Biweekly 2" ...

not

JAN1
JAN2
FEB1
FEB2
FEB3 ...

I have tried several things in the g:select to do this, but without any success. I thought perhaps "it" would be available as part of the g:select (as it is clearly an iteration) and tried to reference it.batchTag.name for the optionValue, but that did not work. Any suggestions?

Thank you!

Alexx
  • 3,572
  • 6
  • 32
  • 39

2 Answers2

23
enum BatchRange {
    JAN1 "January Biweekly 1",
    JAN2 "January Biweekly 2",

    final String value

    BatchRange(String value) { this.value = value }

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

Note the getKey() method. And then your g:select

<g:select name="batch" from="${BatchRange.values()}" optionKey="key" />

or

<g:select name="batch" from="${BatchRange.values()}" keys="${BatchRange.values()*.name()}" />
Tyler Rafferty
  • 3,391
  • 4
  • 28
  • 37
Gregg
  • 34,973
  • 19
  • 109
  • 214
  • 1
    Thank you! The second suggestion is what I sought. – Alexx Jun 21 '12 at 19:44
  • The first tag-solution can be simplified to ``. Then you don't need the BatchRange toString- or getKey-methods either. – Wonko Sep 04 '15 at 07:14
  • @Gregg, I am getting the following error: `...No signature of method: static BatchRange.values() is applicable for argument types: () values: [] Possible solutions: use([Ljava.lang.Object;), use(java.lang.Class, groovy.lang.Closure), use(java.util.List, groovy.lang.Closure), save(), evaluate(java.io.File), evaluate(java.lang.String)` Any suggestions?! Thanks. – AlwaysANovice Oct 09 '15 at 18:46
  • @AlwaysANovice you have to create a groovy enum type under src/groovy – Almalerik Feb 23 '16 at 10:22
  • @AlwaysANovice : This syntax worked for me : `CREEE('Créée'), LANCEE('Lancée'), TERMINEE('Terminée')`. see https://grails.org/wiki/TipsAndTricks#Enum%20usage – BenC Jun 01 '16 at 16:17
  • Thank you @Alex and BenC for the help – AlwaysANovice Jun 02 '16 at 17:48
0

A better approach would be to use i18n messages in this case. There are two options:

  1. Add valueMessagePrefix to the select.
  2. Make the enum implement org.springframework.context.MessageSourceResolvable as described in this blog post.

See this question for further information.

stenix
  • 3,068
  • 2
  • 19
  • 30