I have no special talent. I'm only passionately curious - Albert Einstein
April 30, 2010
Binding Indexed Properties in Grails
Posted by Dave Malone
in Grails,
Spring,
Configuration,
Java,
Technology
Here's an example of how to bind indexed properties to a Grails (or Spring) domain or command object without having to hand roll the parameter parsing and binding. The domain object graph is simple, and based on a project I'm currently working on, but this method can be applied to any sized object graph.
class LeagueMembersCommand implements Serializable{
String[] types
String[] firstNames
String[] lastNames
String[] emails
Integer[] handicaps
static constraints = {
types(nullable:false)
firstNames(nullable:false)
lastNames(nullable:false)
emails(nullable:false)
handicaps(nullable:false)
}
}
Here is the relevant snippet from my league/create.gsp file:
<g:each var="i" in="${(0..< lmc?.types?.length)}">
<tr class="${(i % 2) == 0 ? 'odd' : 'even'}">
<td>${i + 1}</td>
<td><g:select name="types.${i}" from="${['Full Time', 'Sub']}"
value="${lmc?.types[i]}"/></td>
<td><g:textField name="firstNames.${i}" value="${lmc?.firstNames[i]}" /></td>
<td><g:textField name="firstNames.${i}" value="${lmc?.lastNames[i]}" /></td>
<td><g:textField name="emails.${i}" value="${lmc?.emails[i]}" /></td>
<td><g:textField name="handicaps.${i}" value="${lmc?.handicaps[i]}" /></td>
</tr>
</g:each>
The important thing to note here is that in order to have Grails or Spring bind indexed
properties to an Array or a List on your domain object, you must append a '.' and a
number representing the index to the end of the property name you want to bind to.
This example is very simple, and only uses String arrays on a simple Command object,
but you could easily apply this method to an object graph instead.
Comments are currently disabled