Grails bindData to collections
Recently, I was stuck with a scenario where I was trying to bind a list of objects in my controller. While trying the way as suggested in the grails docs I was getting some weird IndexOutOfBoundException. Luckily I found a good solution on the grails mailing list: http://grails.1312388.n4.nabble.com/Databinding-Collection-of-non-domain-objects-tp3260578p3260856.html
Thanks to mkwhit for asking this and Dana for suggesting this solution.
There is a Car class in my src/groovy. There is a create.gsp that should create n number of cars at a time. The problem is to bind this data to a List of Car objects.
Here is how I got it done:
I ensured in my gsp that the car parameters are passed as car.1.name, car.1.brand, car.2.name, car.2.brand ….. So, when I did a params.car I get a Map like this:
[groovy]
1: [name:’carA’, brand:’brand1′]
2: [name:’carB’, brand:’brand2′]
3: [name:’carC’, brand:’brand2′]
1.name:’carA’
1.brand:’brand1′
2.name:’carB’
2.brand:’brand2′
3.name:’carC’
3.brand:’brand3′
[/groovy]
[groovy]
def carParams = params.car.values().findAll {it instanceof GrailsParameterMap}
List<Car> carList = carParams.collect {
def car = new Car()
bindData(car, it)
car
}[/groovy]
So, we have a list of Car objects out from the params.
Hope this helps.
-Mohd Farid-