Dónal
Dónal

Reputation: 187419

Data binding to an enum on a command in Grails

I have a class:

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

where Foo is an enum:

class Foo { A, B, C, D}

I have a controller action with a parameter of type User

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

I've created a multi-select in a 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. What am I doing wrong?

Upvotes: 4

Views: 2179

Answers (2)

Gregg
Gregg

Reputation: 35904

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:

Debugging in IDEA

So I'm not entirely sure what is different between yours and mine, except the name of the enum. Can you see anything?

Upvotes: 0

Ray Tayek
Ray Tayek

Reputation: 10013

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. Credit: Gregg Bolinger

Upvotes: 2

Related Questions