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 && (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 && (mediaItem.Id > 0 && !string.IsNullOrWhiteSpace(mediaItem["key"])))
            {
                var key = mediaItem["key"];
                return $"umb://media/{key.Replace("-","")}";
            }
            return null;
        }
    }
}

Before adding the above code:

After adding the above code. See the article date is pre-filled with today's date.

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.

Share this post

About the author

Paul Seal

Umbraco MVP and .NET Web Developer from Derby (UK) who specialises in building Content Management System (CMS) websites using MVC with Umbraco as a framework. Paul is passionate about web development and programming as a whole. Apart from when he's with his wife and son, if he's not writing code, he's thinking about it or listening to a podcast about it.

Related Posts

How to start working with Umbraco v8

In this post I give you step by step instructions for getting Umbraco v8 forked, checked out and wor…

Read Post

How to solve Multiple types were found that match the controller named x

This post shows you how to solve the error 'Multiple types were found that match the controller name…

Read Post

5 things a developer should do before asking for help

In this post I give you my opinions and experience about when I think you should ask for help and wi…

Read Post

Some questions answered about Umbraco Cloud

In this post I give you some answers to the questions I had about Umbraco Cloud at the beginning of…

Read Post