knorv
knorv

Reputation: 50117

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

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)?

Upvotes: 1

Views: 2937

Answers (2)

John Stoneham
John Stoneham

Reputation: 2483

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

Upvotes: 0

knorv
knorv

Reputation: 50117

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" />

Upvotes: 5

Related Questions