Umbraco: Create content automatically on events

0
67

When you have big but repeating content-structures it might make the work of your conent editor easier to auto-create certain types of content.

Lets say you have a document type for a page with a slider. A possible structure for the content would be to add a slider-repository beneath the page and slider items beneath the slider repository.

Umbraco: Homepage with slider repository
Homepage with slider repository and three slider items

And it would be very usefull the create the slider repository automatically for all document types that can contain a slider.

Luckily there is the ApplicationEventHandler class that we can override to react to events like the creation of a new content element.

How to automatically add content on events

Lets start with the code. Just add this to a new file. I usually add it inside the controllers folder.

public class AddSliderRepositoryEventHandler : ApplicationEventHandler
{
    protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        ContentService.Saved += NewPageCreated;
    }

    static void NewPageCreated(IContentService cs, SaveEventArgs<IContent> e)
    {
        if (e.SavedEntities != null)
        {
            foreach (var elem in e.SavedEntities.Where(n => n.IsNewEntity() && n.ContentType.Alias == "AliasOfYourDocumentType"))
            {      
                IContent c = cs.CreateContent("Slider Repository", elem.Id, "AliasOfSliderRepositoryDocumentType");
                cs.SaveAndPublishWithStatus(c);
            }
        }
    }
}

The ApplicationStarted method will be called when umbraco is initialised. We use that method do add a new action. Whenever a content element is saved from the umbraco backend the method NewPageCreated will be executed.

If you want to pass an additional parameter to the NewPageCreated method you can do this by creating a anonymous function receiving the two parameters and calling our method with a third one:

ContentService.Saved += (cs, e) => NewPageCreated(cs, e, "additionalParam");

Within the NewPageCreated method we create a new element beneath the newly saved one. The important parts are:

  • Only create something if the saved element is new. Don’t create a slider repository if the element is saved a second or third time. This information can be obtained by calling the IsNewEntity function
  • add the right aliases for you slider repository document type and for the document type that contains a slider.

You can of course populate some of the fields of the document you are adding or the document containing it.

If you have any special requierements, feel free to ask about them in the comments.

LEAVE A REPLY

Please enter your comment!
Please enter your name here