Preventing duplicate items in Sitecore

As a recommended practice, we should not allow duplicate names, in order to achieve this, we have to create a new event in Sitecore. Events in Sitecore are similar to the events in other systems: something triggers an event and there are handlers that are configured to handle the event.

Creating an Event Handler

While there is neither a class to extend nor an interface to implement, a convention must be followed in order for Sitecore to be in order for a class to be used as an event handler.

The class must have an OnItemCreating method that accepts object and EventArgs

public void OnItemCreating(object sender, EventArgs args)
{
        
   Assert.ArgumentNotNull(sender, "sender");
   Assert.ArgumentNotNull(args, "args");

   using (new SecurityDisabler())
   {
       ItemCreatingEventArgs arg = Event.ExtractParameter(args, 0) as ItemCreatingEventArgs;

       if (Sitecore.Context.Site.Name == "shell")
       {
            var firstOrDefault = arg.Parent.GetChildren()
                                            .FirstOrDefault(x => (arg.ItemName.Equals(x.Name, StringComparison.OrdinalIgnoreCase)) && (arg.ItemId != x.ID));
            
            if (firstOrDefault != null && firstOrDefault.Fields[FieldIDs.LayoutField] != null && !string.IsNullOrEmpty(firstOrDefault.Fields[FieldIDs.LayoutField].Value))
            {
                ((SitecoreEventArgs)args).Result.Cancel = true;
                Sitecore.Context.ClientPage.ClientResponse.Alert($"Item '{firstOrDefault.Name}' already exists!");
                return;
            }
        }
   }
}

After the event handler is written, it must be added to the event definition.

Create a Sitecore Patch file

Create a new Patch file inside the /App_Config/Include folder. The following is the Sitecore patch file with an example of how the custom event handler is added.

<configuration xmlns:patch="http://www.sitecore.net/xmlconfig/">
  <sitecore>
    <events>
      <event name="item:creating">
        <handler type="YourNameSpace.PreventDuplicateItem, YourAssembly" method="OnItemCreating"/>
      </event>
    </events>
  </sitecore>
</configuration>