Creating select tag with optgroup in Grails
Hi,
In one of my projects i needed to create a select-input tag with OPTGROUP options.
I searched a lot about it and found that g:select tag do not support OPTGROUP
So to solve this problem, i created a simple optgroup tag using Html and grails taglib.
I created a Map for the values to be used in the select tag and pass it to the test.gsp page from the controller.
Say Map dataMap=[“Car”:[“Car A”,”Car B”,”Car C”],”Truck”:[“Truck A”,”Truck B”]]
I put the tag in test.gsp where i want to display the select dropdown
In my TestTaglib.groovy, i defined the tag as
class TestTagLib {
static namespace = 'test'
def optGroup = {attrs ->
Map dataMap = attrs['dataMap']
out << g.render(template: 'layouts/optSelect', model: [dataMap:dataMap])
}
}
I created a template "_optSelect.gsp" under the layouts folder
This generated the required SELECT dropdown with OPTGROUP and solved the problem.
Hope it helps.
Regards:-
Vishal Sahu
vishal@intelligrape.com
The html tags used in my comment got corrupted. Please check if you can publish them.
Thanks a lot Vishal. This Taglib made my day.. Morevover, I have added the support for value to it through following implementation.
Suppose, Map dataMap=[“Car”:[“Car A”,”Car B”,”Car C”],”Truck”:[“Truck A”,”Truck B”]]
and Map valueCodes = [‘Car A’:10, ‘Car B’: 20, ‘Car C’: 30, ‘Truck A’:100, ‘Truck B’: 110]
Usage:
TagLib Definition:
def optGroup = {attrs ->
Map dataMap = attrs[‘dataMap’]
Map valueCodes = attrs[‘valueCodes’]
out << g.render(template: '/layouts/optSelect', model: [dataMap: dataMap, valueCodes: valueCodes])
}
Template definition in _optSelect.gsp:
(Select One)
${value}
Thanks again for sharing it.