开发者

grails enum type in domain class

I use grails 1.3.2 and hbase..

I have domain class, one of which fields is in enum type:

class MyDomainClass{

     MyEnum enumVal

        //....

}

public enum开发者_运维百科 MyEnum {

    val1("val1"),
    val2("val2")

   final String value
   MyEnum (String value) {
      this.value = value
    }
   String toString() { value }
   String getKey() { name() }
}


<g:form action="create">
   <g:select name="enumVal" from="${MyEnum ?.values()}" optionKey="key" />
   <g:submitButton name="createOb" value="CreateOb"/>
</g:form>

"create" action have to save selected value in db.

When I submit I get exception:

Cannot cast object 'val1' with class 'java.lang.String' to class 'myPack.MyEnum '

Is there any way to save enum value as a String?


  1. The space after "MyEnum" in GSP and error message makes me doubt, can you remove it from GSP?
  2. You don't need ?, as MyEnum class should always be there.
  3. I believe you don't need optionKey, especially if you have overridden MyEnum.toString().
  4. We write selects from enum this way:

    <g:select from="${SomeEnum.values()*.toFriendlyString()}" keys="${SomeEnum.values()*.name()}" value="${xxxInstance.field.name()}" ... />

where toFriendlyString() is our Enum's method that returns user-readable String representation.


It seems to be a data-type conversion issue. You may try:

def domainObject = new MyDomainClass()
def enumValue = myPack.MyEnum.valueOf(params.enumVal) // This is the conversion.

After that, assign your domain object with the new enumValue.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜