Hjem   |   Kontakt   |   Sitemap
Hvem er vi Hvad kan vi Vores kunder Ledige stillinger Kontakt os Blog

Dependent dropdowns in Grails

Published Friday, September 18th, 2009 by AN

It does really seem to be a very common problem with the dependend or chained drop-downs. At least it was one of the first problems I faced in the Grails app I’m working on now.

The solution is not really more or less elegant than the one for Seam and Richfaces. I followed the guide on Grails.org but decided to make the solution a bit more general. So I pass the name of the select-element-to-update as a string to the update function. This way I can also put the function in a separate file for inclusion (updateselect.js).

function updateSelect(e, elemId) {
// The response comes back as a bunch-o-JSON
var values = eval("(" + e.responseText + ")") // evaluate JSON

if (values) {
updateSelectFromJSON(values, elemId);
}
}

function updateSelectFromJSON(values, elemId) {
var rselect = document.getElementById(elemId)
// 	Clear all previous options
rselect.options.length = 0

// Rebuild the select
for (var i=0; i < values.length; i++) {
var opt = document.createElement('option');
opt.text = values[i].name
opt.value = values[i].id
try {
rselect.add(opt, null) // standards compliant; doesn't work in IE
} catch(ex) {
rselect.add(opt) // IE only
}
}
}

Which is then called like this


...

<form>
optionKey="id" optionValue="name" name="country.name" id="country.name" from="${Country.list()}"
onchange="${remoteFunction(
controller:'country',
action:'ajaxGetCities',
params:''id=' + escape(this.value)',
onComplete:'''updateSelect(e, 'city')''')}"
>

</form>

One thing is missing from this solution, though. Unlike the solution on grails.org, the chained select is not updated based on the default value of the previous select. This can be fixed by inserting the following in the head element of the .gsp page.


function init() {
document.cityform['country.name'].onchange();
}
window.onload = init;

Leave a Reply

Creating, consuming and testing SOAP webservices on Grails

Friday, February 12th, 2010
We are currently making a backend system, that has its services exposed as webservices. Since ...

My first patch to Grails accepted

Monday, November 23rd, 2009
I recently wrote a patch for Grails to support dateCreated and lastUpdated when using mockDomain ...
 
© 2008 Code3 ApS  |  Rådmandsgade 45A, 1.  |  2200 København N  |  +45 7020 3383  |  kontakt@code3.dk