17 Oct 2012

SharePoint. Set PeoplePicker via JavaScript

There is no way to set default value of “Person or Group” field. But it is possible to populate “Person or Group” field via JavaScript. Code below populate SharePoint PeoplePicker control with current user. It’s just example with hardcoded id, to show basic idea:

  • how to get current user via SharePoint JavaScript Client Object Model
  • how to insert user into SharePoint PeoplePicker control (“Person or Group” field) via JavaScript
function SetPickerValue(pickerid, key, dispval) {
    var xml = '<Entities Append="False" Error="" Separator=";" MaxHeight="3">';
    xml = xml + PreparePickerEntityXml(key, dispval);
    xml = xml + '</Entities>';

    EntityEditorCallback(xml, pickerid, true);
}

function PreparePickerEntityXml(key, dispval) {
    return '<Entity Key="' + key + '" DisplayText="' + dispval + '" IsResolved="True" Description="' + key + '"><MultipleMatches /></Entity>';
}


function GetCurrentUserAndInsertIntoUserField() {
    var context = new SP.ClientContext.get_current();
    var web = context.get_web();
    this._currentUser = web.get_currentUser();
    context.load(this._currentUser);
    context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
    Function.createDelegate(this, this.onFailure));
}
function onSuccess(sender, args) {
    SetPickerValue('ctl00_m_g_02c785ac_e0cb_4e03_92c2_0e3dbe6d0097_ctl00_ctl05_ctl01_ctl00_ctl00_ctl04_ctl00_ctl00_UserField', this._currentUser.get_loginName(), this._currentUser.get_title());
}
function onFaiure(sender, args) {
    alert(args.get_message() + ' ' + args.get_stackTrace());
}

ExecuteOrDelayUntilScriptLoaded(GetCurrentUserAndInsertIntoUserField, "sp.js");

Picture to show where to get “pickerid” (you can do that via JavaScript)

image_thumb[4]

No comments:

Post a Comment