Search code examples
grailsenums

How to add a multiple enum field to the create and edit forms in Grails 4?


In my domain model, some classes have a collection of enums as a field. I have modeled it in two differente ways, as an embedded collection:

class A {
  String name
  Set<Enumeration> enumerations

  static embedded = ['enumerations']
}

enum Enumeration {
  ENUM_VALUE_1,
  ENUM_VALUE_2,
  ENUM_VALUE_3
}

And also as a hasMany collection:

class A {
  String name

  static hasMany = [enumerations:Enumeration]
}

enum Enumeration {
  ENUM_VALUE_1,
  ENUM_VALUE_2,
  ENUM_VALUE_3
}

In both cases, I can add enum values to the collection in BootStrap.groovy in the following way:

A.withTransaction { status ->
  def a1 = new A( name:"a1" )
  a1.addToEnumerations( Enumeration.ENUM_VALUE_1 )
  a1.addToEnumerations( Enumeration.ENUM_VALUE_2 )
}

Using scaffolding, I can see the content of the enumeration collection in the index and show pages, but in the edit and create pages, only the label is shown, no widget is displayed.

Which is the simplest way to show a widget, e.g. a multiple select, for this kind of fields in Grails 4 (I am using Grails 4.0.3)?

Thanks in advance.


Solution

  • Which is the simplest way to show a widget, e.g. a multiple select, for this kind of fields in Grails 4 (I am using Grails 4.0.3)?

    You can use the select tag.

    <g:select multiple="true" name="someName" from="${somePackage.SomeEnumClassName}"/>