6

I was able to set the current user to people picker field in SharePoint 2010,but now i am new to SharePoint 2013 .

Please tell me how to set the current user value to that filed.

In SharePoint 2010-

<script type="text/javascript">
 $(document).ready(function() {   
 //Get the current user name
 var user= $().SPServices.SPGetCurrentUser();  
 //Find the Specific People picker field "Requester" and set its value
 $().SPServices.SPFindPeoplePicker({
 peoplePickerDisplayName: "Requester",
 valueToSet: user,
 checkNames: true
 });
 });
</script> 
3

You can use below code to find out the current user login name

<script type="text/javascript">
  var userid= _spPageContextInfo.userId;
  var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
  var requestHeaders = { "accept" : "application/json;odata=verbose" };
  $.ajax({
    url : requestUri,
    contentType : "application/json;odata=verbose",
    headers : requestHeaders,
    success : onSuccess,
    error : onError
  });

  function onSuccess(data, request){
    var loginName = data.d.Title;
    alert(loginName);
  }

  function onError(error) {
    alert("error");
  }
</script>

Once you have this, you can set the people picker using

var controlName     = "ControlName";                    
var ppDiv       = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");         // Select the People Picker DIV
var ppEditor        = ppDiv.find("[title='" + controlName + "']");  // Use the PP DIV to narrow jQuery scope
var spPP        = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv[0].id];           // Get the instance of the People Picker from the Dictionary
ppEditor.val("jasonscript\\jason            // Set the value
spPP.AddUnresolvedUserFromEditor(true);                 // Resolve the User

https://jasonscript.wordpress.com/2013/08/07/javascript-and-working-with-the-sharepoint-2013-people-picker/

  • 3
    This is just a note from the future: on 6/16/2017 the structure of the people picker field changed. You cannot use the controlName to find ppEditor - you have to append ", Enter a name or email address..." to the controlName – Robin in Or Jun 16 '17 at 16:33
3

Since you are using SharePoint 2013 I would recommend you to consider the following approach. In SharePoint 2013 for rendering of List Views and Forms was introduced a Client Rendering Mode (CSR).

How to initialize User field in New/Edit forms to current user using CSR

Below example demonstrates how to populate User field (AssignedTo) in New form for a List (Tasks list)

Template code:

(function () {
    var ctx = {};
    ctx.Templates = {};
    ctx.Templates.Fields = {
        'AssignedTo': {
            'NewForm': renderAssignedTo
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();

function renderAssignedTo(ctx) {
     var currentUser = $().SPServices.SPGetCurrentUser({fieldNames: ["Title", "Name"]});   //get current user properties
     var currentUserEntry = createUserEntity(currentUser.Name,currentUser.Title);
     //Set user default value
     ctx.CurrentFieldValue = [];   //Note: it is assumed the user field is a multi-valued field (!)
     ctx.CurrentFieldValue.push(currentUserEntry);  
     return SPClientPeoplePickerCSRTemplate(ctx);
}

function createUserEntity(userLoginName,userDisplayName)
{
   return {
      Description: userLoginName,
      DisplayText: userDisplayName,
      EntityGroupName: "",
      EntityType: "",
      HierarchyIdentifier: null,
      IsResolved: true,
      Key: userLoginName,
      MultipleMatches: [],
      ProviderDisplayName: "",
      ProviderName: ""
   };
}

$().SPServices.SPGetCurrentUser function is used to retrieve a current user

In addition to SharePoint Web Services (SPServices), JSOM or REST APIs could be utilized for retrieving current user

How to apply the changes

There are at least two options how to apply the changes:

  1. Using JSLink property
  2. Place JavaScript template on page via Script Editor/Content Editor web parts

Here is how to apply the changes using the second option:

  1. Switch the page (NewForm.aspx) into edit mode
  2. Add Script Editor webpart right below the list view web part.
  3. Put the specified code by wrapping it using script tag code into the Script Editor, for example: <script type="text/javascript">{Template JS code goes here}</script>
  4. Save the page

Results

enter image description here

  • 1
    +1 The createUserEntity is really helpful. – Emiliano Poggi Mar 18 '16 at 19:14
1
//Resolve the user in people picker field
var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.h_Requestor_PPkr_TopSpan; //Select the People Picker AKA Get the instance of the People Picker from the Dictionary
var usrObj = { 'Key': v_Requestor_Acct_Id }; //Set the user value AKA 'Key' name value pair format: myDomain\UserId  i.e. abc\shane.gibson you may have to drop the claims token prefix {i:0#.w|}
peoplePicker.AddUnresolvedUser(usrObj, true); //Resolve the User

Here's a link to the best dang resource I have found on the web about the sharepoint client side people picker object! The code works perfect everytime. Only note I would add on it is their people picker object name is 'peoplePickerDiv' might help a bit in interpreting the code in the link.

I always make mine specific to the role i.e. 'Requestor' in my code 'h_Requestor_PPkr'. If it where a 'Manager' people picker I would call it 'h_Manager_PPkr' etc. enjoy!

Thanks.

SG.

  • 1
    +1 for being former ICC – Josey Jun 12 '17 at 20:22
  • 😉🙄 Thanks! If you get a timing issue with this you may need to use nested async calls or deferred! – Shane Gib. Jun 14 '17 at 0:33
  • Nice Documentation link you have provided.... Very elaborate!! – zainul Mar 13 at 11:04
1

We found here that the code above can work, but not on all computers. We had timing issues that would cause errors on the part that validated. So we had to do this (SP2013 on premise):

$(document).ready(function() {


   window.setTimeout(function(){ doTheDefaults(0,10,200);},200);
});
// --------------------------------------
//  Sets Default Values will loop untile compleates or exceeds retryes
 //
//  loopValue - The current loop it is on
//  MaxLoops  - The max amount of loops that can be executed
//  TimeDelay - Time between retries
// ----------------------------------------
function doTheDefaults( loopValue,MaxLoops, TimeDelay) {
    try {
        // -----------------
        // Default requested by and phone
        // -----------------
      var thisUser = getCurrentUser();

       // get people picker object
      var controlName = "Requested By";     
      var ppDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']"); // PP Div
      var ppEditor = ppDiv.find("[title='" + controlName + "']");
      var spPP  = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv[0].id];  
      ppEditor.val(thisUser);
      spPP.AddUnresolvedUserFromEditor(true); 
  }
     catch(err) {

      loopValue++;

      //Total Time allowed for retrys is 2 seconds
      if(loopValue > MaxLoops)
      {
        window.setTimeout(function(){ doTheDefaults(loopValue,MaxLoops,TimeDelay);},TimeDelay);
      }
     }
}
function getCurrentUser() {

// 2013 Name is the full i:0#.w|domain\\name
// we use SPServices, but you could do whatever you need
// to get user name

    var cu = $().SPServices.SPGetCurrentUser({
     fieldName: "Title",
     debug: false
    });
 return cu;
}
-1

The one solution worked for me until recently. I was able to fix the code to work again now - building off of the answer by Robin in Or.

var controlName = "Assigned To";

var controlName1 = "Assigned To, Enter a name or email address...";

var ppDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']"); // controlName is right for this one

var ppEditor  = ppDiv.find("[title='" + controlName1 + "']"); // controlName1 is needed here to find the right element

var spPP = SPClientPeoplePicker.SPClientPeoplePickerDict[ppDiv[0].id];

ppEditor.val(newAssignee);  // set the value using your var etc.

spPP.AddUnresolvedUserFromEditor(true); 
  • what was the issue? – Mohamed El-Qassas MVP Jul 10 '17 at 19:16
  • 1
    There was a security update lats month that actually changed the structure of people fields and url fields in sharepoint 2013 (on premise at least). Don't know why a general MS security update would do that, but it was the only thing that had happened to our server - they said there were a ton of patches. MS changed the titles of these type of fields. – Robin in Or Jul 10 '17 at 20:46

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.