Total Pageviews

18 Jan 2014

Check if a Field was Changed Inside ItemUpdated Handler of a List EventReceiver

I think, I found the easiest way to check if a particular field was changed inside ItemUpdated handler. Here is what you should do:
  1. Add a new hidden field to the list.
  2. Register a new EventReceiver for ItemUpdating. It will save previous field values.
  3. In ItemUpdating save a field value from before properties of the field to afterProperties of the hidden field.
  4. In ItemUpdated compare afterProperties of the wanted field with the after properties of the hiddenField
2. Registering event receivers inside a feature receiver with the web scope:


 private static void AddEventReceivers(SPFeatureReceiverProperties properties)
        {
            SPWeb web = (SPWeb) properties.Feature.Parent;
            string assembly = Assembly.GetExecutingAssembly().FullName;

            web.AllowUnsafeUpdates = true;

            SPList list = GetTheListSomehow();
            SPEventReceiverDefinition ERDefinitionUpdated = list.EventReceivers.Add();
            ERDefinitionUpdated.Assembly = assembly;
            ERDefinitionUpdated.Class = typeof(Event_Receiver_Class).FullName;
            ERDefinitionUpdated.Type = SPEventReceiverType.ItemUpdated;
            ERDefinitionUpdated.Name = "ClipsEventReceiverItemUpdated";
            ERDefinitionUpdated.Update();

            SPEventReceiverDefinition ERDefinitionUpdating = list.EventReceivers.Add();
            ERDefinitionUpdating.Assembly = assembly;
            ERDefinitionUpdating.Class = typeof(Event_Receiver_Class).FullName;
            ERDefinitionUpdating.Type = SPEventReceiverType.ItemUpdating;
            ERDefinitionUpdating.Name = "ClipsEventReceiverItemUpdating";
            ERDefinitionUpdating.Update();
}


3. ItemUpdating EventReceiver:

public override void ItemUpdating(SPItemEventProperties properties)
{
    //warning: you should check if the field is not null
    properties.AfterProperties["hiddenFieldName"] = properties.ListItem["fieldName"];
}
warning: do not try to save values straight the hidden field. You should use afterProperties instead like is shown above.

4. ItemUpdated EventReceiver:

public override void ItemUpdated(SPItemEventProperties properties)
{
   string oldfieldValue = properties.ListItem["hiddenField"];

    //simplified example. you should check for nulls and maybe use a better way of comparing field values
   if (String.Equals(oldfieldValue, properties.AfterProperties["fieldName"]))
   {
       return;
   }
   //some code...
}



No comments:

Post a Comment