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]

2 Oct 2012

Sharepoint. Advanced filtering of SharePoint list view by URL

This post is about advanced filtering of SharePoint list view (or XsltListViewWebPart) by setting parameters in URL, such as:

  • filter list view by part of the word (contains) in URL
  • filter list view by date range in URL
  • and so on.

The key is to use CAML GetVar Element.

For example, View with this <Query> will show list items whose titles contains specified in URL parameter “ProjectTitle” substring (Lists/Projects/AllItems.aspx?ProjectTitle=crm):

<Query>
  <Where>
    <Contains>
      <FieldRef Name="Title"/>
      <Value Type="Text">
        <GetVar Scope="Request" Name="ProjectTitle"/>
      </Value>
    </Contains>
  </Where>
</Query>

This View has two problems:

  1. It is possibly to set such View <Query> via SharePoint Designer, List Definition, custom code, but not using standard SharePoint web UI.
  2. If URL doesn’t contain “ProjectTitle” parameter, the View will show nothing.