Sitecore Hyphenate Item name and set displayname to item name

5/21/2018 sitecore-events

It's better to make URLs in lowercase and hyphenate for SEO purposes. In case of Sitecore, URLs are generated based on the items created in Sitecore.

We can modify the item names and display names of a Sitecore item on item save the event. 

First, add your Item event handler to Sitecore config like below:


<event name="item:saved">
       <handler type="Sitecoreblog.Tools4geeks.SitecoreCustom.Data.Items.ItemEventHandler, Sitecoreblog.Tools4geeks.SitecoreCustom" method="HyphenateItenName"/>
</event>
<event name="item:saved:remote">
       <handler type="Sitecoreblog.Tools4geeks.SitecoreCustom.Data.Items.ItemEventHandler, Sitecoreblog.Tools4geeks.SitecoreCustom" method="HyphenateItenName"/>
</event>

Here is the way how to do it. Quick mentions:

  • Process only items in Master database.
  • Process only content Items
  • While hyphenating item name change display name to item name. So content editors see nice item names in Sitecore.

/// <summary>
        /// Ensures that item names are lower case and hyphenated for URL creation purposes. The original name is saved as the Display Name.        /// </summary>
        /// <param name="sender">Event sender.</param>
        /// <param name="args">Event arguments.</param>
        protected void HyphenateItemName(object sender, EventArgs args)
        {
            var item = (Item)Event.ExtractParameter(args, 0);
            // only process items in master database
            if (item.Database.Name != "master")
            {
                return;
            }
            // only process items in the content tree
            if (!item.Paths.IsContentItem)
            {
                return;
            }
            string processedName = item.Name.ToLower().Replace(' ', '-');
            if (item.Name == processedName)
            {
                return;
            }
            item.Editing.BeginEdit();
            try
            {
                item.Appearance.DisplayName = item.Name;
                item.Name = processedName;
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error("Error while hyphenating item name.", ex, this);
            }
            finally
            {
                item.Editing.EndEdit();
            }
        }

 

Hope this helps someone!