简体   繁体   English

在Grails中的命令上将数据绑定到枚举

[英]Data binding to an enum on a command in Grails

I have a class: 我有一堂课:

class User {
    Set<Foo> foos = []
}

where Foo is an enum: Foo是一个枚举:

class Foo { A, B, C, D}

I have a controller action with a parameter of type User 我有一个参数类型为User的控制器动作

def someAction = {User user ->
    // impl omitted   
}

I've created a multi-select in a GSP 我在GSP中创建了多选

<g:select name="foos" multiple="true" from="${Foo.values()}"/>

But when I submit the form the selected values do not get bound to the foos property of the User command object. 但是,当我提交表单时,所选值不会绑定到User命令对象的foos属性。 What am I doing wrong? 我究竟做错了什么?

http://www.grails.org/TipsAndTricks http://www.grails.org/TipsAndTricks

Enum usage 枚举用法

If you want to use a Enum with a "value" String attribute (a pretty common idiom) in a element, try this: 如果要在元素中使用带有“值”字符串属性(一种非常常见的习惯用法)的枚举,请尝试以下操作:

enum Rating {
    G("G"),PG("PG"),PG13("PG-13"),R("R"),NC17("NC-17"),NR("Not Rated")

    final String value

    Rating(String value) { this.value = value }

    String toString() { value }

    String getKey() { name() } 
}

Then add optionKey="key" to your tag. 然后将optionKey =“ key”添加到标签中。 Credit: Gregg Bolinger 图片来源:Gregg Bolinger

This isn't really going to be an answer, per se. 就其本身而言,这并不是真正的答案。 But I can't post the details of this in a comment. 但我无法在评论中发布此细节。 I just created the following: 我刚刚创建了以下内容:

enum State {
  OK,KS,FL,MA
}

class User {
  Set<State> states = []

  static constraints = {
  }
}

<g:form controller="home" action="save">
    <g:select name="states" multiple="true" from="${com.orm.fun.State.values()}"/>
    <g:submitButton name="save" value="Save"/>
</g:form>

// controller action
def save = { User user ->
    // I didn't do anything here except
    // set a breakpoint for debugging
}

And this is what I get: 这就是我得到的:

在IDEA中进行调试

So I'm not entirely sure what is different between yours and mine, except the name of the enum. 因此,我不完全确定您和我的人之间有什么区别,枚举名称除外。 Can you see anything? 你看到什么了吗

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM