Friends, Technology, Web2.0 - What I am reading

    [Home] [Recent] [Site Map]

   

Using Javascript to Manipulate a List Form Field

The following blog entry is a cross-posting from the SharePoint Designer Team Blog. It has received lots of kudos, so I thought that it deserves a bit more visibility.

<Lawrence />

 

Hi, my name is Rob Howard, and I’m a Program Manager with the SharePoint Designer team. Like several of the other people posting here, I also built many of the Application Templates for Windows SharePoint Services.

If you’re familiar with them, you may have noticed that in several of the application templates we use a bit of Javascript to set default form values based on the query string. Because we found this to be useful in many different cases throughout our applications, I wanted to share our method with you guys so that you can include it in the applications you develop.

When might you use this?

It’s pretty easy to set a field’s default value through the list settings in the browser UI, so why might you need Javascript to set a default field value? The reason is that field default values can only take static values or simple formulae based on the current user or today’s date. If that meets your needs, then I’d definitely recommend sticking with that method. Sometimes, though, you may want the form to fill with default values based on the user’s interaction with the previous page, and that’s exactly where this method comes in.

How does it work?

In short, we add some Javascript to the page that runs when the body is loaded. This Javascript parses the page’s query string, locates the HTML objects that are rendered by the relevant SharePoint fields, and sets their value based on the information in the query string.

getTagFromIdentifierAndTitle

The most important part of our solution is the “getTagFromIdentifier” function. This function finds the HTML element rendered by a given SharePoint FormField control. It takes the following parameters:

Here’s a partial table of SharePoint column types and their corresponding “identifiers” and “tagNames”:

SharePoint Field Type identifier tagName
Single Line of Text TextField input
Multiple Lines of Text TextField input
Number TextField input
Currency TextField input
Choice (dropdown) DropDownChoice select
Lookup (single)* Lookup select
Lookup (multiple) SelectCandidate; SelectResult select
Yes/No BooleanField input

*Lookups are a bit more complicated because Lookup FormFields render differently when the target list contains more than 20 items. See the end of the post for an example.

function getTagFromIdentifierAndTitle(tagName, identifier, title) {

  var len = identifier.length;

  var tags = document.getElementsByTagName(tagName);

  for (var i=0; i < tags.length; i++) {

    var tempString = tags[i].id;

    if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {

      return tags[i];

    }

  }

  return null;

}

fillDefaultValues

Now that we have the HTML elements that we want to set, we need the values with which to set them. In our solution, we wrote the “fillDefaultValues” function, which parses the page’s querystring and then uses the values to set the field defaults.

function fillDefaultValues() {

  var qs = location.search.substring(1, location.search.length);

  var args = qs.split("&");

  var vals = new Object();

  for (var i=0; i < args.length; i++) {

    var nameVal = args[i].split("=");

    var temp = unescape(nameVal[1]).split("+");

    nameVal[1] = temp.join(" ");

    vals[nameVal[0]] = nameVal[1];

  } 

  // Set HTML element default values here

}

_spBodyOnLoadFunctionNames

In most cases SharePoint pages are based on a master page that contains the “body” element. These content pages can’t directly add a function to the body’s onload event. In order to work around this limitation, SharePoint provides the “_spBodyOnLoadFunctionNames” array. When the body is loaded, the onload event handler executes each function whose name is contained in this array. We added “fillDefaultValues” to the array so that it would run when the body’s onload event fires.

_spBodyOnLoadFunctionNames.push("fillDefaultValues");

All Together Now

With the script above, you can set most different field types to any value from the querystring – or any other source that javascript can access. Below is a full example of the script we use to set the default value of a Lookup field based on an ID stored in the querystring. You’ll notice that setting a Lookup field is a bit more complicated than some other field types. The reason is that Lookup FormFields are rendered with different HTML when the target list contains more than 20 items.

Enjoy!

<script type="text/javascript">

 

// This javascript sets the default value of a lookup field identified

// by <<FIELD DISPLAY NAME>> to the value stored in the querysting variable

// identified by <<QUERYSTRING VARIABLE NAME>>

 

 

// Customize this javascript by replacing <<FIELD DISPLAY NAME>> and

// <<QUERYSTRING VARIABLE NAME>> with appropriate values.

// Then just paste it into NewForm.aspx inside PlaceHolderMain

 

_spBodyOnLoadFunctionNames.push("fillDefaultValues");

 

function fillDefaultValues() {

  var qs = location.search.substring(1, location.search.length);

  var args = qs.split("&");

  var vals = new Object();

  for (var i=0; i < args.length; i++) {

    var nameVal = args[i].split("=");

    var temp = unescape(nameVal[1]).split("+");

    nameVal[1] = temp.join(" ");

    vals[nameVal[0]] = nameVal[1];

  } 

  setLookupFromFieldName("<<FIELD DISPLAY NAME>>", vals["<<QUERYSTRING VARIABLE NAME>>"]);

}

 

function setLookupFromFieldName(fieldName, value) {

  if (value == undefined) return;

  var theSelect = getTagFromIdentifierAndTitle("select","Lookup",fieldName);

 

// if theSelect is null, it means that the target list has more than

// 20 items, and the Lookup is being rendered with an input element

 

  if (theSelect == null) {

    var theInput = getTagFromIdentifierAndTitle("input","",fieldName);

    ShowDropdown(theInput.id); //this function is provided by SharePoint

    var opt=document.getElementById(theInput.opt);

    setSelectedOption(opt, value);

    OptLoseFocus(opt); //this function is provided by SharePoint

  } else {

    setSelectedOption(theSelect, value);

  }

}

 

function setSelectedOption(select, value) {

  var opts = select.options;

  var l = opts.length;

  if (select == null) return;

  for (var i=0; i < l; i++) {

    if (opts[i].value == value) {

      select.selectedIndex = i;

      return true;

    }

  }

  return false;

}

 

function getTagFromIdentifierAndTitle(tagName, identifier, title) {

  var len = identifier.length;

  var tags = document.getElementsByTagName(tagName);

  for (var i=0; i < tags.length; i++) {

    var tempString = tags[i].id;

    if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {

      return tags[i];

    }

  }

  return null;

}

</script>


>>
Source Link
>>Blog: Microsoft SharePoint Products and Technologies Team Blog
>>Publish Date: 6/23/2007 7:13:37 AM
>>Keywords: field sharepoint

Related Posts
>>Creating Custom Field Types #
    I love the new Person or Group column type in SharePoint, but a recent project required a lookup of people in a certain Active Directory group. Seeing as it appears that you cannot customise the Perso
>>How to update Content Types through the Object Model? #
    When we add a field to the site content type SharePoint doesn"t push-down those changes to the document library and the list level. The below code sample is for push-down all the changes to document
>>SharePoint 2007 Filter webparts - using the Page Field Filter webpart on a Lookup field #
    This post describes an issue we were having using the SharePoint PageFieldFilter webpart in combination with a Lookup field. First the issue is explained, then a solution is provided. The issue In our
>>The solution to saving properties in Custom Field Types! #
    I have finally managed to put Anton"s code to the test in my own custom field type with great results. The underlying issue is that the Update method does not seem to get called when adding a new fiel
>>"Invalid data has been used to update the list item. The field you are trying to update may be read only" - when updating BEGIN - END fields in an event list through Object Model code #
    When updating the "Begin" or the "End" datetime fields in a SharePoint 2003/2007 event list, the error "Invalid data has been used to update the list item. The field you are trying to update may be re
>>Visual Studio Extensions for WSS v3 #
    The RTM version has just been released and you can get it here. Overview This release of the Visual Studio 2005 Extensions for Windows SharePoint Services contains the following tools to aid developer
>>Nifty InfoPath 2007/SharePoint 2007 Feature #
    Every once in a while you bump into a new feature in the 2007 Microsoft Office System and you think "hey! this is really cool!". This happened to me last week when I was playing around with InfoPath 2
>>Telerik"s cross-browser rich text editor for SharePoint 2007 -- public beta now available #
    As previously announced on this blog and as of now officially named r.a.d.editor for SharePoint 2007, this Web-based rich text editor extends the web content authoring environment of Office SharePo
>>Finally - SharePoint Solutions without all the mess! #
    Well, I"m happy to say that I have just about finished my first complex Microsoft Office SharePoint Server (hereafter referred to as MOSS!). It involves custom field types, customised searching, custo
>>MOSS Workflows are versioned #
    I was asked today about MOSS"s behavior when workflows are changed midstream. Say I have a document library with a Workflow attached to it, start a few long-running (non-immediate) workflows, then cha

Related Posts:
>>Microsoft Office SharePoint Server 2007 VHD (i.e. Virtual Machine) now available for download!
>>Announcing three CodePlex projects for community developed SharePoint WCM components
>>Excel 2007 Add-in for Synchronizing Tables with SharePoint Lists - now available!
>>Community Kit for SharePoint 2.0 Pre-Release announcement
>>MOSS Has Got Game - Glu Mobile’s Website (www.glu.com) - How We Did It - Part 1 of 3
>>Prescan.exe Download and Information
>>Fix for the corrupted Virtual Machine on the Microsoft Office SharePoint Server 2007 Technical Resources DVD
>>SharePoint Governance - Key to a Successful Deployment
>>Answers to FAQs about SharePoint Blogs and Wikis
>>Microsoft IT Team Site Life Cycle Management Beta 1.0 for SharePoint Products and Technologies now available on CodePlex
>>Presentations and related resources from SharePoint Conference 2007 APAC now available
>>SharePoint 2007 Customization Policy white paper now available


Month Archives:

Top Tags:
social software social networking .NET mashable Sharepoint ASP.NET Web 2.0 Web2.0 Startups Community News Search Marketplace General Software Development AJAX myspace Visual Studio People Powered! Microsoft YouTube Windows Vista Silverlight Vista MOSS Events C# Featured News Google WPF MOSS 2007 Web Community Security



@2007 All rights Reserved