Search code examples
grailsgrails-orm

Grails handle objects in select


I have a domain class like this :

class City {
String name;
Country country;

}

In the create view I want to put country as a select box like this :

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

What is the best way to handle the submit, so that the country is sent as an object (currently i receive a message :

    Failed to convert property value of type java.lang.String to required type com.example.Country for property country; 

nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.example.Country] for property country: 

no matching editors or conversion strategy found

)

note : i found this matching question : Grails select not returning the object but a string but the solution didn't solve my problem.

Thank you.


Solution

  • This is because Grails controller doesn't understand what to do with numeric value of country request parameter. Thus, in your controller you should write:

    def country = Country.get(params.getLong('country'))
    def city = new City(name: params.name, country: country)