act:ualise | technology

05 Dec, 2008

handling multiple object instances within gsp forms

Posted by: j pimmel In: development|grails

I needed to handle multiple dynamic instances of the same type of validating object in a form within Grails.

Having searched Google and the lists for an out-of-the-box way, or plugin, or pending bug-fix, I found nothing that already provided this capability so ended up writing my own utility.

Given

Map params = [
    'chart1.size': '10',  // could also be 'chart_1.size' or 'chart_id1.size'
    'chart1.height': '100',
    'chart1.width': '200',
    'chart1.name': 'foo',
    'chart2.size': '9',
    'chart2.height': '109',
    'chart2.width': '209',
    'chart2.name': 'blah'
]

The utility function broke the flat structure of the submission into a map of maps, keyed on the id.

static def multiInstanceFormElementsMap = { String groupKey, Set entries ->
    Map perInstanceParams = [:]
    entries.each {
        def matcher = (it.key =~ /${groupKey}([\d+]).(\w+)/);
        if (matcher.matches()) {
            def instanceId = matcher[0][1]
            if (!perInstanceParams[instanceId]) perInstanceParams[instanceId] = [:]
            perInstanceParams[instanceId] [matcher[0][2]] = it.value
        }
    }
    return perInstanceParams
}

Usage:

Map result = ControllerUtil.multiInstanceFormElementsMap('chart',  params.entrySet())

No Responses to "handling multiple object instances within gsp forms"

Comment Form

About

act:ualise | technical blog

notes, observations and obssessions on software quality, agile software development, testing and grails


part of the EnergizedWork experiment