Search code examples
phpcakephphas-manyincrementupdate-all

CakePHP increment value


My problem looks as follows:

I want to make a vote app where People can choose one or more Events(like Doodle). For this I have set up a function called vote. In the View you can choose the Events using checkboxes. The Models are Poll and Groupevent. A Poll has Many Groupevents. My Problem is when I call updateAll(), all values of the associated Groupevents are incremented.

Here is my code:

View:

echo $this->Form->create('Poll', array('action' => 'vote'));

for($i=0; $i<$count; $i++){
    echo $this->Form->input('Groupevent.'.$i.'.votes', array('type'=>'checkbox', 
        'label'=>$this->Groupevent['startTime']));
    echo $this->Form->input('Groupevent.'.$i.'.id', array('type'=>'hidden'));
}   
echo $this->Form->input('id', array('type' => 'hidden'));   
echo $this->Form->end('vote');

Controller function:

function vote($id=null){
    $this->Poll->id = $id;
    if ($this->request->is('get')) {
        $this->request->data = $this->Poll->read();
        $this->set('count', $this->Poll->Groupevent->find('count',
            array('conditions'=>array('Groupevent.poll_id'=>$this->Poll->id))));                                               
    } else {
        unset($this->Poll->Groupevent->validate['poll_id']);            
        if ($this->Poll->Groupevent->updateAll(
              array('Groupevent.votes'=>'Groupevent.votes+1'), 
              array('Groupevent.poll_id'=>$this->Poll->id))) 
        {                            
            $this->Session->setFlash('Your poll has been updated.');
            $this->redirect(array('action' => 'edit', $id));
        } else {
            $this->Session->setFlash('Unable to update your poll.');
        }
    }
}

How can I make it work, so that just the checked values get incremented?

thanks in advance

Edit:

Thanks for the suggest with the array. But i've tried certain ways it wont work. How do I create this Array?


Solution

  • It looks like you are running an updateAll query for all Groupevents assigned to a selected Poll:

    if ($this->Poll->Groupevent->updateAll(
                  array('Groupevent.votes'=>'Groupevent.votes+1'), 
                  array('Groupevent.poll_id'=>$this->Poll->id))) 
            { 
    ...
    

    You need to create an array with the ID's of checked Groupevents and add a condition that will limit the update only to selected events:

    if ($this->Poll->Groupevent->updateAll(
                  array('Groupevent.votes'=>'Groupevent.votes+1'),
                  array('Groupevent.id IN' => $selectedEventsIds),
                  array('Groupevent.poll_id'=>$this->Poll->id))) 
            {
    ...