Twitter LinkedIn

CODE SITECORE ITEM EVENT CUSTOM HANDLERS

  • By Andrew Ward
Andrew Ward

Located in the web config is a section called <events> this contains a load of events that are fired when things happen within Sitecore. The common one I see Sitecore solutions using is the item:saved event. Hopefully this post is going to get you started on writing some custom save event handlers.
All we need is a class within our project containing the following code:

When the code below is run it is going to replace any spaces in the item’s name with hyphens (this is just an example, if you wish to achieve hyphens instead of spaces in the URL of a page, there is a replace section in the web.config where this can be easily achieved with “out of the box” functionality)

using System;
using Sitecore.Data.Items;
using Sitecore.Diagnostics;
using Sitecore.Events;

namespace Sitecore.Playground.ItemEventHandler
{
    public class EventHandler
    {
        protected void OnItemSaved(object sender, System.EventArgs args)
        {
            if (args == null)
            {
                return;
            }

            // get item from args
            Item item = Event.ExtractParameter(args, 0) as Item;

            // if we have an item
            if (item != null && item.Name.Contains("-"))
            {
                try
                {
                    // begin editing and replace spaces in the items name with hyphens
                    item.Editing.BeginEdit();
                    item.Name = item.Name.Replace(" ", "-");
                    item.Editing.AcceptChanges();
 		    item.Editing.EndEdit();

		}
		catch (Exception ex)
		{
			// catch and log exception to the Sitecore log logs
			Log.Error(string.Format("Failed to rename item {0}: ", item.ID), ex, this);
		}
	}
}
// other example method
protected void OnItemDeleted(object sender, System.EventArgs args)
{
}
}
}



To get the code to run when an item is saved, we need to head over to the web.config in the section, find your desired item:event and place the following handler in the event element. In my case I’m going to place it in the item:saved event.

<event name="item:saved">
        <handler type="Sitecore.Playground.ItemEventHandler, Sitecore.Playground" method="OnItemSaved"></handler>
</event>



References required:

-          Sitecore.Kernal.dll

 

3chillies Reading (HQ) 4th Floor, The Blade, Abbey Square Reading Berkshire RG1 3BE 0118 931 4196 Find us
This website is hosted Green - checked by thegreenwebfoundation.org

Our Partners

  • microsoft partner logo
  • sitecore logo
  • umbraco logo
  • Optmizely logo
  • uMarketingSuite logo
  • Cookiebot
scroll back to the top of the current web page