Wednesday, April 16, 2014

SharePoint 2013 User Welcome Control with Client-Side Scripting

This is an example of using SharePoint 2013 JSOM to get the current logged in user's account information. This example uses SP.UserProfiles.PeopleManager object comes in SP.UserProfiles.js file and greets the currently logged on user saying “Hi, first name, last name [picture]”.

In order to load the profile picture, I used userphoto.aspx page resides in the SharePoint layouts folder. Two parameters passed for that are the picture size and account name (user email address in SharePoint online).

This code looks for a DIV element with the id "userDetails" on the page and will place the generated markup in it.

var TestApp = TestApp || {};

TestApp.UserWelcome = function (TestApp) {
 var context;
 var user;
 var personProperties;

 var getCurrentUser = function () {
  context = SP.ClientContext.get_current();
  user = context.get_web().get_currentUser();
  context.load(user);
  context.executeQueryAsync(getUserProperties, onGetUserFailed);
 };

 var onGetUserFailed = function (sender, args) {
  if ($('#userDetails').length) {
   $get("userDetails").innerHTML = "Get current user failed: " + args.get_message();
  }
 };

 var getUserProperties = function () {
  var targetUser = user.get_loginName();
  var peopleManager = new SP.UserProfiles.PeopleManager(context);
  personProperties = peopleManager.getPropertiesFor(targetUser);
  context.load(personProperties);
  context.executeQueryAsync(onUserPropSuccess, onUserPropFail);
 };

 var onUserPropSuccess = function () {
  var userPhoto = "/_layouts/15/userphoto.aspx?size=s&accountname=" + currentUser.get_email();
  var displayName = personProperties.get_displayName();
  displayName = displayName.replace(/\(.*\)/g, '');

  var detailHtml = '<div>Hi, ' + displayName + '<img src="' + userPhoto + '" /></div>';

  if ($('#userDetails').length) {
   $get("userDetails").innerHTML = detailHtml;
  }
 };

 var onUserPropFail = function (sender, args) {
  if ($('#userDetails').length) {
   $get("userDetails").innerHTML = "Error: " + args.get_message();
  }
 };

 return {
  getCurrentUser: getCurrentUser
 };
}();

$(document).ready(function () {
 var initWelcomeUser = function () {
  TestApp.UserWelcome.getCurrentUser();
 };

 ExecuteOrDelayUntilScriptLoaded(initWelcomeUser, 'SP.UserProfiles.js');
});

Additionally, namespaces are used in this example in order to reduce the number of objects and functions that are added to the global scope of the application.

No comments: