Search code examples
grailsmodel-view-controllergroovygrails-controller

Formatting POJO inside Grails/GSP select element


I have the following POJO/POGO:

class Person {
    String firstName
    String lastName
    int age
    // ... lots of other fields
}

And a Grails 2.3.6 controller:

class PeopleController {
    List<Person> people = new ArrayList<Person>()

    def populatePeople() {
        // Add lots of people to the 'people' list.
    }

    def doSomething() {
        populatePeople()

        render(
            view: "people", 
            model:[
                people: people,
            ]
        )
    }
}

And then in the GSP:

<div id="peopleSelector">
    <g:select name="people" from="${people}" />
</div>

When I run my app I get the <select> element with com.me.myapp.domain.Person@398r4d99-looking values as <option>s. This is obviously Grails not deserializing my Person instances into pretty print form.

I want peoples' first and last names to appear as the select options. Hence, if one of the Person instances in the people list is:

Person smeeb = new Person(firstName: "Smeeb", lastNname: "McGuillocuty")

Then I would expect "Smeeb McGuillocuty" as a select option in the final HTML. How can I accomplish this?


Solution

  • Add the following method to your Person class:

    @Override public String toString() {
        "$firstName $lastName"
    }
    

    And, somewhat unrelated to the actual question, you may have to add an identifier to your option rows to uniquely identify the person. Assuming the Person class has an id property:

    <g:select name="people" from="${people}" optionKey="id" />
    

    so that you get the following HTML:

    <select name="people" id="people">
        <option value="123">Smeeb McGuillocuty</option>
        :
    

    Useful link to official doc: http://grails.org/doc/latest/ref/Tags/select.html: "..The default behaviour is to call toString() on each element in the from attribute.."