0
votes

Has anyone successfully managed to get the value of a User (Person or Group) field from the New or Edit form specifically for SharePoint 2013?

I have tried all solutions I can find from searching the internet and everything I can think of myself, all resulting in the result being blank or undefined.

The closest I’ve got have been from the following links where the latter worked for setting the value if anyone is interested but I was unable to successfully adapt it to retrieve the value.

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

http://www.sharepointcolumn.com/sp2013-setting-people-picker-value-in-newform-aspx/

My goal is to set the value only if it is empty but I can’t get the current value.

Looking in the DOM there are numerous HTML elements which have attributes containing the value but using JQuery to retrieve those attributes results in blank or undefined. I have confirmed I have the correct object with the title or id attributes. There is one HTML element where the title attribute has the value and still the JQuery returns blank or undefined in that particular case.

Thanks for any assistance you may be able to give.

2

2 Answers

2
votes

Since you are using SharePoint 2013 I would recommend you to consider the following 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 and which is a default rendering mode.

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

Below example demonstrates how to initialize User field (AssignedTo field in Tasks List) in New & Edit forms:

Note: it is assumed the user field is a multi-valued field

Template code:

SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function() {
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides({

      Templates: {
           Fields: {
               "AssignedTo": {
                   EditForm: renderAssignedTo,
                   NewForm: renderAssignedTo
               }
           }
      }

    });

});


function renderAssignedTo(ctx)
{
    var defaultAssigneeTo = {'LoginName': 'i:0#.f|membership|[email protected]','DisplayName':'John Dow' };


    if(ctx.CurrentFieldValue.length == 0) /* Is user field value empty? */
    { 
        var userEntry = createUserEntity(defaultAssigneeTo.LoginName,defaultAssigneeTo.DisplayName);
        ctx.CurrentFieldValue = [];   //Note: it is assumed the user field is a multi-valued field (!)
        ctx.CurrentFieldValue.push(userEntry);
    }
    return SPClientPeoplePickerCSRTemplate(ctx); 
}

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

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

Pic 1. New Form page

enter image description here

References

0
votes

I know I'm too late but just to help others having same problem with the default people picker I'm recording my code here. To call our own JavaScript function on PeoplePicker change event we need to attach OnUserResolvedClientScript event on PeoplePicker field.

$(document).ready(function(){
  SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () {
    SP.SOD.registerSod('clienttemplates.js', SP.Utilities.Utility.getLayoutsPageUrl('clienttemplates.js'));
    SP.SOD.registerSod('clientforms.js', SP.Utilities.Utility.getLayoutsPageUrl('clientforms.js'));
    SP.SOD.registerSod('clientpeoplepicker.js', SP.Utilities.Utility.getLayoutsPageUrl('clientpeoplepicker.js'));
    SP.SOD.executeFunc('clientpeoplepicker.js', "SPClientPeoplePicker", function () {
        GetPeoplePicker('<Field Name>'); //for required field append the fieldName with 'Required Field' text

     });
   });
});

function GetPeoplePicker(fieldName) { 
var controlName = fieldName;     
var peoplePickerDiv = $("[id$='ClientPeoplePicker'][title='" + controlName + "']");  
var peoplePickerEditor = peoplePickerDiv.find("[title='" + controlName + "']");  
var spPeoplePicker = SPClientPeoplePicker.SPClientPeoplePickerDict[peoplePickerDiv[0].id];   
spPeoplePicker.OnUserResolvedClientScript = function (peoplePickerId, selectedUsersInfo) {
    console.log('inside OnUserResolvedClientScript:'+ peoplePickerId);
    console.log(selectedUsersInfo);

  };    

  var userInfo = GetUserInfo(spPeoplePicker); 
}

Below is the function to Get the users from PeoplePicker field

function GetUserInfo(peoplePicker) {
// Get the people picker object from the page.
var userInfo = [];
if (typeof peoplePicker != 'undefined' && peoplePicker !== null) {
    // Get information about all users.
    var users = peoplePicker.GetAllUserInfo();
    userInfo =users;
    for (var i = 0; i < users.length; i++) {
        var user = users[i];            
        //logic for selected users
    }
  }
  return userInfo;
}

Happy Coding :)