1

I have followed this example and here is my custom event handler for item:saving.

protected void OnItemSaving(object sender, EventArgs args)
{
   Item newItem = Event.ExtractParameter(args, 0) as Item;    
   Item originalItem = newItem.Database.GetItem(newItem.ID, newItem.Language, newItem.Version);  

    string Title = originalItem.Fields["Title"].Value; // "Chapter One" (old value)
    Title = newItem.Fields["Title"].Value; // "Chapter Two" (new value)       
}

The code works perfect for my requirement, but I'm confused on a few things.

  1. I was assuming that the Item fetched in the item:saving event will only have old field values, but here the newItem has new values also.
  2. I'm unable to understand this piece of code on how it is getting old item/old values from newItem - newItem.Database.GetItem(newItem.ID, newItem.Language, newItem.Version);

Could anyone please help me understand. Thank you.

1 Answer 1

2

item:saving event is executed before item is saved in the database.

Item which is stored within event args is what will be saved to the database if none of the handlers abandons the process.

And item which is in the database is the original one as nothing was saved to database yet. When you're calling

Item originalItem = newItem.Database.GetItem(newItem.ID, newItem.Language, newItem.Version);  

you're telling Sitecore to give you what is there still in the database before you "confirm" or "cancel" saving new changes.

So yes, in your case newItem has all the new field values and originalItem has all the fields which are still in the database.

With that approach you can add some condition when item should not be saved to the database and call the following line in order to prevent saving new values:

ItemSavingEventArgs itemSavingEventArgs = (ItemSavingEventArgs) args;
itemSavingEventArgs.Cancel = true;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.