Grails form data binding when another domain object is referenced in the form

Tag: grails Author: guniaotiankong Date: 2009-08-30

How do I get Grails data binding to correctly bind referenced objects (such as Country in the example below)?

Given the following two Grails domain classes ..

class User {
  String username
  Country country
}

class Country {
  String name
}

.. and the following HTML form ..

<g:form>

<g:textField name="user.username" value="${user.username}" />

<g:select name="user.country" from="${Country.list()}" optionKey="id" />

</g:form>

.. and the following code in the corresponding action ..

User user = new User(params["user"])

.. I would have hoped that user.username and user.country would get bind. However, it appears as if username.username gets bind, whereas user.country is not. What is the correct syntax to bind referenced objects (user.country in this example)?

Best Answer

The binding of the "country" property starts working if ..

<g:select name="user.country" from="${Country.list()}" optionKey="id" />

.. is changed to ..

<g:select name="user.country.id" from="${Country.list()}" optionKey="id" />

Other Answer1

You should also look into command objects. They can validate and bind all of your parameters at once.