Search code examples
grailsgrails-orm

how to format grails list in g:select


Here's a sample grails g:select to be rendered in a gsp:

<g:select name="user.company.id"
          from="${Company.list()}"
          value="${user?.company.id}"
          optionKey="id" />

And the HTML would look something like this:

<select id="user.company.id" name="user.company.id">
<option value="1">ABC Company</option>
<option value="2">XYZ Company</option>
</select>

So the company domain has entries for:

ABC Company
XYZ Company

I'm trying to format the text of each option, so the user would see:

Some text - ABC Company:
Some text - XYZ Company:

How can I format the output of Company.list() to include pre and post text for display in the view?


Solution

  • Use optionValue.

    <g:select name="user.company.id"
              from="${Company.list()}"
              value="${user?.company.id}"
              optionKey="id"
              optionValue="Some text - ${it.name}:" />
    

    provided name depicts the name of the Company (ideally the former case works if you have toString() implemented in Company to return the name by default)

    Further reading on optionValue.