Score:4

How to prevent a node from being deleted while performing a delete operation?

cn flag

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.

Kevin avatar
in flag
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.
sailormoon avatar
cn flag
Thank you for your comment, I found another solution (I added it below as an answer).
Score:1
cn flag

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.

leymannx avatar
ne flag
Would probably be helpful for future readers to see a bit of the code
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.