Question

I have a page with a list of books, and every row has a checkbox. (I'm using cakephp 1.2).
I want to let the user to save multiple books.
For now I have this checkbox in my view (in a cycle, where I get the list of all books):

<?php echo $form->input('salva', array('value' => $cdBiblio['CdBiblio']['codiceBiblio'], 'label' => '', 'type' => 'checkbox')); ?>

This form:
<?php echo $form->create('cd_biblios', array('action' => 'save')); ?>

And this button:

<?php echo $form->end('Add All');?>

In the controller, I have something like this for debugging:

    debug($this->data);
    foreach($this->data['cd_biblios']['salva'] as $item) {
        debug($item);
    }

But it's not working.
I noticed that it takes only the last book id of the list with debug($this->data); and if I check more than 1 book, it show 0 or the last book id, for example:

Array (
[cd_biblios] => Array
    (
        [salva] => 0
    ) )


SOLVED:
In the view I use Danial's code.

In the controller I use this code:

if(!empty($this->data)) {               
        $item=$this->data;
        debug($item);
        $dim=count($item['Model']['field']);
        $i=0;
        for ($i=0;$i<$dim;$i++)         
            if ($item['Model']['field'][$i]!=0)
            {
                $data = $this->Session->read('libri');
                $data[] = $item['Model']['field'][$i];
                $this->Session->write('libri', $data);
            }
        $this->Session->setFlash(__('I libri sono stati salvati', true));
        $this->redirect($this->referer());
    }
Was it helpful?

Solution

In View:

<?php 
foreach($array as $each_elem) { 
echo $form->checkbox(
        'Model.field', 
        array(
              'id'=>'abcd_'.$each_elem['Model']['id'],
              'value' => $each_elem['Model']['id'],
              'hiddenField' => false,
              'name' => 'data[Model][field][]',
              'label' => false,
              'div' => false,
        ));
}
?>

On submit the form, you will get the checked values in controller in $this->request->data

OTHER TIPS

You have a conception problem.

Your checkboxes must be inside a form, because they are input tags. So, to send those values to the controller you'll need to submit that form. In your code, i see that "Add All" is just a link. And a link won't submit the form.

Change your link to a button :)

Hope this helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top