Monday, February 1, 2016

Client-side People Picker control for Sharepoint 2013 Apps

When creating my "Sharepoint Hosted" App for Office365 (15) I had to use the client-side People Picker control in the App Part. There doesn't appear to be much in the way of documentation for this control other than the "How to" MSDN document here:
I wanted to default the control to the current user. From the document I could tell that there was a parameter in the init function that should contain an array of initial PickerEntity objects, but sadly no example of this. The example code simply passed a null where this should be.

SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema); 


I like to use the jQuery deferred function with the SharePoint asynchronous requests so that I have some control over my code executing in a sequential manner.
Here is a snippet of code that demonstrates how to default the People Picker control to the current user:

$(document).ready(function () {  
    SP.SOD.executeFunc('sp.js', 'SP.ClientContext', sharePointReady);  
})  
  
function sharePointReady() {  
    context = new SP.ClientContext.get_current();  
    web = context.get_web();  
    getUser().done(function (user) {  
        var schema = {};  
        schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';  
        schema['SearchPrincipalSource'] = 15;  
        schema['ResolvePrincipalSource'] = 15;  
        schema['AllowMultipleValues'] = false;  
        schema['MaximumEntitySuggestions'] = 50;  
        schema['Width'] = '280px';  
  
        var users = new Array(1);  
        var defaultUser = new Object();  
        defaultUser.AutoFillDisplayText = user.get_title();  
        defaultUser.AutoFillKey = user.get_loginName();  
        defaultUser.Description = user.get_email();  
        defaultUser.DisplayText = user.get_title();  
        defaultUser.EntityType = "User";  
        defaultUser.IsResolved = true;  
        defaultUser.Key = user.get_loginName();  
        defaultUser.Resolved = true;  
        users[0] = defaultUser;  
        SPClientPeoplePicker_InitStandaloneControlWrapper('peoplePickerDiv', users, schema);  
    });  
}  
  
function getUser() {  
    var dfd = $.Deferred(function () {  
        user = web.get_currentUser();  
        context.load(user);  
        context.executeQueryAsync(  
            function () {  
                dfd.resolve(user);  
            }),  
            function () {  
                dfd.reject(args.get_message());  
            };  
    });  
    return dfd.promise();  
}  

No comments:

Post a Comment