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?
- The space after "
MyEnum
" in GSP and error message makes me doubt, can you remove it from GSP? - You don't need ?, as
MyEnum
class should always be there. - I believe you don't need
optionKey
, especially if you have overriddenMyEnum.toString()
. We write
select
s 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
.
精彩评论