Multiple checkboxes

One question that I’ve seen come up a few times is: “How do I handle multiple checkboxes in a form?”
The only trick here is the way you name your checkbox form element. Let’s consider an example where you’d like to select multiple messages (by using checkboxes) and then delete these messages in your controller.

Let’s say that in your controller you did a $messages = $this->Message->find… and you have set the resulting array for the view $this->set(‘messages’, $messages).
Now, in the view you will loop through all the $messages and construct a form by doing something like this:

[sourcecode language=’php’]

checkbox(‘Messages.id.[‘.$message[‘Message’][‘id’].’]’, array(‘value’ => $message[‘Message’][‘id’])); ?> link($message[‘Message’][‘subject’], ‘/messages/read/’.$message[‘Message’][‘id’]);?>


[/cc]

So your checkboxes will now be named Messages.id.[1], Messages.id.[2], Messages.id.[3]… and so on.

Now if you’d like to delete all selected messages, do this in your ‘deleteMsg’ action in the controller:

[sourcecode language=’php’]
data[‘Messages’] as $key => $value) {
if($value != 0) {
$this->Message->del($value);
}
}
[/cc]

 

Related Posts

%d bloggers like this: