I've problem when saving data with hasMany association. There are two tables like bellow. Now When I save it , it is saving data only services table, but it is not saving to service_times table. Also I have given here template and controller code. Can any one suggest me, how can I solve this issue.
1) services table:
id | id | ...
1 | name | ...
2) service_times table
id | id | ...
1 | service_id | ...
2 | star_time | (type= time)
3 | end_time | (type= time)
TEMPLATE FORM:
<?= $this->Form->create($service) ?>
<fieldset>
<legend><?= __('Add Service') ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('ServiceTimes.start_time');
echo $this->Form->input('ServiceTimes.end_time');
echo $this->Form->input('description');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
SERVICE CONTROLLER
public function add(){
$service = $this->Services->newEntity($this->request->data, [
'associated' => ['ServiceTimes']
]);
if ($this->request->is('post')) {
if ($this->Services->save($service, ['associated' => ['ServiceTimes']])) {
pr($this->request->data);exit;
$this->Flash->success(__('The service has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The service could not be saved. Please, try again.'));
}
}
//}
$this->set(compact('service'));
$this->set('_serialize', ['service']);
$this->viewBuilder()->theme('ThemeAdmin');
}
I am thinking that a smart solution would be to create a different entity for service_times table and include a small form for that table inside this one where you save only those two attributes. That should solve the "save" part of the problem.
Finally I have solve it by following way:
my CTP file like
<?= $this->Form->create($service) ?>
<fieldset>
<legend><?= __('Add Service') ?></legend>
<?php
echo $this->Form->input('name');
echo $this->Form->input('serviceTimes.start_time');
echo $this->Form->input('serviceTimes.end_time');
echo $this->Form->input('description');
?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
Controller function
public function add()
{
$service = $this->Services->newEntity();
if ($this->request->is('post')) {
$service = $this->Services->patchEntity($service, $this->request->data);
if ($this->Services->save($service)) {
// Last inserted service id
$service_id = $service->id;
$serviceTime = $this->Services->ServiceTimes->newEntity();
$serviceTime->service_id = $service_id;
$serviceTime->start_time = $this->request->data['serviceTimes']['start_time'];
$serviceTime->end_time = $this->request->data['serviceTimes']['end_time'];
if ($this->Services->ServiceTimes->save($serviceTime)) {
$this->Flash->success(__('The service has been saved.'));
return $this->redirect(['action' => 'index']);
}
} else {
$this->Flash->error(__('The service could not be saved. Please, try again.'));
}
}
$this->set(compact('service'));
$this->set('_serialize', ['service']);
$this->viewBuilder()->theme('ThemeAdmin');
}