Fustigador
Fustigador

Reputation: 6459

How to know which checkbox (es) is/are selected

I have this result from the DataBase. The number of result can be one, more than one, or none at all. For every register returned, a table is created, and inside one column a checkbox is displayed. In the view, I need to know which one of the checkboxes are checked, so I can pass the content of another column of the table to the controller, to be processed. It's like "Database returns me a list of people, and I want to send an email to some of them, not all of them. I select the checkbox, look for the "email" column and if the checkbox of that person is checked, the email is sent".

Is there any (preferably, easy) way to achieve that?

Thank you.

Upvotes: 0

Views: 144

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122374

If you give all your checkboxes the same name, but distinct values:

<g:checkBox name="sendTo" value="${firstPerson.id}" checked="${false}"/>
....
<g:checkBox name="sendTo" value="${secondPerson.id}" checked="${false}"/>

then in the controller you can use

params.list("sendTo").each { personId ->
  def person = Person.get(personId)
  // send email to this person
}

params.list() is a handy tool to know about when dealing with potentially multi-valued parameters. A standard params.sendTo would give you null if no checkboxes were selected, a String if one is selected, and a List if two or more are selected. Using params.list("sendTo") will always give you a List (with zero, one or more than one element as appropriate).

Upvotes: 2

Related Questions