I studied the posts here, also the documentation in:
- https://book.cakephp.org/4/en/views/helpers/form.html#creating-inputs-for-associated-data
- https://book.cakephp.org/4/en/orm/saving-data.html#saving-hasmany-associations
But unfortunately I am apparently to stupid to save data into an associated table. I have this simple example:
CREATE TABLE `fathers` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`intval` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
INSERT INTO `fathers` (`id`, `name`, `intval`) VALUES (1, 'f1', 1);
CREATE TABLE `sons` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`father_id` int(11) NOT NULL,
`name` varchar(25) NOT NULL,
`floatval` float NOT NULL,
PRIMARY KEY (`id`),
KEY `father_id` (`father_id`),
CONSTRAINT `sons_ibfk_1` FOREIGN KEY (`father_id`) REFERENCES `fathers` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
I want to display in the form for fathers
additionally the associated fields of sons
. This is how I do according to the above link from the official documentation:
echo $this->Form->control('name');
echo $this->Form->control('intval');
echo $this->Form->control('sons.0.id');
echo $this->Form->control('sons.0.name');
echo $this->Form->control('sons.0.intval');
echo $this->Form->control('sons.1.id');
echo $this->Form->control('sons.1.name');
echo $this->Form->control('sons.1.intval');
I baked the Controller and model by the cake binary and there isn’t any error message regarding the model so I would say they are correct.
In the fathers
Controller in the add()
& edit()
functions I have - again according to the two above documentations - this code:
if ($this->request->is(['patch', 'post', 'put'])) {
$data = $this->request->getData();
$father = $this->Fathers->newEntity($data, [ 'associated' => ['Sons'] ]);
$father->setDirty('Sons', TRUE);
if ($this->Fathers->save($father)) {
$this->Flash->success(__('The father has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The father could not be saved. Please, try again.'));
This code doesn’t save the records and I get the flash error that it couldn’t be saved.
What am I doing wrong? Thx