In a recent project, I have to update certain fields of sitecore item when the item is saved in sitecore.
The solution I went for involved extending item:saved event and adding my own handler to do certain actions based upon template type
If you are in a similar situation, here are the steps to do
1. Create you custom class with a public method to perform your logic
2. In web.config under <events> find , <event name=”item:saved”> and append your handler at the end.
Here is basic class code
public class ItemSaveEventHandler { //master database name public static readonly string Master = "master"; //sample template id public static readonly string TemplateIdItem = "{67B44133-70CD-405C-BDAF-B93E5AEA2682}"; public void OnItemSaved(object sender, EventArgs args) { Item temp = Event.ExtractParameter(args, 0) as Item; //make sure you are in edit mode and not in publish mode if (temp != null && temp.Database.Name.ToLower() == Master) { //check if the template is what you are looking for if (temp.TemplateID.ToString() == TemplateIdItem ) { //do your stuff with the item, this is just a sample temp.Editing.BeginEdit(); temp.Fields["Title"] = "new item saved title"; temp.Editing.EndEdit(); temp.Editing.AcceptChanges(); } } }
Complie and debug code, when you are ready change the web.config
<event name="item:saved"> <handler type="Sitecore.Links.ItemEventHandler, Sitecore.Kernel" method="OnItemSaved"/> <handler type="Sitecore.Globalization.ItemEventHandler, Sitecore.Kernel" method="OnItemSaved"/> <handler type="Sitecore.Rules.ItemEventHandler, Sitecore.Kernel" method="OnItemSaved"/> <!-- add the namespace name and assembly dll name as per your site --> <handler type="<MyWebsite.Handlers.ItemSaveEventHandler>, <MyWebsite.Hanlders>" method="OnItemSaved"/> </event>
Thats it, if everything is correct the event handler will be called when someone saves an item in sitecore
Cheers
Thanks for the post, I didn’t see the AcceptChanges() – it is very confusing, what is the BeginEdit() and EndEdit() for if you need an AcceptChanges() as well?
And one should use EndEdit(true) when inside this pipeline or else one might trigger a stackoverflow by triggering the pipeline again and again.
Works great for me! Using EventArgs instead of ItemSavedEventArgs was the trick for me.