user82302124
user82302124

Reputation: 1143

OptionValue in Grails Select with list of domain objects

I've done some research on how to display a dropdown with an optional value. Currently, I have a list of domain objects (people) in a dropdown. They display with "First name last name".

I want to change the way the names are displayed in a selection. Looking at the g:select API, I see I can use optionValue and optionKey. I've tried, but got nowhere. So here is my current code:

<g:select id="allPeople" name="allPeople" from="${dropdown}" />

I want the output to be "Last, First". I've tried this:

<g:select id="allPeople" optionValue="${it?.last},${it?.first}" from="${dropdown}" name="allPeople" value="" >

Upvotes: 1

Views: 1776

Answers (2)

doelleri
doelleri

Reputation: 19682

A nice way to do it is to add a transient getter on your domain, then use that for the optionValue.

class Person {
    String first
    String last

    static transients = ['lastFirst']

    String getLastFirst() {
        "$last, $first"
    }
}

then

<g:select name="allPeople" optionValue="${it.lastFirst}" from="${dropdown}"/>

Upvotes: 4

Mr. Cat
Mr. Cat

Reputation: 3552

Try like this:

optionValue="${{it?.last+', '+it.first}}"

This mean that you pass a closure that builds what you need.

Upvotes: 2

Related Questions