How to add default values to Umbraco properties in the backoffice

Posted written by Paul Seal on September 26, 2018 Umbraco

If you are looking for the v8 version. Nik Rimington has done that in this blog post.

Since starting my new job at Moriyama, I've been learning lots of new things about Umbraco, especially from Marc Goodson.

Today I was working on a newsletter generator. The document type had some content that would benefit from having a default value. Marc said it would be good if the values were pre-filled with default values when you load the page in the Umbraco backoffice editor. I didn't know how to do this. 

Marc sent me a link to the EditorModel Events documentation, which he also wrote.

The code is in the official documentation linked above, but I thought I would play with it and take it a little further.
Now I have got it putting default values in properties and in the node name.

You add the code to a class which inherits from ApplicationEventHandler like this:

using Examine;
using System;
using System.Linq;
using Umbraco.Core;
using Umbraco.Web.Editors;
using Umbraco.Web.Models.ContentEditing;

namespace UDT.Web.EventHandlers
{
    public class EditorModelEventHandler : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            //Here we are binding the new method we created below to the SendingContentModel event.
            EditorModelEventManager.SendingContentModel += EditorModelEventManager_SendingContentModel;
        }

        private void EditorModelEventManager_SendingContentModel(System.Web.Http.Filters.HttpActionExecutedContext sender,
            EditorModelEventArgs<ContentItemDisplay> e)
        {
            SetDefaultValue(e, new string[] { "blogpost" }, "articleDate", DateTime.Now.AddDays(+1).Date);
            SetDefaultValue(e, new string[] { "blogpost" }, "mainImage", GetLastImage());
            SetDefaultValue(e, new string[] { "blogpost" }, "categories", "umbraco,tutorial,howto,paul seal");
            SetDefaultValue(e, new string[] { "content", "profile" }, "title", "Interesting title here");
            //This one is pretty cool, it sets the node name for you as a long version of today's date.
            SetDefaultNodeNameValue(e, new string[] { "blogpost" }, DateTime.Now.ToString("dddd MMMM dd yyyy"));
        }

        private static void SetDefaultValue(EditorModelEventArgs<ContentItemDisplay> e, string[] docTypeAliases, string propertyAlias, object newValue)
        {
            //check if the doc type alias in the current model is in the array of doc type aliases you are interested in
            if (docTypeAliases.Contains(e.Model.ContentTypeAlias))
            {
                //find the property you are interested in and set its default value
                var property = e.Model.Properties.FirstOrDefault(f => f.Alias == propertyAlias);
                if (property != null &amp;&amp; (property.Value == null || String.IsNullOrEmpty(property.Value.ToString())))
                {
                    property.Value = newValue;
                }
            }
        }

        private static void SetDefaultNodeNameValue(EditorModelEventArgs<ContentItemDisplay> e, string[] docTypeAliases, string newValue)
        {
            if (docTypeAliases.Contains(e.Model.ContentTypeAlias))
            {
                if (string.IsNullOrWhiteSpace(e.Model.Name))
                {
                    e.Model.Name = newValue;
                }
            }
        }

        private static string GetLastImage()
        {
            var criteria = ExamineManager.Instance.SearchProviderCollection["InternalSearcher"].CreateSearchCriteria(UmbracoExamine.IndexTypes.Media);
            var filter = criteria.NodeTypeAlias("Image").And().OrderBy("createDate");
            var results = ExamineManager.Instance.SearchProviderCollection["InternalSearcher"].Search(filter.Compile());
            var mediaItem = results.Last();
            if(mediaItem != null &amp;&amp; (mediaItem.Id > 0 &amp;&amp; !string.IsNullOrWhiteSpace(mediaItem["key"])))
            {
                var key = mediaItem["key"];
                return $"umb://media/{key.Replace("-","")}";
            }
            return null;
        }
    }
}

As you can see, it is really convenient especially for date fields.

Thanks again to Marc for telling me about this.

Watch the video

If you learn better from videos, take a look at the video I made for this.