Undocumented goodies of Grails - Part 1
Working with Grails you can often discover exciting features from time to time. And even better (or worse?), some of them are undocumented, which feels kind of like treasure hunting.
Lately I discovered this gem of feature which is left out of the latest documentation. You can use a closure with the <g:select> tag to fully customize the displayed values of your options list!
It works like this. For example you have a list of values indicating minutes, e.g. 15, 30, 60, 120, … You want to give the list to <g:select>, but you don’t want to simply display the bunch of numbers as-is because that’s ugly. You want the minute values to be displayed as “15 Minutes”, “30 Minutes”, “1 Hour”, “2 Hours”, etc.
How would you do this? Custom tag lib? It sure works, but definitely will cost you more than a one-liner. But using a closure to supply the formatting logics directly to <g:select>, this IS a one-liner!
<g:select from='${minutesList}' optionValue='${{it<60?("$it Minutes"):(it>60?("${it/60} Hours"):("${it/60} Hour"))}}' name='prettyList'/>
That’s it! The closure supplied to optionValue takes the List given by the “from” attribute, and iterates the List. Now your controller can take the raw minutes values while the front end displays human friendly minutes and hours reading.
By reading the <g:select> source code, you will see that the attribute “optionKey” can take a closure, too. What clever use of this can you think of now?
Update: I think part of the reason this is undocumented could be that this would encourage bad habits of littering the views with too much logic. So use it wisely. I recommend only using this for simple and clear one-liners.
Tags: Grails