Search code examples
grailsgsp

conditions inside g:select gsp tag


I am using g:select and wishes to put a default selected value. However when default value is null it should display a 'Please select one'. However, I cannot seem to work it out.

Code is below:

This is the Address object - options contained in a drop down

Address
    Long id
    String name
    Sheriff sheriff
    String phaseCode

ListOfSheriffs is a list of sheriffs-contains list of Sheriff object

Sheriff
    Long id
    String name
    //other property here

defaultSheriff is the default sheriff of an Address

The below code is one on my gsp

<g:select optionKey = "id" 
          optionValue = "${{sheriff.name +' '+sheriff.id}}"  
          name="sheriff.name"
          from="${ListOfSheriffs}"
          value="${(defaultSheriff == null) ? 'Please select one' : defaultSheriff}" />

However, wether defaultSheriff is null 'Please select one' wont display, the page only displays the first sheriff from the ListOfSheriffs.

I got this solution from here . And not so sure what I left out.

Also, I tried using noSelection based on what I've read on docs. However, the result is, the default selected value on dropdown list on the page is always 'Please select one' even though the defaultSheriff is not null

<g:select optionKey = "id" 
          optionValue = "${{sheriff.name +' '+sheriff.id}}"  
          name="sheriff.name"
          from="${ListOfSheriffs}"
          value="${defaultSheriff}"
          noSelection="[null:'Please select one']" />

If something is not clear with what I have provided, feel free to point it add, I'll be happy to detail it. thanks


Solution

  • I would say that you need smth like this

    <g:select optionKey = "id" 
              optionValue = "${{it.name +' '+ it.id}}"  
              name="sheriff.name"
              from="${ListOfSheriffs}"
              value="${sheriff?.id ?: defaultSheriff?.id}"
              noSelection="['':'Please select one']" />