1

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?

Marco
  • 15,101
  • 33
  • 107
  • 174

2 Answers2

7

Try to initialize it before binding, like:

// the command object
class BooksBindingCommand {
   Book book = new Book()
}
Igor Artamonov
  • 35,450
  • 10
  • 82
  • 113
  • Txs.. this solved my little puzzle! Initializing the object in the CommandObject did the trick. Is this because the 'Book' object is a non domain / non model object? I guess so.. – Marco Jan 26 '12 at 06:18
  • This has a problem though, and is that you loose the ability to detect whether the book was null or not. So the possible constraint "book nullable:false" is never going to fail, even if no book was present in the params / JSON... – Deigote Jun 17 '15 at 13:39
0

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.

ibaralf
  • 12,218
  • 5
  • 47
  • 69
  • This will work surely as it would do the binding in a manual way. The use case in my example was that i wanted to bind incoming data to a non - domain/model object. Now i am able to just create a Book object with the nested properties like (title etc) The form that submits the data uses 'book.title' as its name. This gives me the possibilities to combine properties in groovy objects (src/groovy) and work from that instead of specifying all the properties in de command object. – Marco Jan 26 '12 at 07:13