问题
I am trying to bind some data to an object that is part of a command object. The object stays null when trying to use it. Probably i am not giving the correct data in the gsp but i have no clue what am i doing wrong!
I would expect that when i submit a form with a field name 'book.title' this would get mapped into the command object.. but this fails.. The title stays [null]
Whenever i change the command object and form to use String title as property it works..
// the form that submits the data
<g:form>
<g:textField name="book.title" value="Lord Of the Rings"/><br>
<br><br>
<g:actionSubmit action="create" value="Create!"/>
</g:form>
// the controller code
def create = { BooksBindingCommand cmd ->
println cmd?.book?.title // the book property always stays null
redirect(action: "index")
}
// the command object
class BooksBindingCommand {
Book book
}
// the book class, simple plain groovy class
class Book {
String title
}
Any suggestion on why the binding of 'book.title' fails?
回答1:
Try to initialize it before binding, like:
// the command object
class BooksBindingCommand {
Book book = new Book()
}
回答2:
Just a quick stab at it.
The form field name should probably be book_title rather than using a period (not sure if it becomes a problem when handled in the controller).
<g:textField name="book_title" value="Lord Of the Rings"/><br>
In your controller, create your book model first, then assign it to the class you want it bound to.
def create = {
def mybook = new Book()
mybook.title = params.book_title
def binder = new BooksBindingCommand()
binder.book = mybook
}
Is the BooksBindingCommand a model? Because I'm not sure what you're trying to achieve.
来源:https://stackoverflow.com/questions/9011156/how-to-bind-data-to-a-command-object-that-has-a-nested-property-non-domain-obj