tags:

views:

274

answers:

1

Hi guys,

is there any possiblity to select a option field by default in gsp 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 got.

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

+4  A: 

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-']"/>
Daniel Rinser
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.
OemerA
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
BTW, `age ?: 20` is short for `age ? age : 20`, which is short for `if(age != null) age; else 20;`
Daniel Rinser
? and ?: use groovy truth which means 0, empty string, empty list, empty map are all false as well...
leebutts