CakePHP: How to Update Multiple Entries at Once Using a Form Helper

On the editing page for a test test of the model, I want to update the field "Questions. Size" on all questions related to it (by hasMany) from the same form.

I prepared the chapter of the cake book on saveMany () / saveAll () in the book, and I use Model.0.field syntax but I cannot figure out how to tell CakePHP which record corresponds to which entry. Should # in Model.#.field match the id field of the question? Here is what I am doing now:

  echo $this->Form->create( 'Question', array('action'=>'order')); $n = 0; foreach ($questions_array as $question) : ?> <?php echo $this->Form->input('Question.'.$n.'.order' ); ?> <?php echo $this->Form->input('Question.'.$n.'.id', array('type'=>'hidden', 'value'=>$question['Question']['id']) ); ?> <input type="submit" value="Save" /> ... $n++; endforeach; $this->Question->Form->end(); 

The form is submitted and appears for saving, but the updated order values ​​do not match the correct question records. What am I doing wrong?

Update

Here is the order action in my controller:

 public function admin_order() { $data = $this->request->data; $this->Question->saveAll($data['Question']); $this->Session->setFlash( "Order saved."); $this->redirect( $this->referer() ); } 
+4
source share
2 answers

CakePHP associates all fields with the same “index” as a single “record” in your database. The "index" (i.e. 0 in Foo.0.id ) has nothing to do with the "id" of the entry, it's just a number.

For instance:

 Foo.0.id = 123 Foo.0.name = 'hello'; Foo.1.id = 124 Foo.1.name = 'world'; 

As mentioned at the beginning of my answer, the index itself does not matter, this code will do the same:

 Foo.12345.id = 123 Foo.12345.name = 'hello'; Foo.54321.id = 124 Foo.54321.name = 'world'; 

As long as the fields of the same record have the same “index”, CakePHP will understand that they belong “together”.

When sending this data and storing it with;

 $this->Foo->saveMany($this->data['Foo']); // Just $this->data will probably work as well 

CakePHP updates two lines using the Foo model;

table 'foos';

 id name ------------------------ 123 hello 124 world 

Your code seems to use the same identifier ( $qset['Qset']['id'] ) for each line, which is probably not the correct ID to update these entries

+4
source
 As we can see at CakePHP Book, the instruction is: // Create: id isn't set or is null $this->Recipe->create(); $this->Recipe->save($this->request->data); // **Update**: id is set to a numerical value $this->Recipe->id = 2; $this->Recipe->save($this->request->data); 

Given that there are still people who are looking for this answer in 2014, you should use the View : / * (taking into account the counter $ n) * /
$ this-> input ('Question.'. $ n. '. order'); $ This-> input ('Question.' $ P .. 'Identifier.');
Controller : $ this-> Question-> updateAll → ($ this-> request-> data ['Question']);

0
source

All Articles