Wednesday, July 9, 2014

Random People Picker in SharePoint 2013

The Scenario

One of our clients hired Rightpoint to build an intranet with lots of social features.  On each team site, the client wanted a widget that pulled four team members and displayed them as shown in the screenshot at the bottom.  Pretty easy for any seasoned developer.  However the client added one additional stipulation: every time the page loads, different people had to show up randomly.  Still not a bad deal for a seasoned developer.  Here’s how I handled the development.

The Code

The main part of the code is the REST API call. I'll break down all of the parameters.

Here is the breakdown of the code that creates the URL.

Get the protocol and host from the location object.

var rootURL = location.protocol + '//' + location.host;

Note that you can also use the spPageContextInfo object.  It would look like this:

var url = _spPageContextInfo.siteAbsoluteUrl;

Set the row limit to 4.  This will limit the results to just 4.

var rowLimit = 4;

Select a random number between 1 and 1001.  This randomizes the results.

var num = Math.floor((Math.random() * 1000) + 1);

Set the URL for the ajax call.

var serviceLink = rootURL + "/_api/search/query?querytext='PrimaryTeam%3A%22Battle%20Creek%22'

&sourceid='B09A7990-05EA-4AF9-81EF-EDFAB16C4E31'

&sortlist='[random:seed=" + num + "]:ascending'

&rowlimit=" + rowLimit;

 

The service link variable is made up of 4 parameters:
queryText - provides the name of the team.  the value turns out to be PrimaryTeam='Battle Creek'
sourceId – tells SharePoint to pull the data from the people in SharePoint.  The sourceid is a guid and is the same value in any SharePoint farm.
sortList – tells SharePoint to sort the results randomly.
rowlimit - Limits the number of results returned.

The next piece of code is the actual call to the REST service.

$.ajax({

      type: 'GET',

      url: serviceLink,

      headers: { "Accept": "application/json;odata=verbose" },

      success: function (peopledata) {

          //Process results here...

      }, 

      error: function (response) {

         //Handle any exception here. 

      }

  });  

 

The CSS

The CSS took a bit to figure out, but once I did, it became easy.  Basically I used nested divs.  One for the outer container and then 4 more for each person.  The CSS is below

.fourPerson-PeoplePanel{

  display: inline-block;

  height: 107px;

  padding-left: 17px;

  width: 320px;

}        



.fourPerson-DetailPanel{

    display: inline-block;

    height: 107px;

    padding-bottom: 30px;

    padding-right: 10px;

    vertical-align: top !important;

    width: 150px;

}

 

The Results