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.

Want to thank me?

If I've helped you out and you want to thank me, why not buy me a coffee?

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

Find out how my blog reached 1 million page views

In this post I will tell you how my blog reached 1 million page views.

Read Post

How to include scripts from partial views in MVC and Umbraco

This post will show you how you can include scripts from inside an MVC partial view rather than havi…

Read Post

How to fix the error "Authentication failed because the remote party has closed the transport stream"

This post will show you how to fix the error "Authentication failed because the remote party has clo…

Read Post

How to solve the error Could not load file or assembly System.Security.Principal.Windows

This post help you solve the error System.IO.FileNotFoundException Could not load file or assembly S…

Read Post