Set the current date as a default value

Applies to
Microsoft Office InfoPath™ 2003

Although automatically inserting the current date into an InfoPath form requires you to write some script, it will save time for your users (who won’t have to type or remember the date) and reduce mistakes. This article takes you through the process of adding the current date as a default value in your form. If you’ve never used script before, don’t worry — the steps outlined in this article don’t require any previous scripting experience.

Note    Microsoft Office InfoPath 2003 Service Pack 1 includes a number of features that make it easier to design, publish, and fill out forms, including improvements to default values. If you install the service pack, you can set the current date or time as a default value in your forms using a simple procedure that does not require writing script. To learn more about the service pack and how to download it, see Upgrading to Microsoft Office InfoPath 2003 Service Pack 1.

To add the current date automatically, you need to have a date picker in your form. If you haven’t created a date picker, go ahead and do it now.

Create the OnLoad event handler

Because you want the date to appear when the form is first opened, you need to write script that is part of the OnLoad event. Any script in the OnLoad event runs every time the form is opened. To get to the OnLoad event, do the following:

  • In design mode, on the Tools menu, point to Script, and then click On Load Event.

This creates the OnLoad event handler (the name for the script that runs when the form opens — it "handles" the event), opens Microsoft Script Editor (MSE) (Microsoft Script Editor (MSE): A programming environment used to create, edit, and debug Microsoft JScript or Microsoft VBScript code in an InfoPath form.), and positions your pointer in the handler. The section of script that you’re working with should look like this:

//======= 
// The following function handler is created by Microsoft Office InfoPath.
// Do not modify the name of the function, or the name and number of arguments.
//======= 
function XDocument::OnLoad(eventObj) 
{ 
     // Write your code here 
}

 Note   All the script in this article is in Microsoft JScript® syntax.

It is important that you access the OnLoad event as described in the previous procedure. This automatically creates an entry in the form definition file (.xsf) (form definition file: An XML file with an .xsf extension that contains information about all other files and components used within a form, including user interface customizations, XML Schemas, views, business logic, events, and deployment settings.), which is necessary for the event handler to run properly.

Add new script to the OnLoad event handler

After you create the OnLoad event handler, you’re ready to add the new script that will automatically insert the current date into your form. Copy the following text into a text editor, such as Notepad. Select the text in the text editor, and then paste it over the "// Write your code here" text in MSE.

 Note   Pasting the text into a text editor first prevents the Hypertext Markup Language (HTML) (HTML: The standard markup language used for documents on the World Wide Web. HTML uses tags to indicate how Web browsers should display page elements such as text and graphics and how to respond to user actions.) formatting marks from appearing in the script.

     if (!(XDocument.IsNew))
          return;
     if (XDocument.IsSigned) 
          return;
   
     var now = new Date();
     var xmlNode = XDocument.DOM.documentElement.selectSingleNode("my:group1/my:field1");
     if (xmlNode.getAttribute("xsi:nil"))
          xmlNode.removeAttribute("xsi:nil");
       xmlNode.text = getDateString(now);

The resulting function should look like this:

function XDocument::OnLoad(eventObj)
{
     if (!(XDocument.IsNew))
          return;
     if (XDocument.IsSigned) 
          return;
   
     var now = new Date();
     var xmlNode = XDocument.DOM.documentElement.selectSingleNode("my:group1/my:field1");
     if (xmlNode.getAttribute("xsi:nil"))
          xmlNode.removeAttribute("xsi:nil");
       xmlNode.text = getDateString(now);
}
   

This function does the following:

  • Makes sure that the form is new. If the form isn’t new (that is, if the form has already been saved), the function ends. This means that the script will only add a date the first time the form is opened, instead of every time.
  • Makes sure that the form hasn’t been digitally signed. If it has, the fields cannot be updated, so the function ends.
  • Uses the built-in Date command to assign the current date to the variable dateNow.
  • Removes the xsi:nil attribute from the field where you want the date stored. This attribute is attached to blank fields with certain data types to prevent blank values from being marked as invalid. The attribute must be removed before a value can be added to the field. When a user adds values to fields while filling out a form, this attribute is removed automatically. When you are using script, however, you must explicitly remove it.
  • Converts the current date into a date that InfoPath can store by using the getDateString function, which is specified later in this article.
  • Assigns the current date to the field where you want the date stored.

Reference the right field

Now that you have inserted the new script in the previous section, you need to update the following line of script, so that it references the field in your form where you want the current date inserted:

var xmlNode = XDocument.DOM.documentElement.selectSingleNode("my:group1/my:field1");

In particular, you need to update the following XPath with an XPath that points to the correct field:

my:group1/my:field1

In this case, the field is named field1, and is part of the group group1. The namespace abbreviation is my. It is likely that your form’s data source will be more complicated, which means that the resulting XPath (XML Path Language (XPath): A language used to address parts of an XML document. XPath also provides basic facilities for manipulation of strings, numbers, and Booleans.) to your field will also be more complicated. When creating the XPath to your field, you need to identify each of the groups that contain your field and preface all the groups and the field with the namespace abbreviation.

Here's a quick way to get the XPath that references your field:

  1. At the top or bottom of your form, insert an Expression Box from the Controls task pane. The expression box should not be part of a section, repeating section, or repeating table.
  2. In the Insert Expression Box dialog box, click Select XPath Button image.
  3. In the Select a Field or Group dialog box, select the field to which the date picker is bound, and then click OK.
  4. The XPath box in the Insert Expression Box dialog box now contains the XPath that references your field. Copy the XPath, and then click Cancel in the dialog box (so the expression box doesn't become part of your form).
  5. In MSE, select the example XPath in the line of script ("my:group1/my:field1"), and then replace it with the new XPath.

Create the getDateString function

After you change the XPath so that it points to the correct field, you need to create the getDateString function, which is referenced in the script you already inserted. The getDateString function is a few lines of script that convert the current date into a syntax that InfoPath can save correctly.

Because this function runs only when it is referenced (or "called") by another function, you don’t need to associate it with a particular event. That means you can paste the function at the bottom of the script file, after the final bracket in the OnLoad event. Copy and paste the following script into a text editor, such as Notepad. Select the text in the text editor, and then paste it at the bottom of the script file:

function getDateString(oDate)
{
     // Use today as default value.
     if (oDate == null)
          oDate = new Date();

     var m = oDate.getMonth() + 1;
     var d = oDate.getDate();

     if (m < 10)
             m = "0" + m;

   if (d < 10)
      d = "0" + d;

   // ISO 8601 date (YYYY-MM-DD).
   return oDate.getFullYear() + "-" + m + "-" + d;
}

 Note   Because this is a function that does not refer to anything that is particular to your form, it does not need to be customized.

Test your script

After you finish inserting and modifying the script, you should test it to make sure everything works. Quit MSE, and then save your InfoPath form. To test the new function, preview the form. If the current date appears correctly in the date picker, the script is working correctly. If it doesn’t, or if you get an error message, try one of the following:

  • Make sure the date picker doesn’t already have a default associated with it — remember that the function won’t work if the field already contains a value.
  • Make sure that the reference to the field is typed correctly in the script. In particular, if any error messages refer to "object needed" and the script line number where the reference is typed, this is likely to be the problem.
  • Make sure that you pasted the script into a text editor, such as Notepad, before pasting it into the script file in MSE.
  • Make sure that the form isn’t locked in some way that prevents editing (such as a digital signature).

More information on writing script in InfoPath

InfoPath Help contains additional information related to script and other developer tasks, including information about programming InfoPath, a set of developer sample forms, and complete references to the InfoPath object model and form definition (.xsf) file. In addition, MSE Help provides complete references to Microsoft XML Core Services, as well as the Microsoft JScript and Microsoft Visual Basic® Scripting Edition programming languages.