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
inFoo.0.id
) does not have any relation to the 'id' of the record, it's just a number.For example;
As mentioned in the start of my answer, the index itself does not matter, this code will do exactly the same:
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;
CakePHP update two rows via the
Foo
model;table 'foos';
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