3

I have a list called Teams that has 2 columns, 'Title' and 'Team Members'. Team Members is a Person or Group Field that allows multiple values. There are 3 Teams defined in the list with multiple users in each team. I am a member of 2 of the teams.

What I am trying to do is query this list and return only the Teams that the current user is a member of. I have attempted to do this with REST and with JavaScript SharePoint Client context. Here's what I have so far.

REST API Attempt

    function GetTeams(userId) {
    var res;
    var requestURL = config.SiteURL + '/_api/web/lists/GetByTitle(\'' + config.Library + '\')/items?$select=Title,Team_x0020_MembersId';
    $.ajax({
        url: requestURL,
        headers: {
            Accept: 'application/json;odata=verbose'
        },
        method: 'GET',
        //Success Function
        success: function (data) {
            res = data.d.results;
            console.log('This is a list of all the teams');
            console.log(res);
            var teammembers = res[0].Team_x0020_MembersId.results;
            console.log('This is just the Team Member IDs of the first team in the array ' + teammembers);
        },
        //Error Function
        error: function (jQxhr, errorCode, errorThrown) {
            res = jQxhr;
            console.log(res);

        },
        dataType: 'json' //Make me a JSON
    });
};

This will return all the teams. I have tried to use $filter=Team_x0020_MembersID eq userID with no success.

CLIENT CONTEXT ATTEMPT

var ctx;
var web;
var user;
var teams;
var items;

function sharePointReady(){
  var cQuery = new SP.CamlQuery();

  ctx = SP.ClientContext.get_current();
  web=ctx.get_web();
  ctx.load(web);
  user=web.get_currentUser();

  teams = web.get_lists().getByTitle('Teams');
  cQuery.set_viewXml("<View><Where><Includes><FieldRef Name='Team_x0020_Members' LookupId='TRUE'/><Value Type='Integer'>9057</Value></Includes></Where></View>");

  items = teams.getItems(cQuery);
  ctx.load(items);
  console.log(items);
  console.log(cQuery);
  ctx.executeQueryAsync(onRequestSucceeded, onRequestFailed);

}
function onRequestSucceeded() {
    console.log('current user id ' + user.get_id());

    var itemInfo='';
    var TeamMembers;
    var itemEnumerator = items.getEnumerator();
    while(itemEnumerator.moveNext()){
        var li = itemEnumerator.get_current();
        itemInfo += '\n' + li.get_id();
        itemInfo += '\t' + li.get_item('Title');
        itemInfo += '\t' + li.get_item('Team_x0020_Members');
        TeamMembers=li.get_item('Team_x0020_Members');
        console.log('Team Member Array');
        console.log(TeamMembers);
        console.log('Individual Team Members');
        for(i=0; i< TeamMembers.length;i++)
            {
                console.log(TeamMembers[i].$1E_1);
            }

    }
}

function onRequestFailed(sender, args) {
    console.log('Error: ' + args.get_message());
}
console.clear();
sharePointReady();

This again returns all 3 teams instead of just the 2 teams that the current user (me) is a member of.

In short.. does anyone know what I'm doing wrong and can you help me query just the teams that the current logged in user is a member of?

4

You could construct the following CAML query to return only the Teams that the current user is a member of:

<Or>
  <Membership Type=\"CurrentUserGroups\">
    <FieldRef Name=\"Team_x0020_Members\"/>
  </Membership>
  <Eq>
    <FieldRef Name=\"Team_x0020_Members\"></FieldRef>
    <Value Type=\"Integer\">
      <UserID/>
    </Value>
  </Eq>
</Or>

Follow Membership Element (Query) for a more details

REST example

Both REST and JSOM APIs supports CAML queries, the below example shows how to utilize CAML query via REST endpoint:

var listTitle = "Teams";

var url = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getitems";
var queryXml = "\
<View> \
   <Query> \
      <Where> \
          <Or> \
            <Membership Type=\"CurrentUserGroups\">  \
                <FieldRef Name=\"Team_x0020_Members\"/> \
            </Membership> \
            <Eq> \
                <FieldRef Name=\"Team_x0020_Members\"></FieldRef> \
                   <Value Type=\"Integer\">  \
                        <UserID/> \
                   </Value> \
           </Eq>  \
         </Or> \
      </Where> \
   </Query> \
</View>";


var queryPayload = { 
       'query':{ 
           '__metadata': { 'type': 'SP.CamlQuery' },
           'ViewXml': queryXml
        } 
}; 



executeJson({
        "url" :url,
        "method": 'POST',
        "data": queryPayload})
.done(function(items)
{
    items.d.results.forEach(function(item){
        console.log(item.Title); 
    });
})
.fail(function(error){
    console.log(JSON.stringify(error));
});

where

function executeJson(options) 
{
    var headers = options.headers || {};
    var method = options.method || "GET";
    headers["Accept"] = "application/json;odata=verbose";
    if(options.method == "POST") {
        headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
    }   

    var ajaxOptions = 
    {       
       url: options.url,   
       type: method,  
       contentType: "application/json;odata=verbose",
       headers: headers
    };
    if("data" in options) {
      ajaxOptions.data = JSON.stringify(options.data);
    }  

    return $.ajax(ajaxOptions);
}
  • 1
    Very concise and it works great. Thank you for the response I should be able to modify this to my needs nicely! – Brad Fortner Oct 18 '16 at 18:23
-1

Try this:

First get the current user Login name using the below function

var UserName;
function CallClientOM()
{
var context = new SP.ClientContext.get_current();
this.website = context.get_web();
this.currentUser = website.get_currentUser();
context.load(currentUser);
context.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}



function onQuerySucceeded(sender, args)
 {
 alert(currentUser.get_loginName());
 UserName = currentUser.get_loginName()
 }

Then apply filter as follows:

$filter=='Your Internal field name for Team Members' eq 
               'UserName'"

Hope that helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.