Umbraco 9 : Editor Model Notifications

Editor Model Notifications are handy when you want to control over the model that is used by the backoffice of Umbraco before its loaded in the editor. In this article, we will see how we can use the Editor Model Notifications in Umbraco 9.

Editor Model Notifications were handled as Editor Model Events in Umbraco 8. One of the most common use case for Editor Model Notifications is to set default values for fields. For e.g. setting the date for a blog post to the current date and time. In this example, we will see how we can set a default value to a field.

I have set up a local Umbraco 9 site with the starter kit. And I have a property called Theme on the Content document type.

Let us see how we can default it to Light Blue every time when someone tries to create a node based on the document type. I am using the SendingContentNotification for this. This notification is published right before a content item is loaded into backoffice for editing. This notification is for content items. There are similar notifications for media, user, member and dashboards as well.

To create a Notification Handler for the SendingContentNotification create a class which inherits from INotificationHandler passing in the notification type, in this case SendingContentNotification. The INotificationHandler has a Handle() method which can be implemented to control the model sent to the backoffice. 

public void Handle(SendingContentNotification notification)
{
	if (notification.Content.ContentTypeAlias == "contentPage")
	{
		foreach (var variant in notification.Content.Variants)
		{
			var theme = variant.Tabs.SelectMany(f => f.Properties)
					.FirstOrDefault(f => f.Alias.InvariantEquals("theme"));
			if (theme is not null)
			{
				theme.Value = "Light Blue";
			}
		}
	}
}

The Content property of the SendingContentNotification is a ContentItemDisplay type which is the model which represents a content item displayed for editing in the backoffice. 

Now we need to register this notification handler using a Composer.

public class ThemeNotificationComposer : IComposer
{
	public void Compose(IUmbracoBuilder builder)
	{
		builder.AddNotificationHandler<SendingContentNotification, ThemeNotificationHandler>();
	}
}

Build and run and I have my theme set to Light Blue. Whoop whoop!

You can read more about Editor Model Notifications in Umbraco Official Docs.