1

I'm trying to log item events like - on item created, on item saved etc.

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>
   <event name="item:saved">
      <handler type="Basiscore.CmsAudit.Handlers.ItemEventHandler, Basiscore.CmsAudit" method="OnItemSaved"/>
   </event>      
</events>

ItemEventHandler.cs:

public class ItemEventHandler
{
  public void OnItemCreated(object sender, EventArgs args)
  {
     Item createdItem = Event.ExtractParameter(args, 0) as Item;
         if (createdItem == null)
           return;

         Log.Info("ITEM CREATED");        
  }
  
  public void OnItemSaving(object sender, EventArgs args)
  {
     Item changedItem = Event.ExtractParameter(args, 0) as Item;
         if (changedItem == null)
           return;
     Log.Info("ITEM SAVING"); 
  }

  public void OnItemSaved(object sender, EventArgs args)
  {
     Item changedItem = Event.ExtractParameter(args, 0) as Item;
         if (changedItem == null)
           return;
     Log.Info("ITEM SAVED");
  }
}

There are 2 issues here:

  1. In the OnItemCreated method, the createdItem is always null. But in quick watch, I can see the created item.
    And so, the Log.Info method is never getting executed here.
  2. After the OnItemCreated, the OnItemSaving method is triggered and then the OnItemSaved. Both the save methods get the item data. But these two methods are triggered twice.

So, the logs are like:

2023-07-04 10:00:01 ITEM SAVING
2023-07-04 10:00:02 ITEM SAVED
2023-07-04 10:00:03 ITEM SAVING
2023-07-04 10:00:04 ITEM SAVED

enter image description here

1 Answer 1

2

Instead of calling

 Item createdItem = Event.ExtractParameter(args, 0) as Item;

use the following code:

ItemCreatedEventArgs itemCreatedEventArgs = Event.ExtractParameter<ItemCreatedEventArgs>(args, 0);
var createdItem = itemCreatedEventArgs.Item;

OnItemSaving and OnItemSaved methods are executed twice because of how Sitecore works:

  • first item is created only with name and template - that's then first set of events is triggered
  • then other item fields are set - that's when events are triggered again.
1
  • Thank you. That worked!!!
    – sukesh
    Jul 4, 2023 at 7:30

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.