In my Sitecore 6.1.0 installation I have hooked onto the "item:added" event by implementing my own custom handler as follows (in Web.config):
<event name="item:added">
<handler type="Sitecore.Data.Fields.ItemEventHandler, Sitecore.Kernel" method="OnItemAdded" />
<handler type="my.project.Classes.OnSaveItemHandler, my.project" method="OnItemAdded" />
</event>
The purpose of this is to enforce unique names for items - in other words, in my OnItemAdded method I want to do a Lucene search for any other items with the same name as the item being added.
The OnItemAdded method is called every time an item is added in the Sitecore structure. But my problem is - the method is called more than once per item. I've seen it called anywhere between 6 and 26 times per added item, depending on where in the Sitecore structure I add the item. The body of my OnItemAdded method is empty:
protected void OnItemAdded(object obj, EventArgs args)
{
}
The first time the method gets called when an item is added, the item in the args
parameter is the correct item. If the item's name is theItemName
, the FullPath property will look like this:
/sitecore/content/theItemName
Every time except for that first one, the item looks correct, but the item's path looks like this:
[orphan]/sitecore/content/theItemName
Why is the [orphan] bit being added onto the full path? And why is the OnItemAdded method being called more than once, even though I am only adding one item?
I believe there are known issues with event likes this where the method will be called several times. I know I had a similar experience where I was trying to programatically create a role for an item when the item was created. John West said the following as a precaution:
I seem to remember that Sitecore sometimes fires some events more than once, so you might want to check for that [...]
John then provided a link to a blog post called Intercepting Item Updates with Sitecore
In my code, I had a check that checked to see if the operation I was looking for had already occurred, e.g. does the role for the item exist. In your case, this might be a bit harder to check in the method. Maybe you can do something sneaky like:
protected void OnItemAdded(object obj, EventArgs args) {
Item item = // code to extract item from args, I forgot it
if(item.Paths.FullPath.StartsWith("/sitecore/content")) {
// do your stuff because you know its the first time the event fired
}
}
Again, this is very hackish. I'd say this is a last resort if Sitecore support cannot provide any better options (or there aren't any better options posted on Stack overflow).