Subscribe:

Pages

Saturday, February 25, 2012

Sitecore Item Renamed Event Handler

This post is continuation of my previous post Sitecore Custom Token for Display Name which describes how to create a custom token for SEO friendly item name. As described in my previous post we need to handle a case where item is renamed, to update the display name of item to new item name.

So in this post I am going to create a custom event handler for Sitecore item renamed event. Goal of this custom event handler is to check if any of the fields in Sitecore item are using “$displayname” token and replace the “$displayname” token with new item name.

First let’s create a class file for our event handler and name it “ItemEventHandler.cs” which looks as follows

public class ItemEventHandler
    {
        public void OnItemRenamed(object sender, EventArgs args)
        {
            Item itm = Event.ExtractParameter(args, 0) as Item;
            itm.Fields.ReadAll();
            using (new Sitecore.SecurityModel.SecurityDisabler())
            {
                itm.Editing.BeginEdit();
                //Get all the fields which has $displayname token standard value
                foreach (Field fld in itm.Fields.Where(x => x.GetStandardValue() != null && x.GetStandardValue().Equals("$displayname")))
                {
                    //check if user has changed the standard value
                    if ((Event.ExtractParameter(args, 1) as string).ToTitleCase().Equals(itm.Fields[fld.ID].Value))
                    {
                        itm.Fields[fld.ID].Value = itm.Name.ToTitleCase();
                    }
                }
                itm.Editing.EndEdit();
            }
        }
    }

You may note that I am not replacing the token if filed value has been modified by the user.

Now we need to register our custom event handler, to do this go to custom.config file we created as described in previous post and add following under Sitecore node.

<events>
  <event name="item:renamed">
    <handler type="Namespace.ItemEventHandler, assembly name" method="OnItemRenamed"/>
  </event>
</events>

Feel free to post your comments or suggestions.

No comments :

Post a Comment