14

I'm trying to use an enum in a Grails 2.1 domain class. I'm generating the controller and views via the grails generate-all <domain class> command, and when I access the view I get the error shown below. What am I missing here?

Error

Failed to convert property value of type java.lang.String to required type 
com.domain.ActionEnum for property action; nested exception is 
java.lang.IllegalStateException: Cannot convert value of type 
[java.lang.String] to required type [com.domain.ActionEnum] for property action: 
no matching editors or conversion strategy found

Enum (in /src/groovy)

package com.domain

enum ActionEnum  {
    PRE_REGISTER(0), PURCHASE(2)

    private final int val
    public ActionEnum(int val) {
        this.val = val
    }

    int value() { return value }
}

Domain

package com.domain

class Stat {
    ActionEnum action

    static mapping = {
        version false
    }
}   

View

<g:select name="action" 
    from="${com.domain.ActionEnum?.values()}"
    keys="${com.domain.ActionEnum.values()*.name()}" required="" 
    value="${xyzInstance?.action?.name()}"/>



EDIT

Now getting error Property action must be a valid number after changing the following.

View

<g:select optionKey='id' name="action" 
from="${com.domain.ActionEnum?.values()}" 
required="" 
value="${xyzInstance?.action}"/>  // I tried simply putting a number here

Enum

package com.domain

enum ActionEnum  {
    PRE_REGISTER(0), PURCHASE(2)

    final int id
    public ActionEnum(int id) {
        this.id = id
    }

    int value() { return value }

    static ActionEnum byId(int id) {
        values().find { it.id == id }
    } 
}

Domain

package com.domain.site

class Stat {
    static belongsTo = Game;

    Game game
    Integer action

    static mapping = {
        version false
   }

    static constraints = {
        action inList: ActionEnum.values()*.id
    }

    String toString() {
        return "${action}"
    }
}
Shashank Agrawal
  • 25,161
  • 11
  • 89
  • 121
RC.
  • 27,409
  • 9
  • 73
  • 93
  • Take a look here ... http://stackoverflow.com/questions/3748760/grails-enum-mapping http://stackoverflow.com/questions/1969448/grails-gorm-enums – chrislovecnm Aug 21 '12 at 00:02

1 Answers1

25

Take a look here ...

Grails Enum Mapping

Grails GORM & Enums

Also you may be hitting this as well. From the docs:

1) Enum types are now mapped using their String value rather than the ordinal value. You can revert to the old behavior by changing your mapping as follows:

static mapping = {
    someEnum enumType:"ordinal"
}
Community
  • 1
  • 1
chrislovecnm
  • 2,549
  • 3
  • 20
  • 36
  • +1 I had already seen the second link, but did not see the first. I'm closer thanks to your help. See question edits as I seem to be having a validation issue now. Thanks! – RC. Aug 21 '12 at 00:34