blog
Using Sitecore's New AddFromTemplate Item Provider Pipeline

With the release of SXP 8, Sitecore included a new set of item provider pipelines that are incredibly useful. Today, I will show you how you can write a processor for the new <addFromTemplate> pipeline.

When to Use the addFromTemplate Pipeline

The <addFromTemplate> pipeline differs from the <uiAddFromTemplate> pipeline in that the <addFromTemplate> pipeline is run whenever an item is added, regardless of whether it is added programmatically or from the UI. In contrast, the <uiAddFromTemplate> pipeline is only run if an item is added from the “Add From Template” option in the Sitecore UI.

You should use the <addFromTemplate> pipeline when you want to execute custom code whenever an item is created. Note that this is also the best option if you want to run custom logic whenever an item is created from a specific or nonspecific branch template.

Side-note: On all of my projects, I include a processor for this pipeline that will execute rules.


Writing the Processor

The below is what you need at a minimum in order to write this processor:

public class MyAddFromTemplateProcessor : AddFromTemplateProcessor
{
    public override void Process([NotNull] AddFromTemplateArgs args)
    {
        // this is managed in configuration (runIfAborted=true would have to be set to override the value)
        if (args.Aborted)
        {
            return;
        }

        Assert.IsNotNull(args.FallbackProvider, "FallbackProvider is null");

        try
        {
            var item = args.FallbackProvider.AddFromTemplate(args.ItemName, args.TemplateId, args.Destination, args.NewId);
            if (item == null)
            {
                return;
            }

            args.ProcessorItem = args.Result = item;
        }
        catch (Exception ex)
        {
            Log.Error("MyAddFromTemplateProcessor for Pipeline AddFromTemplate failed. Removing partially created item if it exists.", ex, this);

            var item = args.Destination.Database.GetItem(args.NewId);
            item?.Delete();

            throw;
        }

        // your logic here
    }
}
1 Comments
Post a Comment

 
  • Comment by john on Sep 21, 2017
    This post gives a great information on sitecore addfromtemplate item and is very useful for sitecore partners likes for certified sitecore partners kindly visit skybridge infotech pvt ltd