On an edit page for the model Test I want to be able to update the "Questions.order" field on all of it's associated (by hasMany) questions from the same form.
I've ready the Cake book chapter on saveMany()/saveAll() in the book, and I'm using the Model.0.field syntax
but I can't figure out how to tell CakePHP which record to corresponds to which input. Should the #
in Model.#.field
correspond to the question's id field? Here's what I'm currently doing:
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 submits and appears to save, but the updated order
values do not correspond to the right 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() );
}
CakePHP associates all fields with the same 'index' to be a single 'record' in your database. The 'index' (i.e. the 0
in Foo.0.id
) does not have any relation to the 'id' of the record, it's just a number.
For example;
Foo.0.id = 123
Foo.0.name = 'hello';
Foo.1.id = 124
Foo.1.name = 'world';
As mentioned in the start of my answer, the index itself does not matter, this code will do exactly the same:
Foo.12345.id = 123
Foo.12345.name = 'hello';
Foo.54321.id = 124
Foo.54321.name = 'world';
As long as fields of the same record have the same 'index', CakePHP will understand that they belong 'together'.
When submitting this data and saving it using;
$this->Foo->saveMany($this->data['Foo']); // Just $this->data will probably work as well
CakePHP update two rows via the Foo
model;
table 'foos';
id name
------------------------
123 hello
124 world
Your code seems to use the same 'id' ($qset['Qset']['id']
) for each row, which is probably not the right ID to update those records
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);
Considering there are still people looking for this answer in 2014 You must use in the
View: /* (considering the $n counter)*/
$this->input('Question.'.$n.'.order');
$this->input('Question.'.$n.'.id');
Controller: $this->Question->updateAll->($this->request->data['Question']);
来源:https://stackoverflow.com/questions/16134085/cakephp-how-to-update-multiple-records-at-the-same-time-with-the-form-helper