Providing good validation in the Umbraco back-end is an often overlooked but key component when implementing a successful content editor experience. One way to do this is preventing content editors from deleting things they shouldn't. One example of this would be the homepage. If someone accidently deleted that, the whole site would break. Luckily, Umbraco has some useful hooks that allow us, as developers, to write code to prevent this. In today's tutorial, I will discuss the Umbraco publishing events pipeline.
Umbraco Events Pipeline
When a content editor creates or deletes a page in Umbraco, it follows 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. In order for a developer to hook into these events, we must use the Umbraco ApplicationEventHandler. Hooking into ApplicationEventHandler is easy, as it's a base class so all you need to do is inherit from it and override the methods of the events you want to customise. So, if we want to add some validation to prevent certain document types from being deleted, all you need to do is hook into the Trashing and UnPublishing events
Ok, so let's talk through what the code is doing. First, we inherit from 'ApplicationEventHandler'. We create a constructor and register two events Trashing and UnPublishing and create two methods that override. Both methods 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 type is of type 'homepage' then the request is canceled and an event message is generated and returned to the user. This will pop up in the back-end so the user knows why the page wasn't deleted. After you compile the code and run the back-end, provided your home pages alias is 'homepage' then you will now be unable to delete it.
In today's post, we've discussed the Umbraco events handling for the page publishing pipeline. We can hook into different events and add custom logic, by implementing the ApplicationEventHandler. In this class, we register events we want to customize and override the base class methods. You interrogate the event arguments to check the request matches your criteria, then you cancel the request and sent a message to return to the content editor describing why the request was canceled.