locked
Update data for Peoplepicker value using REST and Javascript model RRS feed

  • Question

  • HI.

    I have a custom list having 2000+ entries. In the list I have a people picker and based on people picker data, the job title of the user is set in a single line text column.

    I am trying to update the data in the list, based on role changes for people whose status is "Set On" . Is this correct ?

    <script src="/sites/SiteAssets/Jquery/jquery-1.11.3.min.js"></script>
    <script src="/sites/SiteAssets/Jquery/jquery.SPServices.min.js"></script>
    <script type="text/javascript">
    	
    	$(document).ready(function() {
    		
    var siteURL = _spPageContextInfo.webAbsoluteUrl;
    var controlName 	= "Users ID";
    var destlistname = "my%20Actions%20tracker"
    		
     var resurl1 = siteURL + "/_api/web/lists/getbytitle('" + destlistname + "')/items?$filter=Resource_Status eq '" + Set On + "'";
    $.ajax({
    url: resurl1,
    method: "GET",
    headers: { "Accept": "application/json; odata=verbose" },
    
    success: function (data) {	 	 
    var items = data.d.results;
    if(items.length > 0){
    
    for (i = 0; i < items.length; i++) {										  var ppDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");	
    
     var ppEditor = ppDiv.find("[title='" + controlName + "']");	
    
     var spPP 	= SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv[0].id];
    
    if (!spPP.HasInputError) 
    {
    var userKeys = spPP.GetAllUserInfo();
    														var myUser = userKeys[0];										var textValue = userKeys[0].EntityData.Title;								findFormFieldTd('Career level').find("input").val(textValue);
    	}
    	}
    	}
    else
    {
    }
    },
    	error: function (data) {
    alert(data.responseText);		
    }
    	});
    					
    function findFormFieldTd(columnName) {
                var thisFormBody;
                // There's no easy way to find one of these columns; we'll look for the comment with the columnName
                var searchText = RegExp("FieldName=\"" + columnName.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&") + "\"", "gi");
                // Loop through all of the ms-formbody table cells
                $("td.ms-formbody, td.ms-formbodysurvey").each(function () {
                    // Check for the right comment
                    if (searchText.test($(this).html())) {
                        thisFormBody = $(this);
                        // Found it, so we're done
                        return false;
                    }
                });
                return thisFormBody;
            }
    		
    });
    </script>

    Thanks

    Friday, December 27, 2019 9:18 AM

All replies

  • Hi Venkatzeus,

    Do you want to update the "Career level" field with the value of "Users ID" People field for all list items(Resource_Status is "Set On")?

    I suggest you provide more information and some screenshots about your requirement for further research.

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Monday, December 30, 2019 2:21 AM
  • Yes. I want to update the career level field for all list items whose resource_status is "Set On"
    Monday, December 30, 2019 6:06 AM
  • Hi,

    The following example code for your reference.

    <script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
    <script type="text/javascript" src="_layouts/15/clienttemplates.js"></script>  
    <script type="text/javascript" src="_layouts/15/clientforms.js"></script>  
    <script type="text/javascript" src="_layouts/15/clientpeoplepicker.js"></script>  
    <script type="text/javascript" src="_layouts/15/autofill.js"></script>
    <script type="text/javascript">
    $(function(){
    	initializePeoplePicker('UserID');	
    });
    function updateListItem(){
    	var listTitle = "my Actions tracker";
    	var filter="$filter=Resource_Status eq 'Set On'";	 
    	var spPP=this.SPClientPeoplePicker.SPClientPeoplePickerDict.UserID_TopSpan;
    	if (!spPP.HasInputError){
    		var userKeys = spPP.GetAllUserInfo();
    		var textValue = userKeys[0].DisplayText;
    		getListItems(listTitle,filter).done(function(data){
    			$.each(data.d.results,function(i,item){
    				var itemData = {
    					"__metadata": { "type": item.__metadata.type },
    					"Career_level":textValue     
    				};		
    				$.ajax({
    					url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items("+item.ID+")",
    					type: "POST",
    					contentType: "application/json;odata=verbose",
    					data: JSON.stringify(itemData),
    					headers: {
    						"Accept": "application/json;odata=verbose",
    						"X-RequestDigest": $("#__REQUESTDIGEST").val(),
    						"X-HTTP-Method": "MERGE",
    						"If-Match": "*"
    					},
    					success: function (data) {
    						console.log('Success');
    						//window.location.href=window.location.href;
    					},
    					error: function (data) {
    						console.log(JSON.stringify(data));
    					}
    				});
    			});
    		});
    	}	
    }
    function initializePeoplePicker(peoplePickerElementId) {
    	// Create a schema to store picker properties, and set the properties.
    	var schema = {};
    	schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
    	schema['SearchPrincipalSource'] = 15;
    	schema['ResolvePrincipalSource'] = 15;
    	schema['AllowMultipleValues'] = true;
    	schema['MaximumEntitySuggestions'] = 50;
    	schema['Width'] = '280px';
    	this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
    }
    function getListItems(listTitle,filter){
    	var endpointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listTitle+"')/items?"+filter;
        return $.ajax({
    		url: endpointUrl,
    		method: "GET",
    		contentType: "application/json;odata=verbose",
    		headers: {   
    		 "Accept": "application/json;odata=verbose"
    		} 
        });
    }
    </script>
    <p><div id="UserID" title="Users ID"></div></p>
    <p><input type="button" onclick="updateListItem()" value="Update"/></p>

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Monday, December 30, 2019 8:33 AM
  • Hi.

    Thanks for the reply. I created a page in site pages. In the page, added the code in Embed code option.

    when clicking on Update button,

    function updateListItem(){
     var listTitle = "List Name";
     var filter="$filter=Resource_Status eq 'Set-On'";  
    
    var controlName = "User ID (Off)";
    var spPP=this.SPClientPeoplePicker.SPClientPeoplePickerDict.controlName_TopSpan;

    spPP is coming as undefined. This button is created in a separate page and not added in the list.

    How to fix this ?



    • Edited by Venkatzeus Monday, December 30, 2019 1:33 PM
    Monday, December 30, 2019 12:33 PM
  • Hi,

    Please add the code into script editor web part in site page.

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Tuesday, December 31, 2019 1:19 AM
  • Hi.

    Thanks for the reply.

    I want to do for all the list items passing the condition - Resource_status = set on

    The list already contains 1000 rows, for which the data needs to be updated ? Do you mean, in the All items page of the list, i need to use this script?

    Thanks

    Tuesday, December 31, 2019 7:17 AM
  • Hi,

    Please modify the following line of code.

    var filter="$filter=Resource_Status eq 'Set-On'&$top=5000";  

    If you want to get more than 5000 items, please check the article below.

    SharePoint REST API to retrieve more than 5000 items.

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Tuesday, December 31, 2019 7:27 AM
  • Hi Dennis.

    Should the code be added in All Items.aspx page of the list ?

    Tuesday, December 31, 2019 9:39 AM
  • Hi,

    We can also add the code in script editor web part in a new web part page.

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Wednesday, January 1, 2020 1:16 AM
  • Hi.

    I am getting error in this line:

    var spPP=this.SPClientPeoplePicker.SPClientPeoplePickerDict.controlName_TopSpan;

    This is coming as undefined.

    function updateListItem(){
    	var listTitle = "List Name";
    	var filter="$filter=Resource_Status eq 'Set-On'";	 
    	var controlName = "User ID (office)";
    	
    	var spPP=this.SPClientPeoplePicker.SPClientPeoplePickerDict.controlName_TopSpan;

    This is the code used.

    Friday, January 3, 2020 1:00 PM
  • Hi,

    Please use the people picker DIV below.

    <div id="UserID" title="Users ID"></div>

    Then use the code below to get the people picker.

    var spPP=this.SPClientPeoplePicker.SPClientPeoplePickerDict.UserID_TopSpan;

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Monday, January 6, 2020 1:27 AM
  • Thanks for the reply.

    I apologize for the confusion. In the webpart page, I do not want to add a people picker. I have an existing list, which contains the people picker - User ID (office) .

    I want the code to loop through the contents of the list and update the column user role with the updated career levels based on people picker - User ID (office)

    Monday, January 6, 2020 10:06 AM
  • Hi,

    Modify the code as below. In my test, my people list field name is "User ID (office)" and the internal name is "User_x0020_ID_x0020__x0028_offic".

    <script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript"></script>
    <script type="text/javascript">
    function updateListItem(){
    	var listTitle = "my Actions tracker";	 
    	var filter="$select=ID,User_x0020_ID_x0020__x0028_offic/Title&$expand=User_x0020_ID_x0020__x0028_offic/Id&$filter=Resource_Status eq 'Set On'";	
    	getListItems(listTitle,filter).done(function(data){
    		$.each(data.d.results,function(i,item){
    			var userValue=item.User_x0020_ID_x0020__x0028_offic.Title;			
    			var itemData = {
    				"__metadata": { "type": item.__metadata.type },
    				"Career_level":userValue     
    			};		
    			$.ajax({
    				url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items("+item.ID+")",
    				type: "POST",
    				contentType: "application/json;odata=verbose",
    				data: JSON.stringify(itemData),
    				headers: {
    					"Accept": "application/json;odata=verbose",
    					"X-RequestDigest": $("#__REQUESTDIGEST").val(),
    					"X-HTTP-Method": "MERGE",
    					"If-Match": "*"
    				},
    				success: function (data) {
    					console.log('Success');
    					//window.location.href=window.location.href;
    				},
    				error: function (data) {
    					console.log(JSON.stringify(data));
    				}
    			});
    		});
    	});
    		
    }
    function getListItems(listTitle,filter){
    	var endpointUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listTitle+"')/items?"+filter;
        return $.ajax({
    		url: endpointUrl,
    		method: "GET",
    		contentType: "application/json;odata=verbose",
    		headers: {   
    		 "Accept": "application/json;odata=verbose"
    		} 
        });
    }
    </script>
    <input type="button" onclick="updateListItem()" value="Update"/>

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Tuesday, January 7, 2020 8:43 AM
  • Hi.

    Thanks for the reply.

    var userValue=item.User_x0020_ID_x0020__x0028_offic.Title;

    This is giving the user name and not the role of the user.

    How to fix this ?

    Thanks

    Monday, January 13, 2020 1:12 PM
  • Hi.

    Any help on this ?

    Thanks

    Monday, January 20, 2020 9:06 AM
  • Hi,

    If you want to get the user by the user name, we can use the REST API below.

    https://contoso.sharepoint.com/_api/web/siteusers?$filter=Title eq '<Title>'

    Best Regards,

    Dennis


    Please remember to mark the replies as answers if they helped. If you have feedback for TechNet Subscriber Support, contact tnmff@microsoft.com.

    SharePoint Server 2019 has been released, you can click here to download it.
    Click here to learn new features. Visit the dedicated forum to share, explore and talk to experts about SharePoint Server 2019.

    Monday, January 20, 2020 9:11 AM
  • Hi Dennis.

    Thanks for the reply.

    I have to do for all the list items and hence cannot pass every user as input.

    The code should traverse through all items in the list and update the user role ( as the existing users have changes in the career role )

    Monday, January 20, 2020 11:28 AM