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-']"/>
Author by
OemerA
Updated on June 11, 2022Comments
-
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 over 14 yearsFirst: 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 over 14 yearsIt'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 over 14 yearsBTW,
age ?: 20
is short forage ? age : 20
, which is short forif(age != null) age; else 20;
-
leebutts over 14 years? and ?: use groovy truth which means 0, empty string, empty list, empty map are all false as well...