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.

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.

Proudly sponsored by

AppVeyor

  • CI/CD service for Windows, Linux and macOS
  • Build, test, deploy your apps faster, on any platform.
stkrs

  • Custom stickers for startups, artists and brands.
  • Bespoke easy-apply, removable, custom brand stickers printed in the UK.
elmah.io

  • elmah.io is the easy error logging and uptime monitoring service for .NET.
  • Take back control of your errors with support for all .NET web and logging frameworks.
uSync Complete

  • uSync.Complete gives you all the uSync packages, allowing you to completely control how your Umbraco settings, content and media is stored, transferred and managed across all your Umbraco Installations.