且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何将数据绑定到具有嵌套属性的命令对象? (非域对象)

更新时间:2022-10-21 11:12:07

尝试在绑定之前对其进行初始化,例如:

  //命令对象
class BooksBindingCommand {
Book book = new Book()
}


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?

Try to initialize it before binding, like:

// the command object
class BooksBindingCommand {
   Book book = new Book()
}