Run custom JavaScript code when user is selected from PeoplePicker

Let’s imagine that we have SharePoint PeoplePicker and we want to fill some additional fields with user properties from AD or some other systems (HRM, DB etc.) when user is selected. We want to use client side scripting for better user experience and responsiveness without postback.

If we inspect page with PeoplePicker element on it, there we have table element with ms-usereditor class. Inside it we could find some div elements. First of it has as many span child elements as we have users selected in PeoplePicker. So with this JS code you could check if any user or how many users are selected:

$(".ms-usereditor div")[0].childElementCount

If we want to overwrite default callback function with some custom JavaScript code when user is selected from PeoplePicker, we have to overwrite EntityEditorCallback function. We really don’t want to overwrite it but just add some additional code to existing callback functionality. So, firstly we run old EntityEditorCallback function (saved in oldEntityEditorCallback) and then we call our custom function (saved in func). All that in invokeAfterEntityEditorCallback function.

var invokeAfterEntityEditorCallback = function (func) {
    var oldEntityEditorCallback = EntityEditorCallback;
    if (typeof EntityEditorCallback != 'function') {
        EntityEditorCallback = func;
    } else {
        EntityEditorCallback = function (result, ctx) {
            oldEntityEditorCallback(result, ctx);
            func(result, ctx);
        }
    }
}

Then we have to call that function in document.ready() with name of our custom function (named onPeoplePickerFieldSet) where we have custom JavaScript code:

invokeAfterEntityEditorCallback(onPeoplePickerFieldSet);

And the last one – onPeoplePickerFieldSet function where we parse out username of selected user and do something with it.

function onPeoplePickerFieldSet(result, ctx) {
    if (result != undefined) {
        parser = new DOMParser();
        xmlDoc = parser.parseFromString(result, "text/xml");

        DoSomethingWithUserName(xmlDoc.getElementsByTagName("Entity")[0].getAttribute('Key'));
    }
}

[ Complete code on GitHub ]

Cheers!
Gašper Rupnik

{End.}

Advertisements

One thought on “Run custom JavaScript code when user is selected from PeoplePicker

Add yours

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 )

Google photo

You are commenting using your Google 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 )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: