0

How to set /auto populate Person/ Group field in SharePoint 2013 New/ edit forms using Javascript? I tried this code and its not working in 2013

<script type="text/javascript">
//fiedName is the userfield displayName
//userName is the displayname of user you want to autofill
function SetUserFieldValue(fieldName, userName) {
        var _PeoplePicker = $("div[title='" + fieldName + "']"); //// $("[id$='ClientPeoplePicker'][title='" + fieldName + "']");  // not worked
        var _PeoplePickerTopId = _PeoplePicker.attr('id');
        var _PeoplePickerEditer = $("input[title='" + fieldName + "']");
        _PeoplePickerEditer.val(userName);
        var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict[_PeoplePickerTopId];
        _PeoplePickerOject.AddUnresolvedUserFromEditor(true);
    }
</script>

I can get the current logged in user, but struck to populate, resolve the user name in the person field.

2

Use JSLink on New and Edit form to set current user in people picker

    function setDefaultUser(ctx) {
        var currentUser = null;

        // Get the current form context
        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

        // Get the current user
        $.ajax({
            async: false,
            headers: { "accept": "application/json; odata=verbose" },
            method: "GET",
            url: formCtx.webAttributes.WebUrl + "/_api/web/CurrentUser",
            success: function (data) {
                // Set the current user
                currentUser = data.d;
            }
        });

        // Ensure the current user exists
        if (currentUser != null) {
            var loginName = currentUser.LoginName.replace("\\", "\\\\");

            //Set user default value
            ctx.CurrentFieldValue = [{
                Description: loginName,
                DisplayText: currentUser.Title,
                EntityGroupName: "",
                EntityType: "",
                HierarchyIdentifier: null,
                IsResolved: true,
                Key: loginName,
                MultipleMatches: [],
                ProviderDisplayName: "",
                ProviderName: ""
            }];
        }

        // Return the html for the user field
        return SPClientPeoplePickerCSRTemplate(ctx);
    }
  • 1
    Just a note, if its office 365 you have the _spPageContextInfo.userLoginName available – Anders Aune Oct 21 '15 at 13:36
  • thanks DOM. I will test your solution. what worked for me is this function in the new and edit forms. function SetPeopleValue(loginName) { var peopleDiv=$('div[title="People Picker"]'); peopleDiv.html('<DIV>'+loginName+'</DIV>'); } – Raj Oct 22 '15 at 21:24

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.