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.
  • A method to allow non-supported protocols in links.
  • A method to automate presence aware with Microsoft Lync and Lotus Sametime instant messaging clients.

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, indeed, any 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.

isEditMode()

Determines if the current page is in Edit mode.

Method Signature

isEditMode()

Arguments

This method has no arguments.

Return

Boolean. “true” if the current page is in Edit mode, “false” if not.

isDialog()

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

isDialog()

Arguments

This method has no arguments.

Return

Boolean. “true” if the current page is being presented in a Dialog, “false” if not.

getFormType()

Used on form pages to determine which type of form is being presented.

Method Signature

getFormType()

Arguments

This method has no arguments.

Return

A string denoting the type of form, or null if the current page is not a form. For type can be “Edit”, “New” or “Display”.

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

callService()

A convenience method simplifying the use of the many web services available to SharePoint users. More information about these services is avaiable in the Windows SharePoint Services 3 documentation. This method requires the use of the DP_AJAX library.

Method Signature

callService(Request, ServiceURL, ServiceMethod, Params)

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.
  • ServiceMethod: String, required. The method being used.
  • Params: Object, optional. An object representing the parameters needed by the Web Service method where the name=value pairs of the object represent parameters and values.

Return

null

getRows()

Returns the rows of a SharePoint Web Service response.

Method Signature

getRows(XML)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callService().

Return

Array. The rows returned by the web service call.

getColumn()

Returns an array representing a single column of a SharePoint Web Service response.

Method Signature

getColumn(XML, ColName)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callService().
  • ColName: String, required. The column to be returned.

Return

Array. All of the values, in returned order, of the requested column from the passed XML.

collateResponses()

A convenience method that inserts all rows from “XML2” into the rows from “XML” where the given columns match. The responses do not have to share column or data structure. Useful for outputting related list data via XSL.

Method Signature

collateResponses(XML, ColName, XML2, ColName2)

Arguments

This method has seven arguments:

  • XML: Object, required. An XML document object as returned by callService().
  • ColName: String, required. The column to be matched with information from XML2.
  • XML2: Object, required. An XML document object as returned by callService().
  • ColName2: String, required. The column to be matched with information from XML1.

Return

XML. The “XML” parameter is modified and returned, the “XML2” parameter is left unchanged.

cleanSP_Numeric()

A convenience method that coverts Numeric-type data as pulled from callService() to the JavaScript numeric type.

Method Signature

cleanSP_UserList(XML, ColName)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callService().
  • 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_MultiLineText()

A convenience method that clean MultiLine Text data as pulled from callService(). Data will be parsed as HTML (normally it would be escaped).

Method Signature

cleanSP_MultiLineText(XML, ColName)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callService().
  • 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 callService(). 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 callService().
  • 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 callService(). 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 callService().
  • 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 callService(). 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 callService().
  • 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 callService(). 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 callService().
  • 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).

cleanSP_Custom()

A convenience method that applies a custom function to data pulled from callService(), optionally creating a new column with the modifed information.

Method Signature

cleanSP_CalculatedField(XML, ColName, Handler, NewColName)

Arguments

This method has seven arguments:

  • XML: Object, required. The XML document object as returned by callService().
  • ColName: String, required. The internal column name to clean (for example “ows_Field”).
  • Handler: Function, required. The function to call. The function should accept a single parameter (the data to be modified) and return the same data type.
  • NewColName: String, Optional. If present, a new column of this name will be created to contain the modified data.

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 Microsoft Lync or Lotus SameTime.

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 function provides the ability to seamlessly use link protocols normally filtered by SharePoint 2007/2010 in wiki pages and content editor web parts. In addition it can provide on-demand presence awareness for Microsoft Lync and Lotus Sametime.

Non-standard Protocols

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 correcting the link). Some examples:

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

Microsoft Lync Presence Awareness Links

While MS Lync automatically provides presence awareness for all “people” objects in SharePoint (authors or “people picker” columns, for example), you can also apply presence awareness to any person or email group. The following example demonstrate how to format such links:

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

Once run, the function will, using the email address (Lync ID) in the link, create the needed code for presence awareness. The name used (the displayed text) can be whatever you feel is useful for the purpose. Obviously, MS Lync must be installed on the client for this feature to function.

Sametime Presence Awareness Links

For those people unfortunate enough to be subjected to Lotus Sametime the function can provide intergrated presence awareness. The following example demonstrate how to format such links:

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

The displayed link must be the Sametime id for the individual. Sametime will replace this with the display name of the individual. As with Lync, Sametime must be installed on the client for this feature to function.

Revision History

April 20, 2016

This is a major update that may invalidate some previously working code.

The following Web Service-specific methods have been removed and replaced by a new, generic method called “callService()”:

  • callListService_Get()
  • callListService_Update()

The following methods have been added:

  • “isEditMode()” to determine if the current page is in edit mode.
  • “isDialog()” to determine if the current page is being presented in a dialog.
  • “getRows()” to return the rows of a Web Service response.
  • “getColumn()” to return a single column of a Web Service response as an array.
  • “collateResponses()” used to merge the matching rows of a Web Service response into another Web service response.
  • “cleanSP_Numeric()” a new cleaning method for Web Service responses.

Of course there are also the usual “numerous bug fixes and optimizations”.

September 20, 2014

  • Added Microsoft Lync presence awareness to the “ReplaceLinks” function.
  • Improved the ReplaceLinks function to be more robust on highly dynamic pages.

September 29, 2013

  • Initial release.

3 Comments

Add a Comment

Leave a Reply

DepressedPress.com © 2014 Frontier Theme