Set value of "person" column

Oct 27, 2011 at 11:04 PM

I have been searching all over, and I can't seem to find the answer.

I have successfully added list items with dynamic values using SPServices and JQuery. 

I would like to select a person from the User Information List to populate a "person" field in my list when adding the list item. 

Any ideas on how to go about this? 

Thanks,

Don

Coordinator
Nov 1, 2011 at 4:13 AM

Don:

Check out this blog post and ping back if you need more.
http://sympmarc.com/2010/03/02/query-the-user-information-list-with-jquery-and-web-services/

M.

Nov 1, 2011 at 12:17 PM
Marc,
Thanks.  I actually worked out how to populate the column.  The person column is expecting to be populated with a number (ID lookup from UIL).  One complicating factor was that my ID in "MySite" is different from my ID in the main site. 
 
It's pretty easy to get the current user ID, but now I'm working on a function to search for the person you want (our site has 1,000s of people). 
 
Don
Coordinator
Nov 1, 2011 at 12:19 PM

Yes, the user's ID will be different in every Site Collection. An added wrinkle.

M.

Nov 1, 2011 at 6:34 PM

I found this trick which has allowed me to populate a Person / Group field without having to know the actual ID value.  Simply concatenate -1;# to the beginning of the value. 

Nov 2, 2011 at 8:21 PM

@will266 - Thanks for the tip, I will try and exploit that. 

When I'm trying to search for a person to populate a field, I have tried using <Contains> against the Name field, and supplying the last name as the <Value>, but had not luck.  Should I be appending -1;# in front of the last name?  (We have a strict naming convention for users: LName, FName MI Title etc...).  I have used <Contains> against a different list & (text) field, and it works--even on partial matches.  i.e., search for <Contains> 'Issue' -- returns Issue and Tissue. 

Don

Nov 3, 2011 at 4:41 PM

Not sure why your contains is not working - the tip I included was strictly for when you need to push your value into a Person/Group Field like so (much like I am adding the ID value for items on another list on my site):

function CreateObservation()
{

    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        listName: "{9024B1C9-BB0E-46C5-96D5-F5CEF3FFC296}",
        updates: "<Batch OnError='Continue' PreCalc='TRUE'>" +
                    "<Method ID='1' Cmd='New'>" +
                        "<Field Name='ContentType'>Services</Field>" +
                        "<Field Name='Title'>Please enter Job Description</Field>" +
                        "<Field Name='Observer'>-1;#" + pName + "</Field>" +
                        "<Field Name='Supervisor'>-1;#" + pName + "</Field>" +
                        "<Field Name='Office'>" + officeId + ";#" + office + "</Field>" +
                        "<Field Name='BusinessUnit'>" + companyId + ";#" + company + "</Field>" +
                        "<Field Name='Manager'>-1;#" + mName + "</Field>" +
                        "<Field Name='SafetySpecialist'>" + safeSpecialist + "</Field>" +
                    "</Method>" +
                "</Batch>",
        completefunc: function (xData, Status) {

  
       }

    });
}
Nov 8, 2011 at 9:13 PM

Thanks, Will. 

I am using this code to insert a new list item:

Is there a way to return the ID of the new list item?  I need to update another field in the new item with html link that includes the ID of the entry. 



$().SPServices({
        	operation: "UpdateListItems",
        	async: false,
        	batchCmd: "New",
        	listName: "Project Index",
        	valuepairs: [["Title", MyProjID], ["Test Manager", myProjTMID], ["Project Title", myProjTitle], ["ESP",myProjESP]],
        	completefunc: function(xData, Status) {
          	}
    	});
Coordinator
Nov 8, 2011 at 9:14 PM
Edited Nov 8, 2011 at 9:14 PM

Don:

If you look at the returned XML, you'll see that you get the newly created item's ID.

M.

Nov 8, 2011 at 9:18 PM

Marc is spot on.

Something to parse the xml and create a variable llike:

var newId;

$().SPServices({
        	operation: "UpdateListItems",
        	async: false,
        	batchCmd: "New",
        	listName: "Project Index",
        	valuepairs: [["Title", MyProjID], ["Test Manager", myProjTMID], ["Project Title", myProjTitle], ["ESP",myProjESP]],
        	completefunc: function(xData, Status) {
        	
        	newId = $(xData.responseXML).find("[nodeName=z:row]").attr("ows_ID");

          	}
    	});



Nov 8, 2011 at 9:53 PM

WOW! you guys are fast!  This site (and the people herein) have been immensely helpful...THANKS!

Nov 9, 2011 at 7:20 PM

Guys, how do I visualize the responseXML in its entirety?  

Nov 9, 2011 at 7:30 PM

Something like thisin your complete function:

completefunc: function(xData, Status) {
                $(xData.responseXML).find("QueryResult").each(function() {
               $("#result").text($(this).text());

              });
             }

then after you complete your script (i.e. after </script>) add

<div id=result></div>

or in your completfunc simply alert(xData.responseXML.xml)




        
    
Nov 9, 2011 at 8:18 PM

@Will - Thanks, that will come in handy. 

You guys have helped me to the 95% point...here is the remaining 5%:    The "CreateProject()" function works great.  However, the "UpdatePlink()" function is not updating the newID record...nor is it throwing an error.   The PLink is an image icon (href) that is part of our site functionality, and must contain the item's ID as the querystring. 

var myProjID;
var myProjTitle;
var myProjESP;
var mynewID;

function CreateIt()
	{
	CreateProject();
	UpdatePlink();
	}

function CreateProject()
	{
	var pid = new String( $().SPServices.SPGetCurrentUser({ fieldName: "ID" }));
	$().SPServices({
        	operation: "UpdateListItems",
        	async: false,
        	listName: "Project Index",
	batchCmd: "New",
        	valuepairs: [["Title", myProjID], ["Project_x0020_Title", myProjTitle], ["Test_x0020_Manager", pid], ["ESP", myProjESP]],
        	completefunc: function(xData, Status) {
          		mynewID = $(xData.responseXML).find("[nodeName='z:row']").attr("ows_ID"); 			
          					}
    			});
	}

function UpdatePlink()
	{
	var plnk = "<DIV><A HREF=https://********/org/amcte/TIMS/SiteDocs/Project.aspx?SID=";
	plnk += mynewID; 
	plnk += "><IMG SRC=https://********/_layouts/images/doclink.GIF border=0></A></DIV>";
	
	$().SPServices({
        	operation: "UpdateListItems",
        	async: false,
        	listName: "Project Index",
        	valuepairs: [["P_x0020_Link", plnk]],
		batchCmd: "Update",
		ID: mynewID,
		completefunc: function(xData, Status) {
          		alert("The project was successfully created in TIMS. " + mynewID);
          			}
    			});
	}
Nov 9, 2011 at 8:48 PM

Quick thoughts...

You are introducing some special characters in the plnk (<> etc) that may be messing things up.  I have found you can either escape each one, or add one more variable after you are done building plink like:

var plnk2 = plnk.replace(/&/g,'&amp;').replace(/"/g,'&quot;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
then use plink2 the rest of the way.
Also, when you first enter your UpdatePlink function, alert for the mynewID - I am sure it is golden, but worth a try...then alert the plnk2, yada yada.
Nov 9, 2011 at 9:00 PM

Aha!  I changed to "plnk = 'test';"  ... the record was updated with the word "test" in the P Link field.   I added your suggested line of replaces...now works great.  THANKS! You rock! 

Coordinator
Nov 9, 2011 at 9:01 PM

I love watching you guys work!

M.

Nov 9, 2011 at 9:25 PM

Just passing along a tip that Marc provided in the past - paying it forward!!

Nov 30, 2011 at 7:34 PM

In case anyone references this thread in the future:

When populating a "people" field, you need to pass the ID of the person as a STRING.   This took me a good half hour to figure out. 

i.e., for the current user...



var pid = new String( $().SPServices.SPGetCurrentUser({ fieldName: "ID" }));
...and then use the variable within the value pair for the person column. 
Nov 30, 2011 at 7:44 PM

Ideally, you should locate and pass the ID.  If it is not the current user like in your case, I assum you could use the UserProfileService to get 'er done!

In a pinch, you can fake it by using -1;# instead of their actual ID number then the current users preferred name (if passing to a P/G field set as Name with Presence).

I have recently used this logic to fill a multiple value person/group field, and it is even trickier:  -1;#firstperson;#-1;#secondperson;#-1;#thirdperson;#

so preface the first person with -1;#  then preface the second, third person with ;#-1;#  and trail the string with ;#

Not sure how or why, but it works!

Glad you got it all working!!

Nov 1, 2012 at 3:11 PM

Just an FYI for any who find this thread.  When updating a multiple Person field, you use this pattern:

 

[ID0];#;#[ID1];#;#[ID1]

 

Where [ID] is the collection ID for that person.  The tricky bits:

1. If you are only adding one item, and the Person's ID was say 2302, then your string would look like this:

2302

2.  If you are adding two people and their ID's were respectively 2302  and 2441 your string would look like this:

2302;#;#2441

 

Good post about this here:  http://pholpar.wordpress.com/2010/01/26/updating-multi-value-fields-using-web-service-call-and-batch-update/

 

 

From what I can tell, using -1 is no good.

Apr 3, 2015 at 2:30 AM
So, I realize this post is two years old, but I struggled with something similar today for two hours. In my case, I need to use the Page Contact field, as rendered on a Publishing page, and want to use SPServices to grab that page contact and populate a new list item as part of a feedback process. I struggled for hours and finally found that to insert into a person field, you need this format:

ID;#CommonName. So, if my userID is 8 and my display name is Kevin Lowe, the value would be 8;#Kevin Lowe in order to insert into the person field properly.

Using -1#Kevin Lowe would, in fact, work - but it is very slow and I suspect it'd cause performance issues. In my case, because I'm pulling that value from a person field rendered on the page (in this case a page property inserted on the layout) I can get the ID from the html SharePoint renders as part of that. There's a link to the profile, and it contains the ID (ID=x) in the href. So, I'm using jQuery to grab that href, parsing it with JavaScript to get the ID number, then concatenating it with ;# and the text value of that element. And...

It totally works.

This whole thread was super helpful - thanks a ton!
  • Kevin
Apr 30, 2015 at 11:31 AM
Hi everyone,

couldn't find the answer for updating user field with multiple choices (adding and removing a user), so had to write is myself - maybe it will help someone.
function UpdateParticipants(listName, itemId, userName, userId, initialData) {

    var usersToSet = "";
    if (!IsStringEmpty(initialData)) {
        usersToSet = initialData + ";#" + userId + ";#" + userName;
    } else {
        usersToSet = userId + ";#" + userName;
    }

    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        debug: true,
        listName: listName,
        ID: itemId,
        valuepairs: [["EventParticipants", usersToSet]],
        completefunc: function (xData, Status) {
            if (Status != "success") {
                alert("Something Went Wrong. You haven't applied for the event, please contact Event Manager.");
            } else {
                alert("You have succesfully applied for the event.");
            }
        }
    });

}

function RemoveParticipant(listName, itemId, userName, userId, initialData) {

    var usersToDelete = userId + ";#" + userName;
    var usersToSet = initialData.replace(usersToDelete, "");

    $().SPServices({
        operation: "UpdateListItems",
        async: false,
        debug: true,
        listName: listName,
        ID: itemId,
        valuepairs: [["EventParticipants", usersToSet]],
        completefunc: function (xData, Status) {
            if (Status != "success") {
                alert("Something Went Wrong. You haven't resigned from the event, please contact Event Manager.");
            } else {
                alert("You have succesfully resigned from the event.");
            }
        }
    });

}

function IsStringEmpty(inputString) {
    if (inputString != null && inputString != "" && inputString != "undefined" && inputString.length > 0) {
        return false;
    }
    return true;
}
listName - is is, in fact, list GUID in my case... :)