Grails bindData to collections

24 / Oct / 2011 by Mohd Farid 0 comments

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:
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.brand,, car.2.brand ….. So, when I did a I get a Map like this:
1: [name:’carA’, brand:’brand1′]
2: [name:’carB’, brand:’brand2′]
3: [name:’carC’, brand:’brand2′]’carA’

def carParams = {it instanceof GrailsParameterMap}
List<Car> carList = carParams.collect {
def car = new Car()
bindData(car, it)

So, we have a list of Car objects out from the params.

Hope this helps.

-Mohd Farid-


Leave a Reply

Your email address will not be published. Required fields are marked *