Email Aaron Blake now at webmaster@aaronblake.co.uk
or contact me

Sitecore Item Renamed Event does not provide item name before renaming.

According to Sitecore documentation the item:renamed event arguments should provide you with the result item and the item name before renaming.

item:renamed
0
Item
Result item

1
String
Item name before renaming

Unfortunately in practice the second value is actually the current item name, and not the previous name.

This bug presents a massive problem if you require the previous name.

Fortunately I found a way around this.
By using the Sitecore history engine, you can work out what the previous name was.

Solution:

        protected void OnItemRename(object sender, EventArgs args)
        {
            var itm = Event.ExtractParameter(args, 0) as Sitecore.Data.Items.Item;

            if (itm == null)
            {
                return;
            }

            var history = itm.Database.Engines.HistoryEngine.GetHistory(DateTime.UtcNow.AddDays(-1), DateTime.UtcNow.AddDays(1));

            if (history.Count < 1)
            {
                return;
            }

            var oldEntity = GetOldEntity(itm.ID.Guid, itm.Paths.Path, history);

            var oldName = GetOldName(oldEntity.ItemPath);
        }
        /// 
        /// Uses the history engine to retrieve the last entry with a different path from the target item.
        /// 
        /// 
        /// The item id.
        /// 
        /// 
        /// The item path.
        /// 
        /// 
        /// The history.
        /// 
        /// 
        /// History Entity
        /// 
        public static HistoryEntry GetOldEntity(Guid itemId, string itemPath, HistoryEntryCollection history)
        {
            var oldEntities = from h in history
                              orderby h.Created descending
                              where h.ItemId.Guid.Equals(itemId) && (!h.ItemPath.Equals(itemPath))
                              select h;

            return oldEntities.Count() < 1 ? null : oldEntities.First();
        }

        /// 
        /// Gets the old item name
        /// 
        /// 
        /// The old item path.
        /// 
        /// 
        /// The old item name
        /// 
        public static string GetOldName(string oldItemPath)
        {
            return oldItemPath.Substring(
                (oldItemPath.LastIndexOf("/", StringComparison.CurrentCulture) + 1),
                (oldItemPath.Length - oldItemPath.LastIndexOf("/", StringComparison.CurrentCulture) - 1));
        }

Post a Comment

You must be logged in to post a comment.

Email me through this magic form.