2

I am using jQuery to query a Sharepoint 2013 list and expanding the AssignedTo field (which is a Person or Group field type) in order to get the user id. I was able to get the code working when the AssignedTo field only allowed one person, but when I changed it to allow multiple persons the code failed. This is the url I used for the single user but I don't have any idea of how I need to change this to get multiple assigned to users.

http://collab.micron.com/mfg/TrecMan/_api/Web/Lists/GetByTitle('DEBUG - PLOT Compliance Exceptions')/items?$select=Id,AssignedTo/Title,Title,Comment,Exception_x0020_Type&$expand=AssignedTo/Title&$filter=(Status ne 'Closed' and Status ne 'Closed By System')&$top=5000

I would be OK with getting a string with all the user names if that is the only possibility. Once I get a valid url then I would need to step through the data. This is the code I am using to display the data in a jQuery datatable, so I'll have to know how the data is structured in order to be able to dig down and get all the user names.

        var call = $.ajax({
        async: false,
        url: _spPageContextInfo.webAbsoluteUrl 
            + "/_api/Web/Lists/GetByTitle('DEBUG - PLOT Compliance Exceptions')/items"
            + "?$select=Id,AssignedTo/Title,Title,Comment,Exception_x0020_Type"
            + "&$expand=AssignedTo/Title"
            + "&$filter=(Status ne 'Closed' and Status ne 'Closed By System')" 
            + "&$top=5000",
        type: "GET",
        dataType: "json",
        headers: {
            Accept: "application/json;odata=verbose"

        }

    });
    call.done(function(data, textStatus, jqXHR) {

        $('#issuesDataTable').dataTable({
            "bLengthChange": false,
            "bDestroy": true,
            "bProcessing": true,
            "aaData": data.d.results,
            "aoColumns": [
                {
                    "mData": "Id",
                    "fnRender": function(obj) {
                        var href = _spPageContextInfo.webAbsoluteUrl 
                            + '/Lists/DEBUG  PLOT Compliance Exception List/EditForm.aspx?IsDlg=1&ID=' 
                            + obj.aData.Id;
                        //return '<a href="' + href + '">' + obj.aData.Id + '</a>';
                        return '<a href="#" onclick="openInDialog(0,0,true,true,true,\'' + href + '\');">' + obj.aData.Id + '</a>';
                    }
                },
                {
                    "mData": "AssignedTo",
                    "fnRender": function(obj) {
                        if(obj.aData.AssignedTo.Title) {
                            var str = obj.aData.AssignedTo.Title.toString();
                            return str;
                        } else {
                            return "NA";
                        }
                    }
                },
                {"mData": "Title"},
                {"mData": "Comment"},
                {"mData": "Exception_x0020_Type"}

            ]

        });
    });
    call.fail(function(jqXHR, textStatus, errorThrown) {
        alert("Error retrieving Tasks: " + jqXHR.responseText);
    });

Thanks

Edit

Clarified that the field type was "Person or Group" not a Choice

Edit

Updated code that works

var results = '';
if(obj.aData.AssignedTo.results.length>0) {
    $.each(obj.aData.AssignedTo.results, function(key,item) {
        results += '<p>' + item.Title + '</p>';
    });
} else {
    results = 'NA';
}
return results;
2

Since AssignedTo is a multi-user field, you'd receive an array. You can then loop into the array and receive specific properties such as title or id. Make sure the properties are in the $select.

See the example below:

 var call = $.ajax({
    async: false,
    url: _spPageContextInfo.webAbsoluteUrl 
    + "/_api/Web/Lists/GetByTitle('Tasks')/items"
    + "?$select=Id,AssignedTo/Id, AssignedTo/Title,Title"
    + "&$expand=AssignedTo/Id"
    + "&$top=5000",
    type: "GET",
    dataType: "json",
    headers: {
      Accept: "application/json;odata=verbose"

    }
});

call.done(function(data, textStatus, jqXHR) {
    var items = data.d.results;

    for (var i = 0; i < items.length; i++) {
      var itemId = items[i].Id;
      var itemTitle = items[i].Title;
      window.console && console.log('ID:' + itemId);
      window.console && console.log('Title' + itemTitle);
      window.console && console.log('Assigned To: \n');
      var assignedToArray = items[i].AssignedTo.results;
      for (var j = 0; j < assignedToArray.length; j++) {
        var userName = assignedToArray[j].Title;
        var userId = assignedToArray[j].Id;
        window.console && console.log(userId + ' - ' + userName);
      }
      window.console && console.log('\n');
    }
});
  • This looks promising but items[i].AssignedTo.results is undefined. Possibly it has a different name or deeper in the object? – Matt Dec 9 '14 at 16:46
  • I think there is something about accessing the array this way that doesn't wait for the deferred promise, but using $.each(obj.AssignedTo.results,... works. – Matt Dec 9 '14 at 18:13
  • Since the field is "Person or Group" how do you distinguish between a user and a group item? – user623396 Feb 13 '15 at 15:17
  • One way to distinguish is to get all the groups (name or id) using CSOM's get_siteGroups() function and store it in array then compare the ids using $.inArray – Aveenav Feb 13 '15 at 22:09
1

What you have seems to work just fine for me with a similar list (using AssignedTo field with multiple selections, filter on a list criterea, and use of $Top)

Something to remember, is that when you have a field that allows multiple selections, your JSON result object for that field is actually an array, even if it only contains one object.

So in your code where you say:

var str = obj.aData.AssignedTo.Title.toString();

You need to loop through each item in the array to get the title out because your data actually looks something like this

d: {
    "results": [{
        "AssignedTo": {
            "results: [{"Title": "User1"}, {"Title": "User2"}]
        },{
        "AssignedTo": {
            "results: [{"Title": "User1"}, {"Title": "User2"}]
        }
        ...
    }

So what you would need to do with it in `fnRender something like this:

...
"mData": "AssignedTo",
"fnRender": function(obj) {
    var results;
    if (obj.aData.AssignedTo.results.length > 0) {
        results = $.map(obj.aData.AssignedTo.results, function(item, index) {
            return item.Title;
        });
        return results.toString();
    } else {
        return "NA";
    }
}
...

You can change the return results.toString() back to just results if you just want the array.

I actually couldn't reverse engineer how your data is structured based on your example, so to get the actual truth on what your response looks like you should open your browser dev tools on a page with jQuery loaded and feed it the following:

var options = { url: "http://collab.micron.com/mfg/TrecMan/_api/Web/Lists/GetByTitle('DEBUG - PLOT Compliance Exceptions')/items?$select=Id,AssignedTo/Title,Title,Comment,Exception_x0020_Type&$expand=AssignedTo/Title&$filter=(Status ne 'Closed' and Status ne 'Closed By System')&$top=5000", 
                headers: { "Accept": "application/json;odata=verbose" }
            };

$.ajax(options)
    .then(function(data) { console.log(data) })
    .fail(function(jqXHR) { console.log("There was an error: " + jqXHR.responseText) });

This will log the response payload to your browser dev tools as a JS Object that you can expand and root through to see the exact structure.

  • I may have used a slightly unclear terminology. The AssignedTo field is a "Person or Group" field type that allows multiple entries, it is not a multi-select field. When I look at the data as you suggest it only shows the __deferred object. – Matt Dec 9 '14 at 16:49
  • Right - I am using a Person or Group field that allows multiple selections -- the above example works on SharePoint Online for me. You could try modifying your expand statement to $expand=AssignedTo (no /Title) -- but again I'm getting all of the data with a query just like yours – John-M Dec 9 '14 at 16:54
  • I found the error in your example, it should be obj.aData.AssignedTo.results.length>0 then iterate over the results. Thanks – Matt Dec 9 '14 at 18:11
  • Oh - I think that's one of the odata=verbose side effects, corrected the example – John-M Dec 9 '14 at 18:38

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.