Search code examples
selectgrailspluginsfieldrelation

How to customise select tag in Grails


I have this hasMany relation, between a client and a product. When I generate the views and controllers, in the create view of the product I can chose a client. By default Grails displays a select containing only the id of the clients. How can I change that? For example I want to show only the name of the client instead of the id.

I'm using Grails 3.3, Here is the domain code:

client.groovy:

class client {
    String FirstName
    String LastName

    static hasMany = [products: Product]
}

product.groovy:

class product {
    String Name
    int Price
    Client c

    static belongsTo = Client
}

Solution

  • You can customize how the select looks like by specifying optionKey and optionValue attributes:

    <g:select from="${Client.list()}" name="client" optionKey="FirstName" optionValue="id" />
    

    See the ref doc for details.

    If you need to do something fancier, like show first AND last name, then you could pre-process the list a bit:

    <g:select from="${Client.list().collect{ [ id:it.id, name:it.firstName + ' ' + it.lastName ] }}" name="client" optionKey="name" optionValue="id" />