Search code examples
grailsgrails-ormgsp

How to set default value in grails g:select?


I have domain object City

City{
Long id
String city
...
 String toString() {
        return "$city"
 }
}

Say table is like this.

id  name 
1   ABC
2   PQR
3   XYZ

list of cities I populate in gsp like this

<g:select name="city" from="${City.list()}"  />

Now I need to populate default value of city which comes from controller something like this

cmd.city = "PQR"
render template:'messageDisplay', model:[cmd: cmd]

Now I am trying to populate default value "PQR" in select list

<g:select name="city" from="${City.list()}" value="${cmd.city}" />

but "PQR" doesn't show up as default value.


Solution

  • You have Strings and City objects and are trying to compare them...

    Change your select to:

    <g:select name="city"
              from="${City.list()}"
              value="${cmd?.city?.id}"
              optionKey="id" />
    

    And in your controller:

    cmd.city = City.findByName( "PQR" )