GSP g:select option default selection

13,061

The value attribute does exactly that. From the Grails documentation:

value (optional) - The current selected value that evaluates equals() to true for one of the elements in the from list.

So, if you want to select "20" if your age model variable is null, just do

<g:select name="user.age" from="${18..65}" value="${age ?: 20}"
      noSelection="['':'-Choose your age-']"/>
Share:
13,061
OemerA
Author by

OemerA

Updated on June 11, 2022

Comments

  • OemerA
    OemerA almost 2 years

    Is there any possibility to select a option field by default in a g:select tag?

    I only saw the "noSelection" parameter in the documentation.

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

    But I need a default selection from the data I received.

    For example 18..65 is my range and I want to select 20 as default selection.

    Is that possible or do I have to do this with javascript?

    Thank you

  • OemerA
    OemerA over 14 years
    First: thanks for your answer. Now I got it right. Your closure helped me out. So I just want to put 20 as default that means I need to put "20" in the value attribute without closure. With the closure "$(age?:20)" I got only "20" as default if age is not set.
  • Daniel Rinser
    Daniel Rinser over 14 years
    It's actually not a closure, but rather an EL expression. And yes, if you always want to select 20 (eg. if this is a create view), just set "20" as value. I'm not entirely sure, but maybe you will still have to place it in ${} for Grails to interpret it as an integer rather than a string (ie. value="${20}").
  • Daniel Rinser
    Daniel Rinser over 14 years
    BTW, age ?: 20 is short for age ? age : 20, which is short for if(age != null) age; else 20;
  • leebutts
    leebutts over 14 years
    ? and ?: use groovy truth which means 0, empty string, empty list, empty map are all false as well...