Setting default value of person field in SharePoint 2013 with JSLink

Often, there is a need for setting a default value in a person field. In this article, we will have a look at how to set a person field value to the current logged in user. This involves using the Client People Picker with JSLink for rendering the field in the new form and using the JSOM SharePoint API to get information about the current logged in user.

First, create the JSLink JavaScript file and connect it to for example the field or content type definition (there are numerous articles about how to implement JSLink, for example here). I have separated the logic for the rendering the output into another JavaScript file referred to in the master page, just to keep things clean and more readable. This separate JavaScript file is using a namespace (window.TheSystem.JSLink) in order to prevent global namespace conflicts. The field we are overriding is called “Reporter”:

(function () {
   var currentUserContext = {};
   currentUserContext.Templates = {};
   currentUserContext.Templates.Fields = {
   "Reporter": {
      "NewForm": window.TheSystem.JSLink.ReporterNew
   }
};
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(currentUserContext);
})();

The next step is to create the functionality for the rendering, the “ReporterNew” function:

window.TheSystem.JSLink = (function () {

    return {
        ReporterNew: function(ctx) {
            return reporterNew(ctx);
        }
    }

    var reporterNew = function (ctx) {

        // Check if the context exists
        if (ctx == null || ctx.CurrentFieldValue == null)
            return '';

        // Check that the form context exists
        var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
        if (formCtx == null || formCtx.fieldSchema == null)
            return '';

        // Register a callback to get the value of the people picker
        formCtx.registerGetValueCallback("Reporter", function () {
            var userKey = getUserInfoFromPeoplePicker().replace('\\', '\\\\');
            return '[{"Key":"' + userKey + '"}]';
        });

        // Create the rendering code for the people picker
        var str = '<div id="peoplePickerDiv"></div>';
        initializePeoplePicker('peoplePickerDiv');
        return str;
    }

    // ...
    // internal helper functions (see below)
    // ...
}

In the code above, we use two important methods: one for rendering the field (initializePeoplePicker) and one for getting the value from the client people picker control (SPClientPeoplePicker) in the callback (getUserInfoFromPeoplePicker). The first method called is the initialization of the people picker. This method calls the third important method: getting the user information from JSOM (getUser). The getUser function returns a promise so that we can wait for the asynchronous call to be finished before rendering the output. Note that, in this example, we are assuming that we are dealing with a single person field.

    // Render and initialize the client-side People Picker.
    var initializePeoplePicker = function(peoplePickerElementId) {

        // Get the SharePoint context
        var context = new SP.ClientContext.get_current();
        var web = context.get_web();

        // Get the user promise
        getUser(context, web).done(function (user) {

            // Create the schema for the people picker
            var schema = {};
            schema['PrincipalAccountType'] = 'User';
            schema['SearchPrincipalSource'] = 15;
            schema['ResolvePrincipalSource'] = 15;
            schema['AllowMultipleValues'] = false;
            schema['MaximumEntitySuggestions'] = 50;
            schema['Width'] = '280px';

            // Set the default user by building an array with one user object
            var users = new Array(1);
            var currentUser = new Object();
            currentUser.AutoFillDisplayText = user.get_title();
            currentUser.AutoFillKey = user.get_loginName();
            currentUser.Description = user.get_email();
            currentUser.DisplayText = user.get_title();
            currentUser.EntityType = "User";
            currentUser.IsResolved = true;
            currentUser.Key = user.get_loginName();
            currentUser.Resolved = true;
            users[0] = currentUser;

            // Render and initialize the picker
            SPClientPeoplePicker_InitStandaloneControlWrapper('peoplePickerDiv', users, schema);
        });
    }

    // Get the current user from the context
    var getUser = function(context, web) {
        var dfd = $.Deferred(function() {
            user = web.get_currentUser();
            context.load(user);
            context.executeQueryAsync(
                    function() {
                        dfd.resolve(user);
                    }),
                function() {
                    dfd.reject(args.get_message());
                };
        });
        return dfd.promise();
    }

Finally, we have the method for getting the information from the client people picker when the form is saved:

    // Query the picker for user information.
    var getUserInfoFromPeoplePicker = function() {

        // Get the people picker object from the page.
        var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;

        // Get information about all users.
        var users = peoplePicker.GetAllUserInfo();
        return users[0].Key;
    }

Now, we have a JSLink rendered people picker field that has default value of the current user:
clientpeoplepicker

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s