Catching "Integrity constraint violation" error
VARGA-Peter opened this issue · comments
I was studying the crud documentation and source code. Unfortunately the 'afterDelete' event isn't called in case of "Integrity constraint violation".
Instead, the CakePHP error handler is called with an error message like this:
SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (Database.active_sessions, CONSTRAINT active_sessions_ibfk_1 FOREIGN KEY (shop_id) REFERENCES shops (id))
Can you please give me an advise where to catch this error, which would be the proper event? I don't want to modify the original crud source file vendor/friendsofcake/crud/src/Action/DeleteAction.php
as my modifications are lost with the next crud update.
PS: You have in vendor/friendsofcake/crud/src/Action/DeleteAction.php
in line 25 a typo from copying:
Default settings for 'add' actions
I am convinced it should be 'delete'
instead of 'add'
.
Add a delete()
method to your controller and wrap the $this->Crud->execute()
call in a try catch block.
https://crud.readthedocs.io/en/latest/configuration.html#actions
Works! Thank you very much. May be in the documentation could be added an example for the delete()
method regarding the try/catch
block for database errors.
In the end the solution was very simple and logical. Somehow I have missed it.