4

I want to prevent a node from being deleted while a delete operation is performed on it. For example in administration panel if user clicks "Delete" on the node, the node shouldn't be deleted if he is not an administrator. Permissions and user roles are not a problem for me, the problem is "stopping" delete operation.

I found hook_entity_predelete(), which is perfect, it runs exactly just before deleting the node, but I don't know how to stop delete operation. I want to do some things inside that hook and prevent deleting the node.

I saw also this issue: How do I prevent a Node from being deleted? with hook_node_access(), but it is not working as I need.

hook_entity_delete() is also not ok, because This hook runs once the entity has been deleted from the storage. I need to prevent it.

Thanks for your help.

2
  • 4
    The simplest answer is to remove the permission from their given role of "Delete any" or "Delete own" per content type. This should remove the button in the user interface. Hooks won't help in this case, because they are meant for running before the operation, not stopping it - it will proceed anyway. This is contained in EntityBase::delete, mainly. Otherwise, Clive and Berdirs answers in the linked question should be sufficient.
    – Kevin
    Oct 15, 2021 at 20:26
  • Thank you for your comment, I found another solution (I added it below as an answer).
    – sailormoon
    Oct 19, 2021 at 6:57

1 Answer 1

1

I found a solution that satisfies me: I use hook_form_alter(). When you always try to delete a node there is a confirmation form, with "Delete" and "Cancel" buttons. I'm altering that form - in some cases (which depend of users permissions) I am unsetting "Delete" button (with unset($form['actions']['submit'], so delete is not possible) and adding my own button instead of it, with a callback function. I am also altering title of that form and description.

1
  • Would probably be helpful for future readers to see a bit of the code 🤗
    – leymannx
    Oct 19, 2021 at 11:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.