0

I would like to pass an object from the item:created event to the item:saving event, but unable to do so.

This is to add custom logs for certain events. When an item is created, I will be logging the event in the OnItemCreated method. But this will also trigger the OnItemSaving & OnitemSaved methods, where I do not want to log for item creation as there is one log already.

patch.config:

<events>
  <event name="item:created">
    <handler type="Basiscore.CmsAudit.Handlers.ItemEventHandler, Basiscore.CmsAudit" method="OnItemCreated"/>
  </event>
  <event name="item:saving">
    <handler type="Basiscore.CmsAudit.Handlers.ItemEventHandler, Basiscore.CmsAudit" method="OnItemSaving"/>
  </event>                 
</events>

ItemEventHandler.cs:

protected void OnItemCreated(object sender, EventArgs args)
{
   ItemCreatedEventArgs itemCreatedEventArgs = Event.ExtractParameter<ItemCreatedEventArgs>(args, 0);
   Item createdItem = itemCreatedEventArgs?.Item;
   ///Pass object to successor event
   MyClass obj = new MyClass();
   Event.RaiseEvent("item:saving", new object[] { createdItem, obj });
}

protected void OnItemSaving(object sender, EventArgs args)
{
  Item changingItem = Event.ExtractParameter(args, 0) as Item;
  MyClass obj = Event.ExtractParameter(args, 1) as MyClass; //Here obj is always null
  
  MyClass obj2 = new MyClass();

  ///Pass obj to successor event
  Event.RaiseEvent("item:saved", new object[] { changingItem, obj2 }); //Here is an exception
}

Exception:

could not extract parameter from event args

1 Answer 1

2

You cannot pass data between Sitecore events. Sitecore events you mention in your question are built-in events and you should not raise them on your own in your custom code.

From this and other question asked by you recently, I think you should change your approach slightly instead of passing data between events.

If you want to audit changes in Sitecore using custom code, maybe the following approach would work for you:

  • on item:created - audit only information about item name, id, location and tempalte
  • on item:saving - audit only changed fields. Make sure that your event handler is last one in the config, check if args.Cancel is not true and use code similar to:
protected void OnItemSaving(object sender, EventArgs args)
{
    var itemSavingEventArgs = args as ItemSavingEventArgs;
    if (itemSavingEventArgs != null && !itemSavingEventArgs.Cancel)
    {
        var itemChanges = itemSavingEventArgs.Changes;
        DoSomethingWithItemChanges(itemChanges);
    }
}
  • on item:saved you can confirm that item:saving was completed but don't audit any changes anymore.

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.