HOW TO PREVENT DUPLICATE ITEMS IN SITECORE
HOW TO PREVENT 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.
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
After the event handler is written, it must be added to the event definition.
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.
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)
{
((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.
https://xchangesitecore.com/how-to-prevent-duplicate-items-in-sitecore/ Vikash Raaj
"http://www.sitecore.net/xmlconfig/">
<sitecore>
<events>
<event name="item:creating">
<handler type="YourNameSpace.PreventDuplicateItem, YourAssembly"
method="OnItemCreating"/>
</event>
</events>
</sitecore>
</configuration>
Comments
Post a Comment