Tuesday, March 1, 2011

SharePoint 2010: Approve/Reject Content Programmatically with SharePoint Object Model

In SharePoint 2010, you can modify the moderation status (approve/reject) of an item programmatically. Once you have got the ListItem, you can access the ModerationInformation properties to know the status, as shown below:

SPListItem listItem = GetListItem();
var moderationInformation = listItem.ModerationInformation;
if (moderationInformation != null)
{
if (moderationInformation.Status == SPModerationStatusType.Approved)
{
//approved
}
else if (moderationInformation.Status == SPModerationStatusType.Denied)
{
//rejected
}
else if (moderationInformation.Status == SPModerationStatusType.Draft)
{
//item is in edit mode and yet send to pending state.
}
else if (moderationInformation.Status == SPModerationStatusType.Scheduled)
{
//approval is waiting to be processed by a timer service.
}
}

However, Remember to check the ModerationInformation for null. If versioning/content approval is not enabled then the moderationinformation will be null. You can modify the moderation status by editing the moderationinformation and updating the list item as shown below:

SPListItem listItem = GetListItem();
if (listItem.ModerationInformation != null)
{
listItem.ModerationInformation.Status = SPModerationStatusType.Approved;
listItem.ModerationInformation.Comment = "This is comment";
listItem.Update();
}

Hope someone will get this useful!

8 comments:

  1. Thanks a lot! very clear and useful!
    Just one note: if you update a metadata of the item at the same time, it will throw an exception. You have to do it one by one, i.e. change metadata, then call listItem.Update(), change moderation status and then call listItem.Update() again.

    ReplyDelete
  2. Thanks a lot.... useful for my project...

    ReplyDelete
  3. how to get moderation status field in client object model?

    ReplyDelete
  4. This doesn't work in 2007. The item remains in a "Pending" status.

    ReplyDelete
  5. @Peter, it should work with SP 2007. Do you have any event receiver that's making some changes and as a result the item is back to pending status?

    ReplyDelete
  6. Hi, Do you know how make the same but in Javascript?

    ReplyDelete