Reputation: 3774
Let's say when you submit a form it sends a list of ids.
<form action="/process">
<input type="hidden" name="ids" value="4, 6, 10, 14, 20, 56" >
<input type="submit" value="Submit">
</form>
At the controller side
def process(EmailCommand cmd){
//now iterating over registrations after data binding
cmd.ids.each {
}
}
//Command Object
class EmailCommand {
List<Registration> ids
}
I want to bind all the ids passed to controller to the ids list in EmailCommand command object. How can i achieve it? I appreciate any help! Thanks!
Upvotes: 0
Views: 1058
Reputation: 3774
I could only get it to work after changing the command object to
class EmailCommand{
List<Registration> ids= ListUtils.lazyList([], { new Registration() } as Factory )
}
and view to the following as bassmartin suggested.
<g:hiddenField name="ids[0].id" value="1"></g:hiddenField>
<g:hiddenField name="ids[1].id" value="2"></g:hiddenField>
<g:hiddenField name="ids[2].id" value="3"></g:hiddenField>
<g:hiddenField name="ids[3].id" value="4"></g:hiddenField>
<g:hiddenField name="ids[4].id" value="5"></g:hiddenField>
<g:submitButton name="submit" value="submit"></g:submitButton>
I am wondering why empty list in command object doesn't work. Is this limitation of grails version 2.2?
Upvotes: 1
Reputation: 525
It would be something like
<form action="/process">
<input type="hidden" name="ids[0].id" value="4" >
<input type="hidden" name="ids[1].id" value="6" >
<input type="hidden" name="ids[2].id" value="10" >
<input type="hidden" name="ids[3].id" value="14" >
<input type="hidden" name="ids[4].id" value="20" >
<input type="hidden" name="ids[5].id" value="56" >
<input type="submit" value="Submit">
</form>
Or if you want something more dynamic :
<form action="/process">
<g:each in="[4, 6, 10, 14, 20, 56]" var="id" status="i">
<input type="hidden" name="ids[${i}]" value="${id}" >
</g:each>
<input type="submit" value="Submit">
</form>
Upvotes: 3
Reputation: 20699
You have 2 options here:
Straight forward -> trick with the split comma-separated String in the "setter":
class EmailCommand {
List<Registration> ids
void setIds( String val ){ ids = Registration.getAll( val.split( ', ' ) ) }
}
Correct -> use form params for that:
<form action="/process">
<g:each in="[4, 6, 10, 14, 20, 56]" var="id">
<input type="hidden" name="ids" value="${id}" >
</g:each>
<input type="submit" value="Submit">
</form>
and let grails do the binding.
Upvotes: 1