Thursday, 8 August 2013

Preventing multiple events from triggering when adding a list item or document to a SharePoint list

Normally what happens is developer's use both Item Added and Item Updated events when they want to execute some specific code across just added list item, in result multiple list events triggers.

For example when a user adds a document to a document library first event triggers is Item Added when document is added to list, whereas second event occurs when user is forwarded to /Forms/EditForm.aspx?Mode=Upload  and user can change item's meta data.

You can prevent it by checking if added item is changed after being added to library/list or not using SPItemEventProperties.Versionless property.

For example (SharePoint 2007):

    class myEventReceiverClass: SPItemEventReceiver
    {
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            try
            {
                this.DisableEventFiring();

                // Only Execute if item hasn't been changed in edit form
                if (!properties.Versionless)
                    ExecuteMyCode(properties);
            }
            finally
            {
                this.EnableEventFiring();
            }
        }
    }


For SharePoint 2010 and 2013 it is recommended to use EventFiringEnabled for getting and setting event firing as shown in example below;

         public override void ItemUpdated(SPItemEventProperties properties)
        {
            this.EventFiringEnabled = false;
            properties.ListItem.Update();
            this.EventFiringEnabled = true;
        }

No comments:

Post a Comment