Daniel
Daniel

Reputation: 905

How can I map values of an array into command objects using Grails?

normally I use command objects to work with submitted values. But if multiple values of the same property are submitted via AJAX (using jQuery) I was not able to use command objects.

In my GUI the user can click on checkboxes to mark some objects. Let's assume the name of the checkboxes is provider, i.e.

<input type=checkbox name=provider value=1>
<input type=checkbox name=provider value=2>
and so on...

When the clicked values are submitted via AJAX, in the Grails controller these values are in an map:

params.'provider[]'

where the key is provider[] and the value is an array of Strings if multiple checkboxes are clicked, otherwise it's just a String.

The problem is, that I can not create a command object with a property named provider[]. What I tried was:

class MyCommand {
    Long[] provider
    // or
    List<Long> provider
}

but that didn't work.

So, my question is, how can I use a command object in this case? I want Grails to do the mapping, I do not want to do the mapping myself.

I am using Grails 2.3.11.

Thanks in advance, best regards,

Daniel

Upvotes: 1

Views: 651

Answers (1)

MKB
MKB

Reputation: 7619

To use command object, change your check box name to provider[index]

<input type="checkbox" name="provider[0]" value=1>
<input type="checkbox" name="provider[1]" value=2>
and so on...

and change your command object --

import org.apache.commons.collections.FactoryUtils
import org.apache.commons.collections.ListUtils

class MyCommand {
    List<Provider> provider = ListUtils.lazyList([], FactoryUtils.instantiateFactory(Provider))
}

Upvotes: 0

Related Questions