28 Nov 2012

SharePoint. Add webpart via JavaScript Client Object Model

Code below add SimpleFormWebPart to page via JavaScript Client Object Model. This example show:

  • how to add webpart via JavaScript Client Object Model
  • how to add JavaScript file reference to any SharePoint page (here we add link to JS file on new element list form - newform.aspx)
Igotta.ResourcesBooking.DeployHelper = function () {
    this._initialize();
}

Igotta.ResourcesBooking.DeployHelper.prototype = {
    _context: null,

    _initialize: function () {
        this._context = new SP.ClientContext();
    },

    // targets = [
    //  {ServerRelativeUrl:'/site/Lists/List1/NewForm.aspx', htmlContent:'<p>Any HTML</p>' }, 
    //  {...}, ... 
    // ]
    addSimpleFormWebPartToPages: function (targets, callBack) {
        for (var ii in targets) {
            var webPartXml = '<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2" xmlns:sfwp="http://schemas.microsoft.com/WebPart/v2/SimpleForm"><Assembly>Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly><TypeName>Microsoft.SharePoint.WebPartPages.SimpleFormWebPart</TypeName><FrameType>None</FrameType><Title>JS1</Title><sfwp:Content><![CDATA[{htmlContent}]]></sfwp:Content></WebPart>'
                .replace(/{htmlContent}/, targets[ii].htmlContent);

            var pageFile = this._context.get_web().getFileByServerRelativeUrl(targets[ii].ServerRelativeUrl);
            var limitedWebPartManager = pageFile.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
            var webPartDefinition = limitedWebPartManager.importWebPart(webPartXml);
            var webPart = webPartDefinition.get_webPart();
            limitedWebPartManager.addWebPart(webPart, 'Main', 1);
            this._context.load(webPart);
        }

        var self = this;
        this._context.executeQueryAsync(function () { callBack(); }, this._onError);
    },

    _onError: function (sender, args) { alert(args.get_message()); }
}

Igotta.ResourcesBooking.DeployHelper.registerClass('Igotta.ResourcesBooking.DeployHelper');


//
// usage
//

var deployHelper = new Igotta.ResourcesBooking.DeployHelper();
var addSimpleFormWebPartToPagesCallBack = function(){console.log('DONE')}
deployHelper.addSimpleFormWebPartToPages(
    [{
        ServerRelativeUrl: '/Booking15/Lists/BookingBookings/newform.aspx',
        htmlContent: '<script type=\"text/javascript\" src=\"../../Scripts/igotta.js\"></script>'
    }],
    addSimpleFormWebPartToPagesCallBack);

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.

28 Sept 2012

SharePoint 2013. Update list item dateTime field via JavaScript Client Object Model

SharePoint Client Object Model expects the dates to be in UTC. Example below show how to update list item dateTime field via JavaScript Client Object Model using the SP.TimeZone.localTimeToUTC method.

function addBrowserUtcOffset(date) {
    var utcOffsetMinutes = date.getTimezoneOffset();
    var newDate = new Date(date.getTime());
    newDate.setTime(newDate.getTime() - (utcOffsetMinutes*60*1000));

    return newDate;
}


function updateListItem() {
    this.clientContext = new SP.ClientContext();
    var date = new Date(2012, 8, 17, 5, 0);
    console.log(date);
    this.isoDate = clientContext.get_web().get_regionalSettings().get_timeZone().localTimeToUTC(date.toISOString());

    clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onGetDate),
        Function.createDelegate(this, this.onQueryFailed)
    );
}

function onGetDate() {
    var dateToInsert = addBrowserUtcOffset(this.isoDate.get_value());

    var oList = this.clientContext.get_web().get_lists().getByTitle('testlist');
    var oListItem = oList.getItemById(1);
    oListItem.set_item('dateField', dateToInsert.toISOString());
    oListItem.update();

    this.clientContext.executeQueryAsync(
        Function.createDelegate(this, this.onUpdate),
        Function.createDelegate(this, this.onQueryFailed)
    );
}

function onUpdate() {
    console.log('DONE');
}

function onQueryFailed(sender, args) {
    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

updateListItem();