Helper tag for creating HTML selects.


// create a select from a range
<g:select name="user.age" from="${18..65}" value="${age}"
          noSelection="['':'-Choose your age-']"/>

// use a no selection with a nullable Object property (use 'null' as key) <g:select id="type" name='' value="${person?.type?.id}" noSelection="${['null':'Select One...']}" from='${PersonType.list()}' optionKey="id" optionValue="name"></g:select>

// create select from a list of companies // note the 'optionKey' is set to the id of each company element <g:select name="" from="${Company.list()}" value="${user?}" optionKey="id" />

// create select with internationalized labels (this is useful for small static lists and the inList constraint) // expected properties in // book.category.M=Mystery // book.category.T=Thriller // book.category.F=Fantasy <g:select name="book.category" from="${['M', 'T', 'F']}" valueMessagePrefix="book.category" />

Example as a method call in GSP only:




The optionKey and optionValue attribute of the <g:select> tag deserve special mention as these allow you to control what is displayed to the user within the resulting <select> tag and also the value which is submitted in a form submission. The default behaviour is to call toString() on each element in the from attribute, but for example if you had a list of Book domain classes this may not be useful behaviour.

As an example the following <g:select> uses the optionKey attribute to resolve the id property of each Book as the value of the value attribute in each <option> tag. It also uses the optionValue attribute of <g:select> to display the title property of each Book to the user:

<g:select optionKey="id" optionValue="title" name="book.title" from="${bookList}" />

If you require even more control over how each <option> element is presented to the user you can use a closure to apply a transformation within the optionValue attribute. As an example, the following code transforms each Book title to upper case:

<g:select optionKey="id" optionValue="${{it.title?.toUpperCase()}}" name="book.title" from="${bookList}" />


Show Source