SPWidgets

SharePoint Custom UI Widgets

View the Project on GitHub purtuga/SPWidgets

Widget List

About

SPWidgets is a jQuery plugin that provides SharePoint Widgets that can be used for creating customized User Interfaces (UI) on the SharePoint platform using Client Side scripting (javascript).

For the latest information on this plugin, see the project page on GIT.

Demo Showcase

Want to try them now and not worry about installation/setup etc. A self contained Single Page Application (SPA) is available that you can quickly upload to a Sharepoint library and see the widgets in action. GO HERE for more information.

Dependencies

SPWidgets has the following dependencies:

  1. jQuery
  2. jQuery UI

Usage

The following is an example that loads the required libraries from CDN's, the SPWidgets from the local site and then initiates the People Picker plugin on an input field inside a jQuery UI dialog.

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/themes/redmond/jquery-ui.css" />
<script type="text/javascript" src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
<script type="text/javascript" src='https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js'></script>
<script type="text/javascript" src='yoursite/path/to/jquery.SPWidgets.js'></script>
<script type="text/javascript">
    $(document).ready(function(){
        $('<div> <input name="users" value="" /> </div>')
            .appendTo("body")
            .find("input")
                .pickSPUser()
                .end()
            .dialog();
    });
</script>

License

Dual License support

User can pick whichever one applies best for their project and does'nt not have to contact me.

Author

Paul Tavares @purtuga

Follow me at Twitter @paul_tavares

Version

Install

SPWidgets requires jQuery and jQuery UI libraries. These should be included or loaded first. There is only 1 SPWidgets file required to be included in the page. This file can be located in the dist folder of the downloaded archive (zip, tar). There are two versions of it:

Include only one of the above reference files:

<script type="text/javascript" src='yoursite/path/to/jquery.SPWidgets.min.js'></script>

SPShowBoard Widget

Given a selector (an html element), this method will insert a Kan-Ban board inside of it based on one of the columns from the desired List. The column must be of type Lookup or Choice, and it's values will be used by this widget to build the Board columns. The widget support both columns set as Required or Optional and has input parameters available to filter the list of columns created. Currently, this widget supports no more than 20 columns total, with no more than 10 displayed at one time.

Below is a screen capture from the available demo:

Board Widget

Usage

$("#board").SPShowBoard({
    list: "Tasks",
    field: "Status"
});

Input Parameters

This method takes as input an object containing the supported options:

    $("#board").SPShowBoard({
        list:                   '',
        field:                  '',
        CAMLQuery:              '<Query></Query>',
        CAMLViewFields:         '',
        fieldFilter:            null,
        optionalLabel:          '(none)',
        allowFieldBlanks:       null,
        template:               null,
        webURL:                 $().SPServices.SPGetCurrentSite(),
        showColPicker:          false,
        height:                 null,
        colPickerLabel:         "Columns",
        colPickerCloseLabel:    "Close",
        colPickerApplyLabel:    "Apply",
        colPickerCheckLabel:    "Check-Uncheck All",
        colPickerMaxColMsg:     "Can not exceed 10 columns!",
        colPickerMinColMsg:     "Mininum of 2 required!",
        onGetListItems:         null,
        onPreUpdate:            null,
        onBoardCreate:          null
    });

The default options for this widget can be manipulated/set via the following object:

    $.SPWidgets.defaults.board = {}

Options

Return Value

This plugin will return a jQuery object that contains the initially selected set of nodes (selector), thus maintaining chainability.

Methods

The following methods are supported:

Events

This widget triggers several events that can be used to perform additional actions from those experienced in the board. In addition to the events below specific to this widget, events are also fired by the jQuery UI sortable interaction.

Examples

Example 1

Simple usage. Simply supply the required input options of list and field.

$("<div/>").appendTo("body")
    .SPShowBoard({
        list:   "Tasks",
        field:  "Status"
    });

Example 2

Simple usage. Creates a board based on the 'Status' field of Tasks list. The Column picker button is displayed, allowing the user to manipulate the columns displayed on teh board and also changs a few of the labels on the column picker.

It also listens for changes in the board's visible columns and writes that information to the console (for those browsers that support it).

$("<div/>")
    .appendTo("body")
    .on("spwidget:boardColumnChange", function(ev, $board, colObj){

        try {

            console.log("spwidget:boardColumnChange = Columns changed: " + colObj.join(" | "));

        } catch(e) {}

    })
    .SPShowBoard({
        list:                   "Tasks",
        field:                  "Status",
        showColPicker:          true,
        colPickerLabel:         "Choose Columns",
        colPickerCloseLabel:    "Close Picker",
        colPickerApplyLabel:    "Change"
    });

Example 3

This example demostrates how knockout.js can be used to create the board item UI and thus take advantage of knockout live data binding. The example below retrieves data from the list using SPServices, converts each row to a knockout aware object and then provides that to the Board widget. SPWidgets Board widget supports objects whose attibute values are of type Function.

$().SPServices({
    operation:      "GetListItems",
    async:          true,
    listName:       "Tasks",
    CAMLRowLimit:   0
})
.done(fucntion(xData, status){

    // Check for errors here

    // Get the list of rows as an array of objects
    var rows        = $(xData.responseXML)
                        .SPFilterNode("z:row")
                        .SPXmlToJson({includeAllAttrs: true}),
        rowIdMap    = {};

    // Convert each object in the array to a knockout object
    $.each(rows, function(i, thisRow){

        // Convert each property on this row to an observable object.
        for ( var column in thisRow ) {

            thisRow[ column ] =  ko.observable( thisRow[ column ] );

        }

        // create a map by ID to this row
        rowIdMap[ thisRow.ID() ] = thisRow;

    });

    // now build the Board
    var $board = $("<div/>").appendTo("body")
        /**
         * Event to listen to the Create and Item Add events.
         * Each time an item is added, we populate the template
         * with knockout.js
         */
        .on("spwidget:boardcreate spwidget:boarditemadd ", function(){

            $board.find("div.fill-template").each(function(){

                // get a local reference to this board item, and
                // retrieve the row ID from the markup (which was
                // included when we created the template)
                var $thisItem = $(this).removeClass("fill-template"),
                    thisRowId   = $thisItem.data("row_id");

                // Apply model to the template
                ko.applyBindings(
                    rowIdMap[ thisRowId ],
                    $thisItem[0]
                );

            });

        })
        /**
         * Create the board
         */
        .SPShowBoard({
            list:   "Tasks",
            field:  "Status",
            CAMLQuery: function(sendDataToBoard) {

                // We already got the data... Just send it to the board
                sendDataToBoard( rows );

            },
            template: function(rowObj, $rowUI) {

                // If UI is already done, exit here.
                if ($rowUI){

                    return;

                }

                // Else, Return the template that will be used by KO later
                return '<div class="fill-template" data-row_id="' +
                        rowObj.ID() + '">' +
                            '<div>' +
                                '<span data-bind="text: ID"></span>' +
                                '(<span data-bind="text: Status"></span>)' +
                            '</div>' +
                            '<div data-bind="html: Description"></div>' +
                        '</div>';

            }
        });

});

Although this example does not do much with knockout, the possibilities are high specially for rich application, for things like caching approaches, data refresh strategies, etc.

SPLookupField Widget

SPLookupField Widget takes an input html field and converts it to a lookup field by displaying an autocomplete input area, for selecting new items from the lookup List, and displaying the already selected items on the page. This widget attempts to provide the same functionality as SharePoint's columns of type Lookup, but using more efficient methods of selecting values and presenting the user with a more modern and consistent user interface/experience across all browsers.

The value stored in the input field, after the user selects an item from the autocomplete field, will use the same format that SharePoint returns when a Lookup field is set, with the exception that only the ID is stored.

Example of the value stored when a single item selected:

1;#

Example of the value stored when a 3 items are selected:

1;#;#2;#;#3;#

A common utility ($.SPWidgets.parseLookupFieldValue) is available for parsing Lookup fields, both those created by this widget as well as those returned by SharePoint's Webservices.

Below is a screen capture from the available demo:

Lookupup Field Widget

Usage

$("input[name='productList']")
    .SPLookupField({
        list: 'Products'
    });

Input Parameters

This method takes as input an object containing the supported options:

$("#board").SPLookupField({
    list:               '',
    allowMultiples:     true,
    inputLabel:         '',
    inputPlaceholder:   'Type and Pick',
    readOnly:           false,
    exactMatch:         true,
    uiContainer:        null,
    selectFields:       ['Title'],
    filter:             '',
    filterFields:       ['Title'],
    template:           '<div>{{Title}} <span class="spwidgets-item-remove">[x]</span></div>',
    listTemplate:       '{{Title}}',
    listHeight:         0,
    onItemAdd:          null,
    onItemRemove:       null,
    onReady:            null,
    msgNoItems:         "",
    maxResults:         50,
    minLength:          2,
    hideInput:          true,
    padDelimeter:       false,
    showSelector:       false
});

The default options for this widget can be manipulated/set via the following object:

    $.SPWidgets.defaults.LookupField = {}

Options

Return Value

This plugin will return a jQuery object that contains the initially selected set of nodes (selector), thus maintaining chainability.

Methods

All methods provided by this widget are invoked by calling SPLookupField on the original input element that the widget was called on but providing the word 'method' as the first argument to the function:

$("input[name='productList']").SPLookupField("method", "method name"[, options] )

Events

No custom events are currently triggered by this widget.

Examples

Example 1

$("input[name='productList']")
    .SPLookupField({
        list: 'Products'
    });

SPControlUpload Widget

jQuery plugin that inserts a widget into page for uploading a file to a SharePoint Document Library without having to leave the page that the user is currently on. This plugin provides a behavior similar to an async ajax call.

At its core, this plugin is simply uses the default SharePoint upload.aspx page inside an iframe, but manipulating it from the hosted page, so that the user is shown only a minimalist UI. Code hooks are provided for allowing a developer to further manipulate the page(s) that may be shown after the initial upload (ex. some libraries require users to fill in additional information and then check in the document. This can all be automated without user input.)

In a normal flow, the upload process follows this sequence:

  1. Display upload form. User selects a file for upload and presses the upload button.
  2. File is uploaded to the server and depending on the setup, a check in page may be displayed.
  3. File is checked in and file upload is complete. Page is redirected to display/list view.

Usage

$("div.file_upload").SPControlUpload({ listName: "Shared Documents" });

Input Parameters

This method takes as input an object containing the following options:

    $("div.file_upload").SPControlUpload({
        listName:               '',
        folderPath:             '',
        uploadDonePage:         '/undefined',
        onPageChange:           null,
        onUploadDone:           null,
        uploadUrlOpt:           '',
        overwrite:              false,
        uploadPage:             '',
        overlayClass:           '',
        overlayBgColor:         'white',
        overlayMessage:         '<div>Working on it</div>',
        selectFileMessage:      "Click here to select file...",
        uploadDoneMessage:      "Upload Successful!",
        fileNameErrorMessage:   "A file name cannot contain any of the following characters: \ / : * ? \" &lt; &gt; | # { } % ~ &amp;",
        noFileErrorMessage:     "No file selected!",
        checkInFormHeight:      '25em',
        webURL:                 currentSiteUrl
    });

The default options for this widget can be manipulated/set via the following object:

    $.SPWidgets.defaults.upload = {}

Options

Event Object

The function defined for the onPageChange input parameter will receive as input an event object generated by this plugin. The object will contain information about the state of the upload process.

The following attributes can be found in the event object:

Return Value

This plugin will return a jQuery object that contains the initially selected set of node, thus maintaining chainability.

Examples

Example 1

Simple example. Upload a file to the Share Documents library and display an alert when complete.

$("#uploadContainer")
    .SPControlUpload({
        listName: 'Shared Documents',
        onUploadDone: function(file){
            alert("File upload Done. File url: " & file.EncodedAbsUrl);
        }
    });

Example 2

The following example creates a jQuery UI dialog to display the upload interface to the user. This example uses the onPageCHange event to do certain validations through out the upload process. The dialog closes after the file is sucessfuly uploaded. It demostrates the use of the event object's state and isUploadDone attributes.

$('<div style="height:350px;width;100%;padding:.5em;"></div>')
    .appendTo("body")
    .dialog()
    .SPControlUpload({
        listName:       "Shared Documents",
        onPageChange:   function(ev){

            // If we're done with the upload, then continue to show the
            // overlay, and fade out the area that contained the upload control.
            if (ev.state == 3 && ev.isUploadDone) {
                ev.hideOverlay = false;
                setTimeout(function(){
                        $(this).dialog("close").dialog("destroy");
                        alert("Upload Done!");
                    }, 1000);

            // If file was uploaded, but we have required fields to fill out,
            // then adjust page to only show the required data...
            } else if (ev.state == 3 && !ev.isUploadDone) {

                // Because we're coming from the same domain, we
                // have full access to the content of the page,
                // and thus we can manipulate it. In this example
                // I hide all chrome and show only the form fields
                // the user should be filling in.
                // Note that this works because in this very simple
                // example, I assume that the required fields form
                // does not have any special fields, like people pickers,
                // etc.
                ev.page.find("form")
                    .children(":visible")
                        .css("display", "none")
                        .addClass("ptWasVisible")
                        .end()
                    .find("input[title='Name']")
                        .closest("div[id^='WebPart']")
                            .appendTo(ev.page.find("form"));
                    }

        }//end: onPageChange()
    });

Example 3

In this example the file that the user is attempting to upload will be checked and if not a PDF file, then an error is displayed and the file is not uploaded.

$('<div style="height:350px;width;100%;padding:.5em;"></div>')
    .appendTo("body")
    .dialog()
    .SPControlUpload({
        listName:       "Shared Documents",
        onPageChange:   function(ev){

            // If we're done with the upload, then continue to show the
            // overlay, and fade out the area that contained the upload control.
            if (ev.state == 3 && ev.isUploadDone) {
                ev.hideOverlay = false;
                setTimeout(function(){
                        $(this).dialog("close").dialog("destroy");
                        alert("Upload Done!");
                    }, 1000);

            // If file was uploaded, but we have required fields to fill out,
            // then adjust page to only show the required data...
            } else if (ev.state == 3 && !ev.isUploadDone) {

                ev.page.find("form")
                    .children(":visible")
                        .css("display", "none")
                        .addClass("ptWasVisible")
                        .end()
                    .find("input[title='Name']")
                        .closest("div[id^='WebPart']")
                            .appendTo(ev.page.find("form"));
                    }

            // User has clicked UPLOAD. If file type not pdf, error
            } else if (ev.state == 2 && ev.action === "preLoad") {
                var uploadFileName = String(ev.page.find("input[type='file']").val());
                if (uploadFileName.match(/\.pdf$/i) === null) {
                    alert("Only PDF file are allowed!!");
                    return false; // Cancel upload
                }

            }
        }//end: onPageChange()
    });

SPDateField Widget

SPDateField is a widgets wrapped around jQuery UI's Datepicker that allows the user to pick one or more dates using their own locale format, while storing the SharePoint friendly format (YYY-MM-DD) in the input field to which this widget was bound to. In addition to wrapping the jQuery UI's datepicker, this widget also provide a timepicker which in turn returns both the date and time in the date format used by SharePoint (ISO 8601). Similar to jQuery UI's Datepicker, this widget can also be used on non-input element, which will cause it to be displayed inline within the HTML selector used.

Below is a screen capture of this widget's being used in a Filter Panel:

SPDateField Widget

SPDateField widget was introduced with v2.2

Usage

$("input[name='DueDate']").SPDateField(); // on input field

$("#spdatepicker").SPDateField(); // on a DIV element

Input Parameters

This method takes as input an object containing the supported options:

    $("#listFilter").SPDateField({
        allowMultiples: false,
        delimeter:      ";",
        remainOpen:     true,
        datepicker:     {
            dateFormat:         'mm/dd/yy',
            buttonImage:        '/_layouts/images/CALENDAR.GIF',
            showOn:             "both",
            buttonImageOnly:    true
        },
        dateTemplate: '{{date}} &lt;span class="spwidgets-item-remove"&gt;[x]&lt;/span&gt;',
        showTimepicker: false,
        timeFormat:     ' {{hour}}:{{minutes}} {{ampm}}',
        timeUTC:        true,
        labelHour:      'Hour',
        labelMinutes:   'Minutes',
        labelAMPM:      'AM|PM',
        labelTime:      'Time',
        labelSet:       'Set',
        onSelect:       null
    });

All input options are optional. The default options for this widget can be manipulated/set via the following object:

    $.SPWidgets.defaults.date = {}

Options

Return Value

This plugin will return a jQuery object that contains the initially selected set of nodes (selector), thus maintaining chainability.

Methods

Events

This widgets does not have any custom events. The input field used to bind this widget to, however, will trigger change events everytime a date is added or removed from it.

Allow Multiples Display

When allowMultiples is set to true, the dates selected by the user will be displayed using the dateTemplate value. That template is wrapped in a <span> element with a css class of spwidgets-item. The example below shows the rendred markup of a date using the default dateTemplate definition:

<span class="spwidgets-item" data-spwidget_dt1="2013-08-01" data-spwidget_dt2="08/01/2013">
    08/01/2013<span class="spwidgets-item-remove">[x]</span>
<span>

Examples

Example 1 - Allow multiple dates

$("input[name='DueDate']").SPDateField({
    allowMultiples: true
});

Example 2 - Define date to Euro format

$("input[name='DueDate']").SPDateField({
    datepicker: {
        dateFormat: "dd/mm/yy"
    }
});

SPFilterPanel Widget

Given a selector (an html element), this method will insert a UI that allows the user to enter filter criteria for a list. The widgets generates CAML filters from that data that can then be used by the hosting application to do further processing (ex. retrieve data).

For columns that will be displayed to the user with a text input field (ex. Text, Note, Computed, etc.) the user can enter multiple keywords by delimitering them with a semicolon. In addition, the following columns are displayed using widgets provided by this library:

Below is a screen capture from the available demo:

Filter Panel Widget

The SPFilterPanel widget was introduced with v2.1

Usage

$("#listFilter").SPFilterPanel({
    list: "Tasks",
    columns: [
        'Title', 'Status', 'AssignedTo', 'Predecessors'
    ],
    onFilterClick: function(filters){

        alert("Number of filters entered by the user: " + filters.count);

    }
});

Input Parameters

This method takes as input an object containing the supported options:

    $("#listFilter").SPFilterPanel({
        list:               '',
        webURL:             'current/site/url/',
        columns:            ['Title'],
        textFieldTooltip:   'Use a semicolon to delimiter multiple keywords.',
        showFilterButton:   true,
        filterButtonLabel:  "Filter",
        onFilterClick:      null,
        onReady:            null,
        ignoreKeywords:     /^(of|and|a|an|to|by|the|or|from)$/i,
        height:             null
    });

The default options for this widget can be manipulated/set via the following object:

    $.SPWidgets.defaults.filter = {}

Options

Return Value

This plugin will return a jQuery object that contains the initially selected set of nodes (selector), thus maintaining chainability.

Methods

Examples

Example 1

$("<div/>").appendTo("body")
    .SPFilterPanel({
        list: "Tasks",
        columns: [
            'Title', 'Status', 'AssignedTo', 'Predecessors'
        ],
        onFilterClick: function(filters){

            alert("Number of filters entered by the user: " + fitlers.count);

        }
    });

Common Utilities

The following is a list of common utilities created internally for the widgets, but built generically and accessible externally.

$.SPWidgets.fillTemplate

A simple templating engine. Meant primarily for use internally by the widgets provided in this library. It simply replaces tokens in a string having a format of {{tokenName}} with the tokeName found in the data to be used to fill out the template. (Since v. 2.0)

Input Parameters

The method accepts as input an Object containing the options below.

Options

Return Value

This method will return a String with the template filled out with the data.

Example

$.SPWidgets.fillTemplate({
    tmplt: '<div>{{Title}}</div>',
    data: [
        { Title: "Record number 1" },
        { Title: "Record number 2" },
        { Title: "Record number 3" },
        { Title: "Record number 4" }
    ]
});

$.SPWidgets.getCamlLogical

Given an array of individual CAML filters, this method will wrap them all in a Logical condition (<And></And> or a <Or></Or>). The result (a string) will be returned to the caller. This method takes care of building the proper format required by the CAML conditional aggregates. (Since v. 2.0)

Input Parameters

The method accepts as input an Object containing the options below.

Options

Return Value

This method return a String containing the concatenated filter values in the appropriate AND or OR logical aggregate.

Example 1

$.SPWidgets.getCamlLogical({
    type: "or",
    values: [
        "<Eq><FieldRef Name='Title' /><Value Type='Text'>Test</Value></Eq>",
        "<Eq><FieldRef Name='Title' /><Value Type='Text'>Test1</Value></Eq>",
        "<Eq><FieldRef Name='Title' /><Value Type='Text'>Test2</Value></Eq>",
        "<Eq><FieldRef Name='Title' /><Value Type='Text'>Test3</Value></Eq>",
        "<Eq><FieldRef Name='Title' /><Value Type='Text'>Test4</Value></Eq>"
    ]
})

Example 2

$.SPWidgets.getCamlLogical({
    type: "and",
    values: [
        "west",
        "east"
    ],
    onEachValue: function(loc){

        return "<Neq><FieldRef Name='Region'/>" +
                "<Value Type='Text'>" + loc + "</Value></Neq>";

    }
})

$.SPWidgets.makeSameHeight(ele, pad)

Given a group of elements, this plugin will set their css height attribute to be at least equal to the tallest item among them. (Since v. 2.0)

Input Parameters

Return Value

The ele input parameters is returned to the caller.

Example

Given the following html markup:

<div class="spwidgets-demo" style="height: 30px;" />
<div class="spwidgets-demo" style="height: 100px;" />
<div class="spwidgets-demo" style="height: 50px;" />
<div class="spwidgets-demo" style="height: 102px;" />

The above elements height would be set to 102px by the following:

$.SPWidgets.makeSameHeight( $("div.spwidgets-demo") );

$.SPWidgets.parseLookupFieldValue(value)

Parses a SharePoint lookup values as returned by webservices (id;#title;#id;#Title) into an array of objects where each object contains the lookup item data (ID and TITLE). (Since v. 2.0)

Input Parameters

Return Value

An array of objects will be returned where each object has two keys; title and id of the lookup item that was parsed. Example:

[
    {
        id: "1",
        title: "Title of lookup item 1"
    },
    {
        id: "2",
        title: "Title of lookup item 2"
    },
    {
        id: "3",
        title: "Title of lookup item 3"
    }
]

Example

$.SPWidgets.parseLookupFieldValue("1;#Title of lookup item 1;#2;#Title of lookup item 2");

$.SPWidgets.SPGetDateString(dateObj, formatType)

Returns a date string in the format expected by SharePoint Date/time fields. Useful when wanting to obtain a date/time string for use in CAML Queries. (Since v. 2.0)

Credit: Matt twitter @iOnline247 in this SPServices post

Input Parameters

Return Value

A string is returned with the date formatted in the appropriate locale.

Example

// Return today's date formatted in local time
// Result example: 2013-05-06T13:08:10
$.SPWidgets.SPGetDateString();

// Return date formatted in UTC time
// Result example: 2013-05-06T17:09:19Z
$.SPWidgets.SPGetDateString(null, "utc");

$().SPGetMsgError

A jQuery method (extension of $.fn) that given a SharePoint webservices response object, will look to see if it contains an error and return that error formatted as a string. The XML response object will be checked for errors that might be returned in the following XML elements:

<ErrorCode />
<faultcode />

(Since v. 2.0)

Input Parameters

None.

Return Value

A string with the first error found in the XML message.

Example

alert( $(xData.responseXML).SPGetMsgError() );

$().SPMsgHasError

A jQuery method (extension of $.fn) that given a SharePoint webservices response object, that given an XML message as returned by the SharePoint WebServices API, will check if it contains an error and return a Boolean indicating that. The XML response object will be checked for errors that might be returned in the following XML elements:

<ErrorCode />
<faultcode />

(Since v. 2.0)

Input Parameters

None.

Return Value

A Boolean will be returned indicating whether the XML message has an error (true) or not (false).

Example

if ( $(xData.responseXML).SPMsgHasError() ) {

    alert("error in xml message.");

}

$.SPWidgets.escapeXML

Given a XML or HTML string, this utility will escape the special characters that can impact rendering when displayed as html or xml. (Since v2.1)

Input Parameters

Return Value

Example

$.SPWidgets.escapeXML("This is <text>.");

returns:

"This is &lt;text&gt;."

$.SPWidgets.unEscapeXML

Given a string, this utility will un-escape any special characters that were escaped by $.SPWigets.escapeXML. (Since v2.1)

Input Parameters

Return Value

Example

$.SPWidgets.escapeXML("This is &lt;text&gt;.");

returns:

"This is <text>."

$.SPWidgets.getSPVersion

Returns the SharePoint version number (Since v2.2).

Input Parameters

Return Value

Example

// Under SP 2010, the following returns 14 (Integer)
$.SPWidgets.getSPVersion();

// Under SP2013, the following returns "2013" (String)
$.SPWidgets.getSPVersion(true);

$.SPWidgets.parseDateString(dateString)

Parses the date providedon input, which is assumed to be in ISO 8601 format, and return a JavaScript Date object.

Input Parameters

Return Value

Example

$.SPWidgets.parseDateString('2013-09-02T12:00:00Z');

$.SPWidgets.parseDateString('2013-09-02T05:35:00');

pickSPUser Widget

Given an input field, this method will display an interface that allows the users to select one or more users from SharePoint and stores the selected user information into the input field in the format expected when making an update via webservices.

The input field will be hidden in its current position and a UI will displayed instead. As the user picks or removes users, the input field will be updated at the same time, thus it will always be ready to be submitted as part of an update to the server.

Usage

$("input[name='users']").pickSPUser();

Input Parameters

This method takes as input an object containing the options below. These can also be set globally by setting them on $.SPWidgets.defaults.peoplePicker.

Return Value

This plugin will return a jQuery object that contains the initially selected set of node, thus maintaining chainability.


Utilities

$().pickSPUser.resolvePrincipals(options)

A utility to resolve user accounts that may not be part of the site collection list info table. This is normally needed when a user's ID is -1: meaning the user is valid, but not part of the site collection (yet). By calling this method and setting the addToUserInfoList input option to true, that user will be added and receive a valid (positive) ID. (Since v.2.3)

Input parameters

Options

Return

Method returns a jQuery Promise (the one from $.ajax()). The promise (if successful) will provide its callback 3 input parameters: data (the xml response document), textStatus and the jQuery XHR request.

Example:

$().pickSPUser.resolvePrincipals({
    principalKey: "DOMAIN\PAUL"
})
.done(function(xmlDoc, textstatus, jqXHR){
    var $doc = $(xmlDoc);
    alert($doc.find("DisplayName").eq(0).text());
});

Methods

All methods are called using the original input element where the People Picker widget was bound with the word 'method' as the first parameter:

$("input[name='user']").pickSPUser("method", "method name here");

The following methods are supported:


Events

The following Events are triggered by this widget


Examples

Bind people picker and allow only 1 person to be selected/stored.

$("input[name='users']").pickSPUser({
    allowMultiples: false
});

When user makes a selection, show alert with person's info.

$("input[name='users']").pickSPUser({
    onPickUser: function(person){
        alert("User selected:

displayName: " + person.displayName + " accountId: " + person.accountId + " accountName: " + person.accountName + " accountType:" + person.accountType); } });