Friday 13 April 2012

CAML Query to retrieve data for current user in Sharepoint

While working with SharePoint CAML queries, you will need to get current user data. (Retrieve data from a list, that filtered by current logged in user).

There are couple of ways to achieve this requirement.

1) Filter by current user “Display Name”
<Where>
<Eq>
<FieldRef Name='Person'/>
<Value Type='Text'>Lastname, Firstname</Value>
</Eq>
</Where>

Simply pass the display name of the current user to filter the data. But what if there are multiple users with same display name.

So the above method is not a ideal solution.

2) Filter by current user “User ID” – By Passing the User ID
<Where>
<Eq>
<FieldRef Name='Person' />
<Value Type='Integer'>45</Value>
</Eq>
</Where>

In this method, we pass the current users user id as the parameter and filter the data (45 is the user id of the current user). For this you will need to know the current user id. Retrieving the user id is very simple. But there is another CAML variable that can be used to get current user id.

3) Filter by current user “User ID – User id retrieved from CAML Query it self
<Where>
<Eq>
<FieldRef Name='Person' />
<Value Type='Integer'><UserID/></Value>
</Eq>
</Where>

In this scenario just pass the <UserID/> to the value field in CAML. This will always retrieve the current users user id internally.

No comments:

Post a Comment