Accessing Umbraco 8 Saving Events


How to use IUserComposer & IComponent to access the saving event in Umbraco 8.

 

I did a previous post showing how easy it was to do this with Umbraco 7.  It has changed a lot in Umbraco 8, it now uses dependency injection. 

 

So how do we do it?

 

In this example we have added an Approve property type (datatype: TrueFalse) on our Home document type.

 

When publishing, Approve will have to be checked otherwise an error will be raised and the content not saved.  This example will not be much use in the real world, but it's a basic example to show how easy it is to access events.

 

1) Create a custom composer which inherits from IUserComposer

public class EventSavingComposer : IUserComposer
    {
        public void Compose(Composition composition)
        {
             composition.Components().Append();
        }
    }


2) Create a custom component which inherits from IComponent

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

        public void Terminate()
        {
        }

        private void ContentService_Saving(IContentService sender, ContentSavingEventArgs e)
        {
            foreach (var content in e.SavedEntities.Where(c => c.ContentType.Alias.InvariantEquals("Home") && !c.GetValue("approve")))
            {
                
                    EventMessage msg =
                        new EventMessage("Error", "You must seek approval before publishing this content", EventMessageType.Error);
                    e.CancelOperation(msg);
                
            }
        }
    }


...As simple as that.

Comment