Creating a custom view that filters on the current user or [Me]

 

Earlier this week I was creating custom list views for a customer solution. On of the specifications was that the view needed a filter that only showed the documents that were created by the current user. You can do this using the user interface by specifying that the Created By field needed to be equal to [Me].

 

Filter view by current user

 

I was trying to get this same behaviour by adding a CAML query to my view  using the following code:

 

StringCollection viewFields = new StringCollection();
viewFields.Add("Title");
viewFields.Add("Description");
SPView newView = myDocLib.Views.Add("My documents", viewFields, "<Where><Eq><FieldRef Name='Author' /><Value Type='User'>[Me]</Value></Eq></Where>", 100, true, false);

 

This didn't work, but when I opened the view and saved it again it did work. I tried to search the internet by looking for "sharepoint, spview, [Me]" and I couldn't find a soluton, which is the reason for this post.

Eventually I posted my question on the MSDN forums http://social.msdn.microsoft.com/Forums/en-US/sharepointdevelopment/thread/a4c20e84-4201-4106-9568-df3cfbcd5d3b/ and after only a couple of minutes Dave Hunter  came back with the answer. The correct way to define a view that filters based on the current user using the object model is:

 

StringCollection viewFields = new StringCollection();
viewFields.Add("Title");
viewFields.Add("Description");
SPView newView = myDocLib.Views.Add("My documents", viewFields, "<Where><Eq><FieldRef Name='Author' /
><Value Type="Integer"><UserID Type="Integer"/></Value></Eq></Where>", 100, true, false);

 

Dave also gave the great tip that you can find the CAML for a specific view by doing the following:

  • Define the view using the user interface
  • Save the list as a template
  • Download the template
  • Rename the .stp file to .cab
  • Extract the manifest.xml from the .cab file and find the <Query> definition

 

Thanks again Dave!