Wednesday, November 16, 2011

Event handler to archive items when deleted

A person just asked this on a mailing list I am on, so I thought I'd share this code. The requirement - copy a list item that is deleted to an archive list. The solution - event receiver that copies the item. The code below does the job, but again is only a sample - you still need to implement error handling, and there are hard coded variables there you will want to change.
Note: this code is specifically for list items, not for documents in document libraries. You can easily change the code to support documents as well (see the CopyAttachments function for an example on how to copy files).

public override void ItemDeleting(SPItemEventProperties properties)
           //note: may require permission elevation.
           //TODO: add error handling

           //get the item being deleted
           SPListItem item = properties.ListItem;
           //get the target list
           SPList targetList = properties.Web.Lists["Announcements Archive"];
           //create the new item
           SPListItem newItem = targetList.Items.Add();
           //copy the list item to the target
           foreach (SPField f in item.Fields)
                if (!f.ReadOnlyField && newItem.Fields.ContainsField(f.InternalName))
                    newItem[newItem.Fields.GetFieldByInternalName(f.InternalName).Id] = item[f.Id];   
           //copy "special" read only fields that can be written to
           newItem["Created By"] = item["Created By"];
           newItem["Modified By"] = item["Modified By"];
           newItem["Modified"] = item["Modified"];
           newItem["Created"] = item["Created"];
           CopyAttachments(item, newItem);

Note - for the "CopyAttachments" I used code that I published in the past:

No comments: