SPWidgets

SharePoint Custom UI Widgets

View the Project on GitHub purtuga/SPWidgets

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.

Dependencies

SPWidgets has the following dependencies:

  1. jQuery
  2. jQuery UI
  3. SPServices

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='http://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/0.7.1a/jquery.SPServices-0.7.1a.min.js'></script>
<script type="text/javascript" src='yoursite/path/to/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

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 following options

Return Value

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

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: \n displayName: " + 
            person.displayName + "\n accountId: " +
            person.accountId + "\n accountName: " +
            person.accountName + "\n accountType:" +
            person.accountType);
    }
});

SPControlUpload Widget

jQuery plugin that inserts a widget into page for uploading a file to a SharePoint location (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

$("input[name='users']").SPControlUpload({
    listName: "Shared Documents",
    onPageChange: function(ev){
        if (ev.state === 3) {
            ev.hideOverlay = false;
            alert("Upload Done!");
        }
    }
});

Input Parameters

This method takes as input an object containing the following 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

The following example creates a jQuery UI dialog to display the upload interface to the user. 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 2

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()
    });

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 whose 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.

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)',
        template:       null,
        webURL:         $().SPServices.SPGetCurrentSite(),
        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

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

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

Example 2

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

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

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

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() );

$.fn.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.");

}