Saturday, August 22, 2015

Getting a users Profile Picture from a Display Template

This took quite a while to figure out, since it requires a combination of queries to get. Finally decided the best approach was to get the ID of the list item that has a User field. In this case I have a list with an "AssignedTo" field. I want to create a custom Display Template that would display the photo of the person that the item was "AssignedTo". I couldn't find a single article that covered this specific task.

Make sure your Display Template gets the needed Managed Properties like this:
'ListItemID':'ListItemID','SPSiteUrl':'SPSiteUrl'

First, get the list item that has the AssignedTo field:
var myUrl = mySite + "/_api/web/lists/getByTitle('HighFives')/items("+ itemID +")"


$.getJSON( myUrl, function( data ) {

We are withing the "success" handler here.
Next, now that we have the User ID (AssignedToId, a number) we can query for some useful user data. In this example I really want the "EMail" property since this is all I need to get the photo. Took a while to get this, since Email fails :/
  var url2 = "siteUrl + "/_api/Web/SiteUserInfoList/Items("+ data.AssignedToId +")?$select=Name,Picture,UserName,EMail";
  $.getJSON( url2, function( data ) {
  
  var uName = data.EMail;

Here's the part to get the photo. another option is to use the Picture setting, but using this URL seems simpler and will return a placeholder if nothing found. size can be S,M,L

    var imageLink =siteUrl + "/_layouts/15/userphoto.aspx?size=S&accountname="+ uName +"&url=";

Using jQuery to insert the picture on the page.

$("#userPictureDiv_" + itemID).html("<img style='width:100%;max-width:48px' src='"+ imageLink +"'/> abc " + imageLink);
  }); 

  });

Since this is in a Display template you can't just set the contents of the DOM within a document.ready, this all has to be contained within this:

AddPostRenderCallback(ctx, function () {

// code here

});


No comments:

Post a Comment