Bella
Bella

Reputation: 185

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?

Upvotes: 2

Views: 4085

Answers (2)

Victor Sergienko
Victor Sergienko

Reputation: 13475

  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.

Upvotes: 1

Ho&#224;ng Long
Ho&#224;ng Long

Reputation: 10848

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.

Upvotes: 0

Related Questions