整数枚举和g:选择

时间:2012-06-30 14:33:51

标签: grails groovy

我有一个像这样的枚举:

public enum MyEnum {
  Apple (1)
  Microsoft (2)
  IBM (4)
  Intel (8)

  int company

  MyEnum(int company) {
    this.company = company
  }
}

我想要一个看起来像这样的g:选择框(整数值在value属性中很重要):

<select>
  <option value="1">Apple</option>
  <option value="2">Microsoft</option>
  <option value="4">IBM</option>
  <option value="8">Intel</option>
</select>

好吧,使用g:select:

没问题
<g:select name="myenum" from="${MyEnum?.values()*.company}" />

但是当我尝试保存表单时,我总是得到: java.lang.IllegalStateException:无法将类型[java.lang.String]的值转换为属性myenum所需的类型[MyEnum]:找不到匹配的编辑器或转换策略

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:2)

尝试:

public enum MyEnum {
  Apple (1)
  Microsoft (2)
  IBM (4)
  Intel (8)

  int company

  MyEnum(int company) {
    this.company = company
  }

  String toString() { return company }
  String getKey() { name() }
}

然后使用

修改标记
<g:select name="myenum" from="${MyEnum?.values()*.company}" optionKey="key" />

答案 1 :(得分:0)

现在我使用带有inList约束而不是枚举的简单整数。它不一样,但解决了我的问题。

class MyDomain {
    int company
    static constraints = {
        company(inList: [1, 2, 4, 8])
    }
}

表格中:     &lt; g:select valueMessagePrefix =&#34; company&#34;命名=&#34;公司&#34;从=&#34; $ {MyDomain.constraints.company.inList}&#34;值=&#34; $ {?myDomainInstance。公司}&#34; /&GT;

现在我需要使用i18n文件(messages.properties):

company.1=Apple
company.2=Microsoft
company.4=IBM
company.8=Intel