Wednesday, June 27, 2012

How to change the values of 'CreatedBy' and 'ModifiedBy' fields in SharePoint list

Each SharePoint list by default has these fields 'Created By' and 'Modified By'. The type of these fields is "Person or Group".
Whenever a new list item is added, the value of the 'CreatedBy' column is automatically set to the Login Name of current user.  
And whenever a list item is modified, the value of the 'ModifiedBy' column is automatically set to the Login Name of current user.   
 
Note: If you try to modify or update the 'CreatedBy and 'ModifiedBy' Fields, you may get the below error like   "Invalid data has been used to update the list item. The field you are trying to update may be read only". 

 
Now the question is "why the hell one needs to modify the values of these fields?” The answer can be found in the "Advanced Settings" section of a SharePoint list. One can see, there is a 'Edit own items' permission which means a user can edit all list items which he/she has created, that is very nice and useful feature. But the problem is that it is linked with the 'Created By' field. So if I will create a list item then my login name will be stored in the "Created By" field and only I can modify this list item. But if there is a requirement to modify this list item by some other user then how I can achieve that. To achieve this, one need to modify the value of "Created By" field and set it to the login name of that user. But How? 
I was just stuck with this problem, but finally found a solution. The values of 'Created By' and 'Modified By' fields can be modified programmatically. Here is a code snippet to achieve this: 

Method1:
using (SPSite site = new SPSite("SharepointSiteURL"))
  using (SPWeb web = site.OpenWeb())
  {
    web.AllowUnsafeUpdates = true;
    SPList list = web.Lists["ListName"];
    foreach (SPListItem item in list.Items)
    {
      SPUser user = web.EnsureUser("User'sLoginName");
      //In the "Created By" and " Modified By" fields values are stored in this format      "ID;#LoginName", so create the same format.
 
      string userValue = user.ID + ";#" + user.Name;
      item["Author"] = userValue ;
       //InternalName of "Created By" field is "Author"
      item["Editor"]=userValue ; 
      //InternalName of "Modified By" field is "Editor"
      item.Update(); 
    }
    list.Update();
}
Method2:

using (SPSite site = new SPSite("SharepointSiteURL"))
  using (SPWeb web = site.OpenWeb())
  {
      web.AllowUnsafeUpdates = true;
      SPList list = web.Lists["ListName"];
      SPListitemCollection itemcollection=list.items;
      foreach (SPListItem item in itemcollection)
      {
         SPFieldUserValue user1=new SPFieldUserValue(web, web.CurrentUser.ID,
                                      web.CurrentUser.LoginName);
        Listitem[“Author”]=user1;
        Listitem[“Editor”]=user1;
     }
  }
}

No comments:

Post a Comment