I cant save (update) associated form data for model AvailabilityForTutors that has a hasMany relationship with the Primary model. I used checkboxes to update some options for the 'AvailabilityForTutors. not_available' field. I added in id's but that made no difference. The updated 'AvailabilityForTutors. not_available' field is not being updated in the database. I dont get an error and the primary model data for the Tutor does save.
I checked the docs and past posts for this straightforward task and I cant get it. I am doing something wrong.
//controller
$tutor = $this->Tutors->get($id, [
'contain' => ['AvailabilityForTutors']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
debug($this->request->data);
$tutor = $this->Tutors->patchEntity($tutor, $this->request->data,['associated' => ['AvailabilityForTutors'],'validate' => false ] );
if ($this->Tutors->save($tutor)) {
$this->Flash->success(__('The tutor has been saved.'));
return $this->redirect(['action' => 'edittest2',$id]);
} else {
$this->Flash->error(__('The tutor could not be saved. Please, try again.'));
}
}
//view
<?php
echo $this->Form->hidden('id', ['value'=>$id]);
echo $this->Form->input('first_name',['label' => 'Tutor FirstName']);
echo $this->Form->input('last_name',['label' => 'Tutor LastName']);
foreach ($tutor->availability_for_tutors as $key => $item) {
echo $this->Form->hidden('AvailabilityForTutors.'.$key.'.id', ['value'=>$item->id]);
echo $this->Form->input('AvailabilityForTutors.'.$key.'.not_available', ['label'=>$item->weekday,
'checked'=> $item->not_available,'type'=>'checkbox']);
}
model tutor//
$this->hasMany('AvailabilityForTutors', [
'foreignKey' => 'tutor_id'
]);
posted data which is correct
'id' => '12',
'first_name' => 'fred',
'last_name' => 'Tow',
'AvailabilityForTutors' => [
(int) 0 => [
'id' => '36',
'not_available' => '1'
],
(int) 1 => [
'id' => '37',
'not_available' => '0'
],
(int) 2 => [
'id' => '38',
'not_available' => '0'
],
http://stackoverflow.com/questions/27398100/cakephp-3-0-cant-save-hasmany-associated-data
http://book.cakephp.org/3.0/en/orm/saving-data.html#saving-with-associations
http://stackoverflow.com/questions/35018335/update-a-hasmany-records
UPDATE- debug patched data object(App\Model\Entity\Tutor) {
'id' => (int) 12,
'tutor_inactive' => false,
'first_name' => 'fred2',
'last_name' => 'Tow2',
'availability_for_tutors' => [
(int) 0 => object(App\Model\Entity\AvailabilityForTutor) {
'id' => (int) 36,
'not_available' => false,
....
],
'AvailabilityForTutors' => [
(int) 0 => [
'id' => '36',
'not_available' => '1'
//see not_available is different from patched data output