Dev Notes

Notes on Development with Microsoft Technologies

Using SPServices to get the values of a Choice Field

2 Comments

In a recent requirement for a client, I needed to get a list of all the available choices to provide as a filter to a data view web part. One option would be to iterate over the entire list and return all of the unique values, but this list could contain upward of 3000 items. It wouldn’t be the most efficient way to handle less than 20 filter values. The second option is to get the available options from the list schema, and this is the option I decided to choose.

Prerequisites

In order to complete this task, the following javascript libraries are needed:

  • jQuery 1.4.x
    The core jQuery library. I am currently using 1.4.2 in my production environment.
  • SPServices 0.5.7
    A jQuery plug-in used to communicate with the SharePoint 2007 web services.
Method

I began by adding the scripts to a document library in SharePoint and created a new ASPX page. On the new ASPX page, I added my script references for jQuery 1.4.x and SPServices:

<head runat="server">
<META name="WebPartPageExpansion" content="full">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled 1</title>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="JS/jquery.SPServices-0.5.7.min.js"></script>
</head>

Next, I added some place holders for my menu options:

<div id="SiteList" class="dataview-group-panel">
	<div class="dataview-heading">Site</div>
</div>
<div id="DocumentVersion" class="dataview-group-panel">
	<div class="dataview-heading">Document Version</div>
</div>

Now, for the heavy lifting I created a new function that executes SPServices to get the list schema information and return it to two separate functions for parsing.

Here is the function for executing SPServices to call the Lists web service.

function LoadSiteList()
{
	$().SPServices({
		operation: "GetList",
		listName: "Department Instructions",
		completefunc: function(xData, Status) { 
                                  parseSiteField(xData, Status); 
                                  parseDocVersionField(xData, Status); 
                             },
		async: false
	});
}

This function simply makes a call to the lists.asmx web service and executes a call to get the list schema for the specified list. The returned list schema looks similar to the following:

      <GetListResult>
        <List DocTemplateUrl="" DefaultViewUrl="/sites/policy/di/Forms/myDocuments.aspx"
        MobileDefaultViewUrl="" ID="{67E5E03B-A930-4D47-9097-D4A7A03FF497}"
        Title="Department Instructions" Description="" ImageUrl="/_layouts/images/itdl.gif"
        Name="{67E5E03B-A930-4D47-9097-D4A7A03FF497}" BaseType="1"
        FeatureId="00bfea71-e717-4e80-aa17-d0c71b360101" ServerTemplate="101" Created="20101021 09:01:00"
        Modified="20101025 09:06:43" LastDeleted="20101025 08:31:00" Version="129"
        Direction="none" ThumbnailSize="" WebImageWidth="" WebImageHeight="" Flags="79695880" ItemCount="33"
        AnonymousPermMask="0" RootFolder="/sites/policy/di"
        ReadSecurity="1" WriteSecurity="1" Author="1" EventSinkAssembly="" EventSinkClass="" EventSinkData=""
        EmailInsertsFolder="" EmailAlias="" WebFullUrl="/sites/policy" WebId="464d650f-041e-4209-8877-80b77b7511bb"
        SendToLocation="|" ScopeId="59d29d47-5a65-48b9-8a03-698972e7702e" MajorVersionLimit="0" MajorWithMinorVersionsLimit="0"
        WorkFlowId="" HasUniqueScopes="False" AllowDeletion="True" AllowMultiResponses="False" EnableAttachments="False"
        EnableModeration="False" EnableVersioning="False" Hidden="False" MultipleDataList="False" Ordered="False"
        ShowUser="True" EnableMinorVersion="False" RequireCheckout="False">
          <Fields>
			<!-- EDITED FOR BREVITY -->
            <Field Type="Choice" DisplayName="Document Version"
            Required="FALSE" Format="Dropdown" FillInChoice="FALSE"
            Group="Policy Custom Columns"
            ID="{c13091c2-f9c7-4437-969a-c33bd54ce38a}"
            SourceID="{464d650f-041e-4209-8877-80b77b7511bb}"
            StaticName="Doc_Version" Name="Doc_Version"
            Description="Select the appropriate revision (or New)."
            Version="2" Customization="" ColName="nvarchar11"
            RowOrdinal="0">
              <CHOICES>
                <CHOICE>New</CHOICE>
                <CHOICE>CX</CHOICE>
                <CHOICE>A</CHOICE>
                <CHOICE>B</CHOICE>
                <CHOICE>C</CHOICE>
                <CHOICE>D</CHOICE>
                <CHOICE>E</CHOICE>
                <CHOICE>F</CHOICE>
                <CHOICE>G</CHOICE>
                <CHOICE>H</CHOICE>
                <CHOICE>I</CHOICE>
                <CHOICE>J</CHOICE>
                <CHOICE>K</CHOICE>
                <CHOICE>L</CHOICE>
                <CHOICE>M</CHOICE>
                <CHOICE>N</CHOICE>
                <CHOICE>O</CHOICE>
                <CHOICE>P</CHOICE>
                <CHOICE>Q</CHOICE>
                <CHOICE>R</CHOICE>
                <CHOICE>S</CHOICE>
                <CHOICE>T</CHOICE>
                <CHOICE>U</CHOICE>
                <CHOICE>V</CHOICE>
                <CHOICE>W</CHOICE>
                <CHOICE>X</CHOICE>
                <CHOICE>Y</CHOICE>
                <CHOICE>Z</CHOICE>
              </CHOICES>
            </Field>
 			<!-- EDITED FOR BREVITY -->
            <Field Type="MultiChoice" DisplayName="Site"
            Required="FALSE" FillInChoice="TRUE"
            Group="Policy Custom Columns"
            ID="{98ae721c-ba01-4da1-8c61-177fa550871a}"
            SourceID="{464d650f-041e-4209-8877-80b77b7511bb}"
            StaticName="Site" Name="Site" Customization=""
            ColName="ntext2" RowOrdinal="0"
            Description="Select the site(s) the document applies to."
            Version="2">
              <CHOICES>
                <CHOICE>Site 1</CHOICE>
                <CHOICE>Site 2</CHOICE>
                <CHOICE>Site 3</CHOICE>
              </CHOICES>
            </Field>
 			<!-- EDITED FOR BREVITY -->
          </Fields>
          <RegionalSettings>
            <Language>1033</Language>
            <Locale>1033</Locale>
            <AdvanceHijri>0</AdvanceHijri>
            <CalendarType>1</CalendarType>
            <Time24>False</Time24>
            <TimeZone>360</TimeZone>
            <SortOrder>2070</SortOrder>
            <Presence>True</Presence>
          </RegionalSettings>
          <ServerSettings>
            <ServerVersion>12.0.0.6545</ServerVersion>
            <RecycleBinEnabled>True</RecycleBinEnabled>
            <ServerRelativeUrl>/sites/policy</ServerRelativeUrl>
          </ServerSettings>
        </List>
      </GetListResult>

The list schema includes all of the data related to the list, including the fields that make up the list. Leveraging this information, the schema can be parsed by jQuery to get the values for each choice column where I’m interested in providing filtered values.

The first field to parse is the Site field. To parse the data, simply use the soap response with an appropriate jQuery selector, in this case each field definition is defined as a <Field … />. One of the available attributes is DisplayName. Using this information, the selector becomes Field[DisplayName='[[NAME OF FIELD]]’] CHOICE. Now, simply plug this into a javascript function and target the appropriate placeholder:

function parseSiteField(xData, Status) {
	if(Status == 'success') {
		var SiteList = $("#SiteList");
		$(xData.responseXML).find("Field[DisplayName='Site'] CHOICE").each( function () {
			$(SiteList).append("<div class=\"dataview-choice-option\">" + $(this).text() + "</div>");
			}
		);
	}
}

And again, notice the jQuery selector for a different field:

function parseDocVersionField(xData, Status) {
	if(Status == 'success') {
		var DocVersion = $("#DocumentVersion");
		$(xData.responseXML).find("Field[DisplayName='Document Version'] CHOICE").each( function () {
			$(DocVersion).append("<div class=\"dataview-choice-option\">" + $(this).text() + "</div>");
			}
		);
	}
}

Now, instead of iterating over the entire list to find filter values, I simply use the List’s schema to get the available filters for any choice column in a list.

Advertisements

Author: Chris Quick

I have been a developer of web based solutions since early 2001 delivering solutions to a wide array of organizations using ASP, ASP.NET and SharePoint. I was introduced to SharePoint in 2003 when the consulting firm I worked for at the time introduced it into the workplace. I began working with MOSS 2007 as soon as Microsoft released the RTM version in November 2006. The platform was implemented at the organization I worked for in 2007 and went live in March of that year. I was tasked with the administration and ongoing development of the platform. I currently work as a SharePoint Architect with Artis Consulting, developing solutions for a wide variety of business problems. The goal of this blog is to share my discoveries developing solutions with SharePoint. I welcome your comments and feedback to any post -- and I welcome suggestions for future topics.

2 thoughts on “Using SPServices to get the values of a Choice Field

  1. Worked great…how can use it for getting values of Lookup column

  2. Could not get it working in IE 10. Firefox OK though.
    Thanks, great post.

Leave a Reply

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