In this tutorial, you will learn how to prevent pages from being deleted within the CMS in code. When building a new CMS project, an essential part of providing a good content editing experience is making a backend that is easy to use. One important aspect of this expereince, is preventing content editors from doing things that they shouldn't. One way to do this is to prevent content editors from deleting things they shouldn't. If a content editor accidentally deleted the homepage, the whole site would break. Luckily, Umbraco has some useful hooks that allow us, as developers, to add some nice validations that prevent these unwanted situations from occurring. Today you will learn about the Umbraco publishing events pipeline, so if you want to make a better Umbraco project, read on 🔥🔥🔥

Umbraco Events Pipeline

When a content editor creates or deletes a page in Umbraco, certain backend events are triggered. These events are fired from within the Umbraco events pipeline. When you try to delete content, a delete event is raised, when you try and save a page, the save event is triggered. As a developer, it is possible for you to hook into any of these events and trigger some custom code. To accomplish this, you can use the ApplicationEventHandler. Hooking into ApplicationEventHandler is easy. In your codebase, you create a new class and inherit from ApplicationEventHandler. To hook into an event you register event handlers. In today's example, to prevent a page from being deleted, we could hook into either the Trashing or UnPublishing events:

This class inherits from ApplicationEventHandler. One Line 18 and 19, two event handlers are registered Trashing and UnPublishing. These two methods will be called every time Umbraco raises an event of that type. Both the event handlers do pretty much the same thing. They look in the event args for the alias of the document type being requested to be deleted. If the request is for a page of type homepage the request is cancelled and a message is generated and returned to the content editor. This message will pop up in the back-end so the content editor knows why the page wasn't deleted. After you compile the code and run the back-end, provided your home pages alias is homepage you will now not be unable to delete it 💥


You now know how to do Umbraco event handling. You can hook into different events and add custom business logic, by implementing the ApplicationEventHandler. In this class, we register events we want to customize and override the base class methods. To add validation, interrogate the event arguments to check the request matches your criteria. Happy Coding 🤘