Updating multiple models with a single form

Hi guys, please help me with this. I want to Update two data tables through one form, but the data is updated in only one table and inserted into the second table instead of updating the existing record. Here is my code -

View file:

echo $this->Form->create('Question'); echo $this->Form->input('question'); foreach (range(0,2) as $index) { echo $this->Form->input('Option.'.$index.'.poll_options'); } echo $this->Form->input('id',array('type'=>'hidden')); echo $this->Form->end('Save Poll'); 

Controller File:

 $data=$this->Question->findById($id); if($this->request->is('post') || $this->request->is('put')) { if($this->Question->saveAll($this->request->data)) { $this->Session->setFlash('Question has been updated'); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash('Question has not been updated'); } } if(!$this->request->data) { $this->request->data=$data; } 
+1
source share
1 answer

Controller code designation.

 <?php $data = $this->Question->findById($id); 

above will return the whole question and the associated array of answers, as shown below.

 Array ( [Question] => Array ( [id] => 121 [name] => Gwoo the Kungwoo [created] => 2007-05-01 10:31:01 ) [Option] => Array ( [0] => Array ( [id] => 123 [quesion_id] => 121 [body] => The Kungwooness is not so Gwooish [created] => 2006-05-01 10:31:01 ) [1] => Array ( [id] => 124 [quesion_id] => 121 [title] => More on Gwoo [created] => 2006-05-01 10:41:01 ) ) ) 

Now all we need to do is build our form (do something very simple):

 echo $form->create('Question', array('action' => 'edit')); foreach($this->data['Option'] as $key => $value) { echo $form->input('Option.'.$key.'.name'); echo $form->input('Option.'.$key.'.id'); } echo $form->end('Save All'); 

It is built from our $this->data array and follows exactly in the correct format, which allows the saveAll() method to work correctly.

Now publish it and see, I'm sure it will work now.

Greetings.

0
source

All Articles