Preventing BackOffice Nodes from Being Deleted in Umbraco 7
Have you ever accidentally deleted a node in the BackOffice that shouldn't have been deleted? It's easily preventable with only a little bit of code.
Of course, you can create a group and set the "delete node" permissions, but this won't prevent administrators from accidentally deleting content or other nodes. And some nodes should never be deleted by anyone - like settings or other configuration areas.
(This also works for other menu items that you want to remove!)
Here are two ways to handle it:
- Display an error message when a user attempts to delete a node, or
- Remove the delete option entirely. (This makes more sense to me - why give users the delete option just to display an error message when they use it?)
These examples are for Umbraco 7.xx but can be modified to work with Umbraco 10 and above. The main difference is that Umbraco now uses Composer and Components instead of the ApplicationEventHandler.
Display An Error Message
Attach an event handler to the "Trashing" event and then prevent the delete and display an error message in your ApplicationEventHandler.cs
The above code prevents you from deleting anything. Which you surely aren't looking to do. So at this point you can add whatever criteria you want. Let's code it to prevent certain document types from being deleted.
Remove the Delete Option Entirely
Instead of attaching an event handler to the Trashing event like above you can attach to the MenuRendering event. Then we follow the same logic as the above method: look at the document type of the current node and (in this case) remove the "delete" menu item. The great thing about the MenuRendering event is that it's applied everywhere that a menu is created for that node.
Here's the menu when you click "Do Something Else" for a node:
And here's the "Action" menu on the right-hand side:
Create a method for the MenuRendering event and hook it up in the ApplicationStarted method. Then remove the menu option when you encounter a document type that you don't want deleted.
If you create a toggle property and add it to your documents then you can decide to only remove the delete menu item for nodes that have that property set to "true". That way you don't have to hard code your list.
There! No more accidental deletes.