简体   繁体   中英

Show alert message when event fires

I have the following requirement. I have stored a list of dictionary items. I want Dictionary Key to be unique. I have written the following code like whenever any new item is saving with existing key name, it should throw an alert like "Item already exist".

What I am doing is like comparing the Key value with existing dictionary keys while saving the item. I have written 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's showing alert message and i am able to save the item. 1.I don't want to save the Item with duplicate value again. 2.I am getting 2 alert messges when click on the save button.why?

any help will be appreciated.Thanks Guys..

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

  <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");
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM