DP_SharePoint

The DP_SharePoint library provides tools to make working with Microsoft SharePoint simpler. The library has been tested with Sharepoint 2007 and 2010.The script provides:

  • Methods to acquire JavaScript handlers to SharePoint form controls and fields. This make it much simpler to interrogate or add event handlers to SharePoint forms.
  • Simple methods to add or remove events from SharePoint form elements.
  • Simple methods to hide and show elements of SharePoint forms.
  • Methods to simplify the calling and use of SharePoint web services and ready the data returned from them for use.

The extension is self-contained and presents an extremely small footprint. Only a single global object, “DP_SharePoint”, is created.

Please note: This is a work-in-progress and should be considered BETA-quality for all purposes. Many features are partially complete or experimental. This script is primarily tested and developed against a single SharePoint environment (the only one the author has access to). The enviroment, currently running SP 2010, is tightly controlled. The only currently browser platform is Internet Explorer 8, no access to SharePoint designer or inddedany back-end development is allowed. If you are able to confirm that the component functions as designed in other versions of SharePoint or browser platforms, please share!

Download

The component is available from GitHub:

All downloads and code are covered by our Source Code Policy.

Usage

The script consists of a single JavaScript file with a .JS extension.

Importing the Library

The library must be imported before it is used. To import the library use the <script> tag. For example:

<script type="text/javascript" src="DP_SharePoint.js"></script>

Your path may vary depending on the location of the script on your server.

Accessing the Object

Importing the script automatically creates a new, global JavaScript object called “DP_SharePoint“. To use a method of the object call it directly:

var myFieldRef = DP_SharePoint.getFieldRef("Field Name");

See the Examples section for some sample code.

Properties and Methods

The DP_Cookies object contains no properties.

DP_Cookies methods available:

Note that in method/function signatures a pipe (“|”) indicates “OR” while arguments in square brackets are optional.

getControlRef()

Used on form pages to collect element references to the “OK”, “Save” and “Cancel” buttons. These references can be used to change, hide or add events to these buttons.

Method Signature

getControlRef()

Arguments

This method has no arguments.

Return

A collection (Object) of Arrays. Two collections of references are returned as Arrays. The first, “Submit”, will contain references to all “OK” or “Save” buttons in the order they appear on the page (many pages replicate the control set at the top and the bottom). The second, “Cancel”, contains references to all “Cancel” buttons in the order they appear on the page.

getFieldRef()

Used on form pages (Edit, new and display) to return references to individual fields. These references can be used to modifiy the display, add events or otherwise manipulate these fields. The exact values returned will depend on the type of field being accessed.

Method Signature

getFieldRef(Title)

Arguments

This method has one argument:

  • Title: String, Required. The name of the field. Note that this is the name of the field as displayed on the form, not the internal name of the field.

Return

Object. The following properties are included:

  • RowRef: Node Reference. A reference to the TR tag containing the field.
  • Name: String. The name of the field.
  • InternalName: String. The internal, “SharePoint”, name of the field.
  • Type: String. The type of the field (see below).
  • SubType: String. If applicable, the Sub type of the field. For field Types with no SubTypes this property will be an empty string.
  • ElRef: Object. This property contains specific references to the element(s) that make up the field, based on field Type and SubType as follows (subtypes will be denoted with parenthesis):
    Type SubType Returns
    SPFieldText
    SPFieldNumber
    SPFieldCurrency
    SPFieldBoolean
    N/A Node Reference. The INPUT element of the field.
    SPFieldChoice
    SPFieldMultiChoice
    Select Node Reference. The SELECT element of the field.
    SelectWithCustom Object containing these properties:

    • Select: Node Reference. The SELECT element of the field.
    • Custom: Node Reference. The INPUT element where a user can enter a custom choice.
    • CustomChoice: Node Reference. The INPUT element (type of RADIO) of the field denoting whether the user has selected to enter a new value or use one of the dropdown values.
    Radio
    Checkbox
    Object containing these properties:

    • Choices: Array. A collection of references to the INPUT elements.
    RadioWithCustom
    CheckboxWithCustom
    Object containing these properties:

    • Choices: Array. A collection of references to the INPUT elements.
    • Custom: Node Reference. The INPUT element where a user can enter a custom choice.
    • CustomChoice: Node Reference. The INPUT element (type of RADIO) of the field denoting whether the user has selected to enter a new value or use one of the dropdown values.
    SPFieldNote N/A Object containing these properties:

    • TextArea: Node Reference. The TEXTAREA element of the field.
    • EditorDoc: Node Reference. A reference to the editor associated with the field.
    SPFieldLookup Select Node Reference. The INPUT element of the field.
    Input Node Reference. The INPUT element of the field.
    SPFieldLookupMulti N/A Object containing these properties:

    • Source: Node Reference. Hidden element representing the allowable values.
    • Candidates: Node Reference. The multi-select element containing possible options.
    • Selected: Node Reference. The multi-select element containing those options selected by the user.
    • AddButton: Node Reference. A reference to the button that moves selected options from the Candidates list to the Selected list.
    • RemoveButton: Node Reference. A reference to the button that moves selected options from the Selected list to the Candidates list.
    SPFieldUser
    SPFieldUserMulti
    N/A Object containing these properties:

    • Display: Node Reference. The TEXTAREA element displaying the selected names.
    • InputData: Node Reference. The hidden element containing the “UserFieldValue” (information relating to the people data).
    • SpanData: Node Reference. The hidden element containing the “SpanData” (an alternate representation of people data).
    • XMLData: Node Reference. The hidden element containing the “OriginalEntities” (the raw XML representation of people data).
    • CheckNamesLink: Node Reference. A reference to the link used to “Check Names” on the people-picker.
    • BrowseNamesLink: Node Reference. A reference to the link used to open the “Browse” dialog.
    SPFieldDateTime Date Object containing these properties:

    • Date: Node Reference. The INPUT element containing the date.
    DateTime Object containing these properties:

    • Date: Node Reference. The INPUT element containing the date.
    • Hours: Node Reference. The SELECT element containing the hours options.
    • Minutes: Node Reference. The SELECT element containing the minutes options.
    SPFieldURL N/A Object containing these properties:

    • URL: Node Reference. The INPUT element containing the URL for the link.
    • Label: Node Reference. The INPUT element containing the label for the link.

addFieldEvent()

A convenience method to add custom events to HTML elements. Note handlers added will not override existing handlers.

Method Signature

addFieldEvent(Element, Event, Handler)

Arguments

This method has three arguments:

  • Element: Element Reference, Required. A JavaScript reference to the field on which to add the event.
  • Event: String, Required. The type of event for which the handler will be registered (for example “click” or “onload”).
  • Field: Function, Required. The function to call when the event fires.

Return

Null

removeFieldEvent()

A convenience method to remove custom events from HTML elements.

Method Signature

removeFieldEvent(Element, Event, Handler)

Arguments

This method has three arguments:

  • Element: Element Reference, Required. A JavaScript reference to the field from which to remove the event.
  • Event: String, Required. The type of event for which the handler is registered (for example “click” or “onload”).
  • Field: Function, Required. The function assigned to the event.

Return

Null

hideField()

Hides the passed field (sets the “display” to “none”).

Method Signature

hideField(Field)

Arguments

This method has one argument:

  • Field: Object, Required. A field reference as returned by getFieldRef().

Return

True

showField()

Shows a previously hidden field (sets the “display” to “inline”).

Method Signature

showField(Field)

Arguments

This method has one argument:

  • Field: Object, Required. A field reference as returned by getFieldRef().

Return

True

callListService_Get()

A convenience method simplifying the use of the GetListItems method of the SharePoint Lists Web Service (see the linked documentation for information on the optional parameters below). This method requires the use of the DP_AJAX library.

Method Signature

callListService_Get(Request, ServiceURL, ListName, ViewName[, Query][, QueryOptions][, ViewFields])

Arguments

This method has seven arguments:

  • Request: Object, required. The request instance to use as defined in the DP_AJAX library.
  • ServiceURL: String, required. The URL to the Lists Web Service.
  • ListName: The internal name (GUID) of the list to be queried in the format “{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}”.
  • ViewName: The internal name (GUID) of the list view to be queried in the format “{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}”.
  • Query: String, optional. The CAML query to apply to the call as a fragment of XML (for example “…”).
  • QueryOptions: String, optional. The query options to apply to the call as a fragment of XML.
  • ViewFields: String, optional. The fields to return within the query results as a fragment of XML.

Return

null

callListService_Update()

A convenience method simplifying the use of the UpdateListItems method of the SharePoint Lists Web Service (see the linked documentation for information on the optional parameters below). This method requires the use of the DP_AJAX library.

Method Signature

callListService_Update(Request, ServiceURL, ListName, Batch)

Arguments

This method has seven arguments:

  • Request: Object, required. The request instance to use as defined in the DP_AJAX library.
  • ServiceURL: String, required. The URL to the Lists Web Service.
  • ListName: The internal name (GUID) of the list to be queried in the format “{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}”.
  • Batch: The changes (adds, edits and deletes) to apply to the list as a fragment of XML.

Return

null

cleanSP_MultiLineText()

A convenience method that attempts to clean-up multi-line text data as pulled from the callListService_Get(). The data will be parsed as HTML for display.

Method Signature

cleanSP_MultiLineText(XML, ColName)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callListService_Get().
  • ColName: String, required. The internal column name to clean (for example “ows_Field”).

Return

Object. The XML document passed as input is returned (changes are made in-place).

cleanSP_UserList()

A convenience method that attempts to clean-up userlist data as pulled from the callListService_Get(). The data will have the database keys and delimiters removed.

Method Signature

cleanSP_UserList(XML, ColName)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callListService_Get().
  • ColName: String, required. The internal column name to clean (for example “ows_Field”).

Return

Object. The XML document passed as input is returned (changes are made in-place).

cleanSP_CalculatedField()

A convenience method that attempts to clean-up userlist data as pulled from the callListService_Get(). The data will have the database delimiters removed.

Method Signature

cleanSP_CalculatedField(XML, ColName)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callListService_Get().
  • ColName: String, required. The internal column name to clean (for example “ows_Field”).

Return

Object. The XML document passed as input is returned (changes are made in-place).

cleanSP_LookupList()

A convenience method that attempts to clean-up userlist data as pulled from the callListService_Get(). The data will have the database keys and delimiters removed.

Method Signature

cleanSP_LookupList(XML, ColName)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callListService_Get().
  • ColName: String, required. The internal column name to clean (for example “ows_Field”).

Return

Object. The XML document passed as input is returned (changes are made in-place).

cleanSP_DateTime()

A convenience method that attempts to clean-up userlist data as pulled from the callListService_Get(). This method requires that DP_DateExtensions be available.

Method Signature

cleanSP_DateTime(XML, ColName, TimeFormat, DateFormat, NonDateValue)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callListService_Get().
  • ColName: String, required. The internal column name to clean (for example “ows_Field”).
  • TimeFormat: String, required. The mask to apply to the time value (as documented in DP_DateExtensions).
  • DateFormat: String, required. The mask to apply to the date value (as documented in DP_DateExtensions).
  • NonDateValue: String, required. The value to use as a placeholder in cases where the passed value is not a date or empty.

Return

Object. The XML document passed as input is returned (changes are made in-place).

ReplaceLinks()

A function that will replace specially formatted links allowing the use of normally restricted protocols such as “notes://” or “FMP7://”. There is also special processing available for those using Lotus SameTime. See the examples section for more information.

Method Signature

ReplaceLinks()

Arguments

This method has no arguments.

Return

null.

Examples

As noted the script must be imported (<script type=”text/javascript” src=”DP_SharePoint.js”></script>). Once the script has been imported the DP_SharePoint object is ready for use.

Working with Field References

The getFieldRef() function makes it simple to get a JavaScript reference to a SharePoint field on any “new”, “edit” or “display” page. The function returns an object with several standardized properties. Likely the most accessed property will be “ElRef” which returns, for simple fields, a direct node reference to the field and, for more complex fields, an object containing references to the constituent parts of the field based on the type of field (see the document for the full breakdown).

Calling the function only requires the display name (not the internal name) of the field in question. To get a reference to the field “First Name” you would use:

		var FirstName = DP_SharePoint.getFieldRef("First Name");
	

After doing this you could access FirstName.RowRef.style, for example, to modify the style of the TR tag containing the field. Once the reference is obtained any DOM properties associated with it are available and can be used just as if you retrieve the reference in a more conventional manner.

To demonstrate here is a simple problem. You want to insure that the field “First Name” is populated, but only if another field (a drop-down), “Status” has the value “Active”. This is simple to accomplished with vanilla JavaScript once you get references to the fields in question:

		function CustomValidation() {
			var Status = DP_SharePoint.getFieldRef("Status").ElRef;
			var FirstName = DP_SharePoint.getFieldRef("First Name");
			if ( Status.options[Status.selectedIndex].text == "Active" ) {
				if ( FirstName.ElRef.value == "" ){
					alert("First Name is required when Status is 'Active'.");
				};
			};
		};
	

The field type “SPFieldLookupMulti” presents the user with two selection boxes (“Candidates” and “Selected”) and two controls (“AddButton” and “RemoveButton”). One common problem with this control is that the options provided are partially hidden by the too-narrow fields. To allow those fields to expand to fill the available space you could do the following:

		var MySelections = DP_SharePoint.getFieldRef("My Selections").ElRef;
		MySelections.Candidates.style.width = null;
		MySelections.Selected.style.width = null;
	

Leveraging SharePoint Helper Functions

SharePoint provides a built-in function call, PreSaveAction(). If this function exists it will be called when the “Save” button is pressed on a form. If the function returns “false” the submit will be cancelled and if “true” it will be commited. This gives you a way to easily perform “onsubmit” style validations. Our function from above could be rewritten like this:

		function PreSaveAction() {
			var FirstName = DP_SharePoint.getFieldRef("First Name");
			if ( FirstName.ElRef.value != "" ){
				return true;
			} else {
				return false;
			};
		};
	

A second useful internal function is “_spBodyOnLoadFunctionNames.push();”. This function accepts a function name (as a string) as input and will automatically run that function after the page has fully loaded. This allows you to place your form-management code anywhere on the page you like. To load the code to manage the width of our select field we could use the following:

		function SetSelectWidth() {
			var MySelections = DP_SharePoint.getFieldRef("My Selections").ElRef;
			MySelections.Candidates.style.width = null;
			MySelections.Selected.style.width = null;
		};
		_spBodyOnLoadFunctionNames.push("SetSelectWidth");
	

Adding Events to Fields

The addFieldEvent() and removeFieldEvent() functions help to manage events on fields. Two decent primers on events are available at quirksmode.org and Wikipedia.org.

Assume you have a field called “User Name” and when it’s entered you want to run an AJAX function, validateUserName(), that determines if the name is available. You could create a “change” event on such a field like this:

		var UserName = DP_SharePoint.getFieldRef("User Name");
		DP_SharePoint.addFieldEvent(UserName.ElRef, "change", validateUserName);
	

Note that you first get a reference to the field using the getFieldRef() function. You then add the field event using the addFieldEvent() functon. It accepts a form field reference (“ElRef” here although the specifics will change depending on the kind of field you’re accessing), the event type (“change” here) and finally a handler (function) to be called when the even fires (“validateUserName” here, with no parenthesis as we’re passing the function rather than running it).

Events added will not interfere with existing events and multiple handlers can be added to any event type (they will run in the order that they were added).

Hiding and Showing Fields

The hideField() and showField() functions can be used on SharePoint forms to remove fields from the page (and show them again if you change your mind) that you’d rather not have displayed. These may include calculated fields that simply reformat other fields, fields that are filled in automatically by other processes or any other reason you may have. The functions accept a reference from the getFieldRef() function as input. To later remove the event pass the exact some input to the removeFieldEvent() function.

If you’d like to hide the field named “Test Field” you can use the following (note that this code must appear after the field is loaded):

		DP_SharePoint.hideField(DP_SharePoint.getFieldRef("Test Field"));
	

ReplaceLinks Function

The DP_SharePoint_ReplaceLinks library provides the ability to seamlessly use link protocols normally filtered by SharePoint 2007/2010 in wiki pages and content editor web parts.

  • Can be included directly into Content Editor Web Parts (which can then be saved as reusable Web Parts and added to Wiki pages).
  • Allows for any scheme (protocol) (Notes, RTSP, etc.) to be used within SharePoint content
  • Adds special support for Lotus Sametime prescence awareness.

Links are created in the following format: news://*NewProtocol*Address. Once run the funtion will replace “news” with whatever appears between the asterisks in the link and asterisks and new protocol will be deleted. Some examples:

		news://*notes*DFGTA001/175479E7006436WS7//3G6EF1B738547906F3652476D000225EER
		news://*FMP7*127.0.0.1/MyDatabase
		news://*rtsp*www.youtube.com/somefile.3gp
	

Sametime Presence Awareness Links

For those people unfortunate enough to be subjected to Lotus Sametime the function can provide intergrated presence awareness. For this to function SameTime must be installed on the client machine. The following example demonstrate how to format such links:

		<a href="*sametime*">name@company.com</a>
	

Revision History

September 29, 2013

  • Initial release.

3 Responses to DP_SharePoint

  1. Pingback: Announcing DP_SharePoint | The DepressedPress

  2. Pingback: Obtaining a JavaScript Reference to a SharePoint Field | The DepressedPress

  3. Pingback: Adding Events to SharePoint Fields | The DepressedPress

Share your Opinion

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: