Show warning when a fire occurs

I have the following requirement. I saved a list of dictionary items. I want the dictionary to be unique. I wrote the following code, as if every new item was saved with an existing key name, it should raise a warning, for example, โ€œItem already existsโ€.

What I am doing is similar to comparing the Key value with existing dictionary keys while saving an element. I wrote the code in the ItemSaving event.

public class IsItemExist { Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master"); public void OnItemSaving(object sender, EventArgs args) { Item dbItem = master.GetItem("/sitecore/content/Administration/Development Settings/Lookups"); Item selectedItem = Event.ExtractParameter(args, 0) as Item; foreach (Item item in dbItem.Axes.GetDescendants()) { if (item.Template.Name.Contains("entry")) { if (item.Fields["Key"].Value == selectedItem.Fields["Key"].Value) { Sitecore.Context.ClientPage.ClientResponse.Alert("Item is already exist"); } } } } } 

web.config entry

 <event name="item:saving"> <handler type="CustomEvent.IsItemExist, CustomEvent" method="OnItemSaving"/> </event> 

It shows a warning message and I can save the item. 1. I do not want to save the item with a duplicate value again. 2. I get 2 notifications when a message appears when I click save.why?

Any help would be appreciated. Thanks guys..

+6
source share
1 answer

You must add a handler to the item:adding event and set the Cancel property to the result of the true event:

  <event name="item:adding"> <handler type="CustomEvent.DoesItemExist, CustomEvent" method="OnItemAdding" /> </event> 
 public class DoesItemExist { Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master"); public void OnItemAdding(object sender, EventArgs args) { Item dbItem = master.GetItem("/sitecore/content/Administration/Development Settings/Lookups"); Item selectedItem = Event.ExtractParameter(args, 0) as Item; foreach (Item item in dbItem.Axes.GetDescendants()) { if (item.Template.Name.Contains("entry")) { if (item.Fields["Key"].Value == selectedItem.Fields["Key"].Value) { SitecoreEventArgs evt = args as SitecoreEventArgs; evt.Result.Cancel = true; Sitecore.Context.ClientPage.ClientResponse.Alert("Item already exists"); } } } } } 
+6
source

All Articles