Posts

Showing posts from July, 2016

Get the Current User's Manager in JavaScript

Using the JavaScript Object Model to look up the manager of the current user (from the User Profile Service) seems to be a fairly common requirement - I've had to do it at least three times in the last couple of months.

First of all, you need to load the profile properties for the current user:

var context, userProperties;

var stage1 = function() {
     context = SP.ClientContext.get_current();
     var peopleManager = new SP.UserProfiles.PeopleManager(context);
     userProperties = peopleManager.getMyProperties();
     context.load(userProperties);
     context.executeQueryAsync(stage2, onQueryFail);
}

Then you can retrieve the value of the Manager property as follows:

var stage2 = function() {
    var manager =           userProperties.get_userProfileProperties()["Manager"];
}

And that's it. Easy once you know how.

Incidentally, the trickiest part of all this can be getting the SharePoint script files to load in the right order. You can't run your code until sp.userprofiles.…

Adding Site Columns to Lists and List Views using the JavaScript Object Model

A couple of years ago, I posted on how to create SharePoint site columns using JavaScript. More recently, we needed to add a site column to a list in SharePoint Online as part of a scripted provisioning exercise. There were a few aspects of this that took a bit of trial and error, such as:
Retrieving the site column from the root site.Getting the field to show up on the default list view.Hiding the field from various forms.So I figured it's probably worth sharing the end-to-end code (sanitised and simplified). First of all, let's create a site column named JasonNotes on the root site in the site collection:

var context; 
var rootWeb; 
var rootWebId = "..."; // The GUID identifier for the root web

var stage1 = function () {
     context = new SP.ClientContext();

     // Get the fields collection for the root web
     var rootWeb = context.get_site().openWebById(rootWebId);
var fields = rootWeb.get_fields();

// Create and add the field
     var fieldSchema = '<Field Type=&…