0

This question is related to an earlier question I posted, but did not get an answer on, so I am attempting a different approach.

To summarize: My goal is to set a people picker value to the current user when completing the New Form.

In my previous question, I was trying to use the SPServices function $().SPServices.SPFindPeoplePicker, however, it would seem that this function does not work for SP2013 forms, so I am working on an alternative.

I am able to set the value of the People Picker field to the current user via the following:

var PickerTitle = "Assigned To";
var currUser = $().SPServices.SPGetCurrentUser({ fieldName: "Title" });
$('input[title="' + PickerTitle + '"]').val(currUser).attr('size', 40);
$('div[title="' + PickerTitle + '"] span.ms-helperText').hide();

However, unlike SP2007, SharePoint does not auto-resolve the People Picker values on save, so unless the user selects the field and manually resolves the name, the value is erased.

I have been pulling out my hair trying to trigger the validation programmatically, but have had no luck. I have noticed that SharePoint will resolve the field if you select it, then hit Tab, however, I have not been able to force this same trigger via a jQuery event.

// I've tried 'keydown', 'keypress', 'keyup'
var e = jQuery.Event("keydown");
e.which = 9; // 'Tab' keycode
$('input[title="' + PickerTitle + '"]').trigger(e);

Unfortunately, I'm not good enough with Dev Tools to pick that apart to see exactly where the trigger is occurring. Has anybody else been able to determine what exactly is triggering the People Picker validation function and been able to trigger it using JavaScript/jQuery?

1

Ah! I found a solution!

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

Here is my working code:

var PickerTitle = "Assigned To";
var PickerDiv = $('[id$="ClientPeoplePicker"][title="' + PickerTitle + '"]');
var PickerEditor = PickerDiv.find('[title="' + PickerTitle + '"]');
var PickerInstance = SPClientPeoplePicker.SPClientPeoplePickerDict[PickerDiv[0].id];

var currUser = $().SPServices.SPGetCurrentUser({ fieldName: "Title" });

PickerEditor.val(currUser);
PickerInstance.AddUnresolvedUserFromEditor(true);
0

You need to use the "SPClientPeoplePicker" JS object, which according to this MSDN article you should find in the following SharePoint 2013 JavaScript libraries:

  • clientforms.js
  • clientpeoplepicker.js
  • autofill.js

Here's my solution for you:

var PickerTitle = "Assigned To";
var currUser = $().SPServices.SPGetCurrentUser({ fieldName: "Title" });

$('input[title="' + PickerTitle + '"]').val(currUser).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);

The JavaScript Object Model (JSOM) is pretty rich in SharePoint 2013, it is just not very well documented (yet?). So you need to play around to find how some things work.

-1

Since you are using SharePoint 2013 I would recommend you to consider a different approach, in SharePoint 2013 was introduced a so called Client Rendering Mode (CSR) which is intended for rendering of List Views and Forms using HTML and JavaScript.

How to initialize User field in New/Edit forms 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

  • Not working for me in Office 365 – codemirror Jun 16 '17 at 13:13

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.