Groovy and Grails: Using Enum as dropdown or Combobox for int value

Sample Enum:
public enum FruitType {
Apple(1),
Orange(2);

final Integer id

FruitType(Integer id) {
this.id = id
}

}

In domain class you can define the type by:

Integer fruitType

Adding static contains:

static constraints = {fruitType(nullable: false, inList: [FruittType.Apple, FruitType.Orange])}

Now in GSP you can use this enum as drop-down by following code

<g:select name=”fruitType” from=”${FruitType?.values()}” value=”${fruitInstance?.fruitType}”  />

One Response to Groovy and Grails: Using Enum as dropdown or Combobox for int value

  1. Lakshmi says:

    Hi

    public enum Gender {
    Male(0),
    Female(1)
    final Integer id
    String getId() { id }

    Gender(Integer id) {
    this.id = id
    }
    }
    class Students {
    ObjectId id

    String firstname
    String lastname
    Integer gender

    static mapping = {
    phoneNumber(attr:”phonenumber”)
    bloodGroup(attr:”bloodgroup”)
    }

    static constraints = {
    firstname(blank: false, nullable: false)
    lastname(blank: true, nullable: true)
    gender(nullable: false, inList: [Gender.Male,Gender.Female])
    }
    }

    and trying to save and giving the following error
    Property [gender] of class [class Students] with value [1] is not contained within the list [[Female, Male]]

    what is the problem ?

Leave a comment