My friend Nik asked me today if I knew how to prevent an umbraco node from being saved if the name has changed.

I hadn't done it before but I knew how to intercept saving events, so I knocked up this quick example for him in the v8 project I was working on.

And because I didn't need it in the project I was working on and I knew I might want it in the future, I decided to create this blog post with the code in it.

In this example we are prevent anyone from changing the name of the home page. You can change the Content Type Alias to meet your needs.

using Umbraco.Core;
using Umbraco.Core.Composing;
using Umbraco.Core.Events;
using Umbraco.Core.Services;
using Umbraco.Core.Services.Implement;

namespace CodeShare.Core.Composing
{
    [RuntimeLevel(MinLevel = RuntimeLevel.Run)]
    public class SavingEventComposer : ComponentComposer<SavingEventComponent>
    { }

    public class SavingEventComponent : IComponent
    {
        public void Initialize()
        {
            ContentService.Saving += ContentService_Saving;
        }

        private void ContentService_Saving(IContentService sender, ContentSavingEventArgs e)
        {
            foreach (var node in e.SavedEntities)
            {
                // if it is a home page doc type and it isn't new and the name has changed
                if(node.ContentType.Alias == "homePage" && node.Id > 0 && node.IsPropertyDirty("Name"))
                {
                    e.Cancel = true;
                    e.CancelOperation(new EventMessage("Error", "You can't change the name", EventMessageType.Error));
                }
            }
        }

        public void Terminate()
        {
            // Nothing to terminate
        }
    }
}

I hope it helps someone in the future, even if it is me 😃

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

Moriyama

  • Moriyama build, support and deploy Umbraco, Azure and ASP.NET websites and applications.
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.