I use cakephp v3. I have an issue when saving associated entities that already exist in the database. For example I have an equipment which belongs to a constructor. When I edit an equipement by sending equipement data containing constructor data, the constructor is always detected as new even if I pass the constructor id.
Sended data to PUT http://api_url/equipment/:id
An equipement containing constructor data
Array
(
// ...
[constructor] => Array
(
[id] => 105
[corporate_name] => test
)
// ...
)
Model/Entity/Constructor.php
All fields are accessibles (so the id field should be correctly read)
class Constructor extends Entity
{
// ...
protected $_accessible = [
'id' => true,
'*' => true
];
// ...
}
Controller/EquipmentController.php
Build the equipment entity before saving
public function edit($id) {
// ...
$equipment = $this->Equipments->get($id);
$equipment = $this->patchEntity($equipment, $data, ['associated' => ['Constructors']]);
// ...
}
Display the entity
When I debug the entity before saving, the constructor ‘id’ field is marked as dirty and the constructor entity is marked as new.
// print_r($equipement)
App\Model\Entity\Equipment Object
(
[id] => 2
[constructor] => App\Model\Entity\Constructor Object
(
[id] => 105
[corporate_name] => test
[[new]] => 1
[[accessible]] => Array
(
[id] => 1
[*] => 1
)
[[dirty]] => Array
(
[id] => 1
[corporate_name] => 1
)
[[original]] => Array
(
)
[[virtual]] => Array
(
)
[[errors]] => Array
(
)
[[repository]] => Constructors
)
)
But if I get the equipment like this :
Controller/EquipmentController.php
The equipment now explicitly contains the constructor data before patching
public function edit($id) {
// ...
$equipment = $this->Equipments->get($id, ['contain' => ['Constructors']]);
$equipment = $this->patchEntity($equipment, $data, ['associated' => ['Constructors']]);
// ...
}
Display the entity
The constructor is not detected as new anymore
// print_r($equipement)
App\Model\Entity\Equipment Object
(
[id] => 2
[constructor] => App\Model\Entity\Society Object
(
[id] => 105
[corporate_name] => test
[[new]] =>
[[accessible]] => Array
(
[id] => 1
[*] => 1
)
[[dirty]] => Array
(
)
[[original]] => Array
(
)
[[virtual]] => Array
(
)
[[errors]] => Array
(
)
[[repository]] => Constructors
)
)
Is this the normal behavior ? Do I need to load all associations with contain before patching the equipement entity ?
By the way I have the same issue when I create an new equipment with existing contractor which is very frustrating because I can’t load asociated data like in an edition. So existing data are validated like in creation mode and not in edition mode.
Thanks