Protiviti / SharePoint Blog

SharePoint Blog

October 02
Set List Item field equal to the Current User

Have you ever had the need to set a field on a List Item to the Current User?  Sounds easy enough, but unfortunately there is no built-in mechanism for this functionality.

 

In the screenshot below, notice there is no option to define the User as [Me] for a new Person or Group site column.


MattK1.PNG
 

There are a couple of ways that this can be tackled:


1.       Create a Workflow that runs every time an item is added

2.       Create an EventReceiver on ItemAdded

 

Either of these methods will work, but for this exercise, we are going to implement the Event Receiver. 

 

Here is how the Event Receiver is created:

 

In Visual Studio, Click Project and Add New Item.

Select Event Receiver

 

Add the following code to override the default ItemAdded method:


MattK2.PNG

The method above will override the ItemAdded method so that additional functionality can be added to the process.  The first line runs the ItemAdded method from the base class so that all of the out of the box ItemAdded functionality occurs.

 

Next, we disable Event Firing while the updates are made.

 

The field that I want to set is called Requester and it has been configured as a People or Group field.  There is a List Item field called Author that is created by default in the base Item Content Type that is passed down to all content types and lists.  The Author field is what we will use to accomplish our task.  Simply set the desired field equal to the Author field, update the List Item, enable Event Firing again and the code part is done!

 

The last thing that needs to be done is to update the Elements.xml file in the Visual Studio project so that the Event Receiver is connected to the correct List.


Open the Elements.xml page in the Receiver item and add the following declaration:


MattK3.PNG
 

All that is left to do is build and deploy your code and try it out.  Add an item to your List and you will see the Requester field has the name of the current User!



Quick Launch


© Protiviti 2019. All rights reserved.   |   Privacy Policy