I'm having trouble modifying the logic for saving one of my associated table. The two tables are:
- Clients
- ClientMetadatas (storing the client's metadata with key/value pairs)
In the Clients Controller, the method edit(), classic, baked with cakephp, with the associated table in addition:
$client = $this->Clients->get($id, [
'contain' => ['ClientMetadatas']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$client = $this->Clients->patchEntity($client, $this->request->data);
if ($this->Clients->save($client, ['associated' => ['ClientMetadatas']])) {
$this->Flash->success(__('The client has been saved.'));
} else {
$this->Flash->error(__('The client could not be saved. Please, try again.'));
$this->response->statusCode(500);
$client=$client->errors();
}
}
$this->set(compact('client'));
$this->set('_serialize', ['client']);
An example of how I edit a client and its metadatas would be, calling '/clients/edit/clientid.json'
{
"firstname": "John",
"firstname": "Smith",
"client_metadatas":
[
{
"name": "test",
"value": "test"
}
]
}
Here's my problem: I'd like to verify if there is no metadata existing with this client_id and metadata's name. If it exists, I'd perform an update rather than an insert.
It seems that the ideal solution would be to do it in the Model directly.
I tried to use the callback methods:
- beforeSave(), but I wasn't able to modify the entity
- beforeFind(), but I wasn't able to modify the query
Any advice on how to properly do the verification and the switch between insert/update before saving the entity?
PS: I hope no information in missing. If it the case, don't hesitate, I'll add them...
Thank you !