A good friend had problem recently with adding items to list opon first create in grails. The problem is how can you set the property of an item as position x in a list if it does not yet exist at that position. Well will with a little magic and grails we did this.
The answer is Lazylist and Lazymap implementations from the commons collection package. So we end up with this result.
import org.apache.commons.collections.Factory;
import org.apache.commons.collections.ListUtils;
public class Requirement {
String label;
List requirements =
new ListUtils.lazyList(new ArrayList(),{new Requirement()} as Factory)
static hasMany = [requirements:Requirement];
static constraints = {
label(blank:false);
}
}
This means in your create form page you can have an entry like this:
<g:textField name="requirements[${i}].label" value=""/>
When you create a Requirement object like this in the controller action.
Requirement r = new Requirement(params)
The new entries will be created in the collection and the label value on them set. The same thing can be done with LazyMap.
enjoy :)
1 comments:
Hi Peter,
Thanks for this evergreen post which I've referred to on more than one occasion. :)
I would like to point out a small typing error.
It should be ListUtils.lazyList instead of new ListUtils.lazyList
Post a Comment