Wednesday, July 5, 2017

Auto Populate Person Field / People Picker in SharePoint Online

Wanted to throw some reference code out there for how to auto populate a Person field using jQuery and SPServices.  The full code is below, and I pasted this directly below the "PlaceHolderMain" in the NewForm.aspx file in SharePoint Designer.  You'll find the original article here.

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="/_layouts/15/clientforms.js"></script>
<script src="/_layouts/15/clientpeoplepicker.js"></script>
<script src="/_layouts/15/autofill.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices.js"></script>
<script type="text/javascript">

$(document).ready(function () {
SP.SOD.executeFunc('sp.js', null, function () {
retrieveUserInfo("Employee");  // Set this to the Title of the person column
    })
  });

  function retrieveUserInfo(PickerTitle) {
var currentuserName = $().SPServices.SPGetCurrentUser({
fieldName: "Title"
});

  $('input[title="' + PickerTitle + '"]').val(currentuserName).attr('size', 40);

    $('div[title="' + PickerTitle + '"] span.ms-helperText').hide();

    // Select the target user field from the dictionary of user fields on the page.
    var peoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[$('[title="' + PickerTitle + '"]')[0].id];

    // Resolve the user using the value set in the input field.
    peoplePicker.AddUnresolvedUserFromEditor(true);
}

No comments: