Search User and Retrieve Profile Properties – JSOM

Client Side People Picker Control (http://msdn.microsoft.com/en-us/library/jj713593.aspx) doesn’t work in Provider-Hosted App. Therefore, we need an alternative solution to implement this.

1. 利用SharePoint2013自带的SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser和ClientPeoplePickerQueryParameters对象搜索匹配用户信息。

var clientContext;
$(document).ready(function () {
//Get the URI decoded URLs.
var hostweburl = decodeURIComponent(getQueryStringParameter('SPHostUrl'));
var appweburl = decodeURIComponent(getQueryStringParameter('SPAppWebUrl'));
var scriptbase = hostweburl + '/_layouts/15/';

//load all appropriate scripts for the page to function
$.getScript(scriptbase + 'SP.Runtime.js', function () {
  $.getScript(scriptbase + 'SP.js', function () {
    $.getScript(scriptbase + 'SP.RequestExecutor.js', function () { 
      registContext(appweburl, hostweburl); 
    });
    $.getScript(scriptbase + 'init.js', function () {
      $.getScript(scriptbase + 'SP.UserProfiles.js', function () {
        $('#btnSearch').click(function (event) {
          var txt = $('#txtPeople').val();
          if (txt.length > 0) {
            var query = new SP.UI.ApplicationPages.ClientPeoplePickerQueryParameters();
            query.set_allowMultipleEntities(false);
            query.set_maximumEntitySuggestions(50);
            query.set_principalType(1);
            query.set_principalSource(15);
            query.set_queryString(txt);
            var searchResult = SP.UI.ApplicationPages.ClientPeoplePickerWebServiceInterface.clientPeoplePickerSearchUser(clientContext, query);

            clientContext.executeQueryAsync(function () {
              var results = clientContext.parseObjectFromJsonString(searchResult.get_value());
              var txtResults = '';
              if (results) {
                if (results.length > 0) {
                  for (var i = 0; i < results.length; i++) {
                    var item = results[i];
                    var loginName = item['Key'];
                    var displayName = item['DisplayText'];  // LoginName
                    var title = item['EntityData']['Title'];
                  }
                  ... ...
                }
                else { // no result
                  $('#txtPeople').css("color", "red");
                }
              }
            }, function (sender, args) {
                 alert('Failed Error:' + args.get_message());
          });
        }
      });
    });
  });
});
});
});

http://blogs.msdn.com/b/richard_dizeregas_blog/archive/2012/08/19/real-world-apps-for-sharepoint-2013-kudos-part-1.aspx

2. Related Functions

This function is used to load the SharePoint context. This is very important because the “clientContext” is the key to writing JSOM and calling back to SharePoint.

function registContext(appweburl, hostweburl) {
    clientContext = new SP.ClientContext(appweburl);
    var factory = new SP.ProxyWebRequestExecutorFactory(appweburl);
    clientContext.set_webRequestExecutorFactory(factory);
    var appContextSite = new SP.AppContextSite(clientContext, hostweburl);
}

function getQueryStringParameter(param) {
    var params = document.URL.split("?")[1].split("&");
    var strParams = "";
    for (var i = 0; i < params.length; i = i + 1) {
        var singleParam = params[i].split("=");
        if (singleParam[0] == param) {
            return singleParam[1];
        }
    }
}

http://www.greggalipeau.com/category/sharepoint-2013/apps/

3. Retrieve Profile Property

function getUserProperties(loginName) {
    var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
    personProperties = peopleManager.getPropertiesFor(loginName);

    // Load the PersonProperties object and send the request.
    clientContext.load(personProperties);
    clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}

// This function runs if the executeQueryAsync call succeeds.
function onRequestSuccess() {
    // Get a property from the UserProfileProperties property.
    try{
        if (personProperties.get_userProfileProperties()['Department'] != null)
            $('#txtValue').val(personProperties.get_userProfileProperties()['Department']);
        else
            $('#txtValue').val();
    }
    catch(err)
    {
        $('#txtValue').val();
    }
}

// This function runs if the executeQueryAsync call fails.
function onRequestFail(sender, args) {
    alert('request failed' + args.get_message() + '\n' + args.get_stackTrace());
}
Advertisements

5 thoughts on “Search User and Retrieve Profile Properties – JSOM

  1. Its like you read my mind! You appear to know a lot about this, like you
    wrote the book in it or something. I think that you could do with a
    few pics to drive the message home a bit, but other than
    that, this is great blog. A great read. I’ll certainly be back.

  2. Is there a way in the JSOM to retrieve the GUID of the term store based profile fields like SPS-Department?
    Right now it returns the text value of the field… I couldn’t find an equivalent to the .net csom where you can do a:
    var value = user[“SPS-Department”].GetTaxonomyTerms();
    Guid termGuid = value[0].Id;
    Any advice on how to achieve the same in JSOM ?

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s