0

I want to add multiple UsersID's into a column. Column type is "People and Group". Everytime it's inserted an userid, he smashes the other one, staying only one. Can someone help me? Thank You.

//URL LIST ID
var urllistid = new URLSearchParams(window.location.search);
var listaid = urllistid.get('M_ListID');

//GET SITE URL
var context = new SP.ClientContext();
var relativeWebUrl = context.get_url();
var siteURL = window.location.protocol + '//' + window.location.host + relativeWebUrl ;

//GET USER ID
var UserId = _spPageContextInfo.userId;

//GET ITEM ID FROM URL
var urlParams = new URLSearchParams(window.location.search);
var myParam = urlParams.get('M_ID');

//ADD USERID IN COLUMN "QuemLeu" FROM A SPECIFIC ITEM
var listType = 'SP.Data.' + encodeURIComponent('Páginas') + 'ListItem(myParam)';

jQuery.ajax({
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('Páginas')/items('" + myParam +"')?$select=ID,Title,QuemLeu/Id&$expand=QuemLeu",
    method: "GET",
    headers: {
        "Accept": "application/json; odata=verbose" 
    },
    success: function (data) {
        var userIdArray = [];
        if(data.d){
            if(data.d.QuemLeu.results) {
                for (var i = 0; i < data.d.QuemLeu.results.length; i++) {
                    userIdArray.push(data.d.QuemLeu.results[i].Id);
                }
            }
        }
        userIdArray.push(UserId);
        var fields = {
            "__metadata": { 'type': listType},
            "Title": "teste",
            "QuemLeu": {"results": userIdArray }
        }
        updateItem(fields);
    },
    error: function (error) {
        console.log(error);
    }
});

function updateItem(fields) {
    jQuery.ajax({  
        url: siteURL + "/_api/web/lists/GetByTitle('Páginas')/items('" + myParam +"')",  
        type: "POST",  
        headers: {  
            "Accept": "application/json;odata=verbose",
            "X-RequestDigest" : document.getElementById("__REQUESTDIGEST").value,
            "X-HTTP-Method": "MERGE",
            "If-Match": "*"  
        },  
        data: JSON.stringify(fields),  

        success: function(data) {  
            console.log(data.d.results);  
        },  
        error: function(error) {  
            console.log(JSON.stringify(error));  
        }  
    });
}
  • First of all you need to get the collection of all previous users added in that field and then add current user id in that collection and update that item. – Ganesh Sanap Dec 13 '18 at 14:00
  • @GaneshSanap Ok, How Can I possible do that? – KmDroid Dec 13 '18 at 14:06
  • @GaneshSanap I edit my post with the recent code, is something wrong with it, could you please try to reproduce in your side and test it? Where it is written "Páginas" is the name of the list "Pages" from sharepoint and "QuemLeu" is the name of the column of type "Person Group". Displays this error "return originalSend.apply(this, arguments);" Thank you! – KmDroid Dec 14 '18 at 10:45
  • At which line and in which file it is throwing this error? – Ganesh Sanap Dec 14 '18 at 10:52
  • @GaneshSanap I think it is ajax.ts:153 – KmDroid Dec 14 '18 at 11:24
0

I think you must send data to endpoint in following format:

var fields = {
    "__metadata": { 'type': listType},
    "Title": "teste",
    "QuemLeuId": {
       "results": [
         UserId, OtherId1, OtherId2
       ]
    }
}

You must pass array in results property.

  • Hello, i've this "var UserId = _spPageContextInfo.userId;" to get the current userId, how can I post the current user in "results": [ UserId, OtherId1, OtherId2 ] I only have one variable, how can I add multiple userId's using one variable? – KmDroid Dec 13 '18 at 12:30
  • Please see Ganesh Sanap answer. I think it is what you want. – user80188 Dec 13 '18 at 15:04
0

Here is a demo for your reference, multiple user id needs to pass an array collection with user id like below:

<script type="text/javascript">
var item = {
        "__metadata": { "type": 'SP.Data.MyList3ListItem'},
        "Title": "alue change",
          "QuemLeuId": {"results": [12,9] }

    };

$.ajax({  
    url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/GetByTitle('MyList3')/items",  
    type: "POST",  
    headers: {  
        "accept": "application/json;odata=verbose",  
        "X-RequestDigest": $("#__REQUESTDIGEST").val(),  
        "content-Type": "application/json;odata=verbose"  
    },  
    data: JSON.stringify(item),   
    success: function(data) {  
        console.log(data.d);  
    },  
    error: function(error) {  
        alert(JSON.stringify(error));  
    }  
});  
</script>

Here is the returned Json:

enter image description here

0

Try Using below Code:

function veruser(){

    //URL LIST ID
    var urllistid = new URLSearchParams(window.location.search);
    var listaid = urllistid.get('M_ListID');

    //GET THE LIST NAME FROM LIST ID
    var lista;
    var clientContext = SP.ClientContext.get_current();
    oList = clientContext.get_web().get_lists().getById(listaid);
    clientContext.load(oList,"Title");
    clientContext.executeQueryAsync(
    Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed));
    function onQuerySucceeded(sender, args) {
        lista = this.oList.get_title();
    }

    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
    //END GET THE LIST NAME FROM LIST ID    

    //GET SITE URL
    var context = new SP.ClientContext();
    var relativeWebUrl = context.get_url();
    var siteURL = window.location.protocol + '//' + window.location.host + relativeWebUrl ;

    //GET USER ID
    var UserId = _spPageContextInfo.userId;

    //GET ITEM ID FROM URL
    var urlParams = new URLSearchParams(window.location.search);
    var myParam = urlParams.get('M_ID');

    //ADD USERID IN COLUMN "QuemLeuId" FROM A SPECIFIC ITEM
    var listType = 'SP.Data.' + encodeURIComponent(lista) + 'ListItem(myParam)';

    jQuery.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + lista +"')/items('" + myParam +"')?$select=ID,Title,QuemLeuId/Id&$expand=QuemLeuId",
        method: "GET",
        headers: {
            "Accept": "application/json; odata=verbose" 
        },
        success: function (data) {
            var userIdArray = [];
            if(data.d){
                if(data.d.QuemLeuId.results) {
                    for (var i = 0; i < data.d.QuemLeuId.results.length; i++) {
                        userIdArray.push(data.d.QuemLeuId.results[i].Id);
                    }
                }
            }
            userIdArray.push(UserId);
            var fields = {
                "__metadata": { 'type': listType},
                "Title": "teste",
                "QuemLeuId": {"results": userIdArray }
            }
            updateItem(fields);
        },
        error: function (error) {
            console.log(error);
        }
    });

    function updateItem(fields) {
        $.ajax({  
            url: siteURL + "/_api/web/lists/GetByTitle('" + lista +"')/items('" + myParam +"')",  
            type: "POST",  
            headers: {  
                "Accept": "application/json;odata=verbose",
                "X-RequestDigest" : $("#__REQUESTDIGEST").val(),
                "X-HTTP-Method": "MERGE",
                "If-Match": "*"  
            },  
            data: JSON.stringify(fields),  

            success: function(data) {  
                console.log(data.d.results);  
            },  
            error: function(error) {  
                console.log(JSON.stringify(error));  
            }  
        });
    }
}
  • Seems to be working but display this error "$ is not a function" in this line " "X-RequestDigest" : $("#__REQUESTDIGEST").val()," when I write in web console. – KmDroid Dec 13 '18 at 15:58
  • You need to add jquery file for that. Also you can use document.getElementById("__REQUESTDIGEST").value instead of $("#__REQUESTDIGEST").val() – Ganesh Sanap Dec 13 '18 at 17: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.