Creating select tag with optgroup in Grails « Intelligrape Groovy & Grails Blogs

Creating select tag with optgroup in Grails

Posted by Vishal Sahu

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

 
         <test:optGroup name = "data" dataMap="${dataMap}" />

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

 
<select name="mainList">
    <optgroup label="--"><option value="">(Select One)</option></optgroup>
    <g:each in="${dataMap}" var="data">
        <optgroup label="${data.key}">
            <g:each in="${data.value}" var="value">
                <option value="${value}">${value}</option>
            </g:each>
        </optgroup>
    </g:each>
</select>

This generated the required SELECT dropdown with OPTGROUP and solved the problem.

Hope it helps.

Regards:-

Vishal Sahu
vishal@intelligrape.com

  • Share/Bookmark
This entry was posted on August 10th, 2010 at 9:49 pm and is filed under Grails, Groovy, HTML-UI-CSS, Javascript/Ajax/JQuery . You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site.

2 Responses to “Creating select tag with optgroup in Grails”

  1. Farid says:

    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.

  2. Farid says:

    The html tags used in my comment got corrupted. Please check if you can publish them.

Leave a Reply