Extending Forms with Script


InfoPath enables developers to extend the functionality of forms using script. There are a variety of areas within InfoPath that are scriptable and that provide programmatic extensions on top of both conditional formatting and the data validation engine. Developers take advantage of script to include custom data validation, error handling, form submission, and accessing external data sources. As a client-based application, InfoPath uses the Microsoft Script Editor (MSE) as the Integrated Development Environment (IDE) for script development. InfoPath and MSE support either VBScript or JavaScript for writing and debugging script components. These components are stored in a single file (either with a .js or .vbs extension) in the InfoPath solution file. The  manifest.xsf file is responsible for providing the entry points that control the firing and execution of a script element.

Note  

Within the solution file, these script files are stored in a file named script.js.

InfoPath provides a variety of areas that are extensible. The most common extension point is the object model. This is the hierarchical type library composed of collections, object, properties, methods , and events that give template developers programmatic control over the various aspects of the InfoPath editing environment and XML source data. Object model changes are often used to control other portions of the form template and provide integration points for solution extensibility. Table 3.3 provides an overview of the common programmatic integration points within InfoPath.

Table 3.3: Common InfoPath areas for adding script.

Name

Description

Data Validation

The combination of XML schema, expressions, and script code that is used to validate and constrain the data that users are allowed to enter within a form template.

Error Handling

The combination of event handlers, object model calls, and XSF entries that are used to generate errors within an InfoPath form template.

Customizable User Components

These include menus , toolbars , command bars, and task panes.

Security

The set of security levels that are used to restrict access to the InfoPath object model and independent system resources.

Data Submission

The set of predefined functions that are used to implement custom posting and submission functionality for an InfoPath form template.

Business Logic

The set of custom scripting files that contain programming code used to implement specific editing behavior, data validation, event handlers, and control of data flow. Many times, this may include accessing external COM components.

Form Template Integration

The use of other Office applications like Microsoft Excel or Outlook to integrate with InfoPath 2003.

Note  

A complete overview of the InfoPath object model is located in Appendix A.

Declarative vs. Programmatic Development

Based on the type of customization, template files are modified using either declarative or programmatic styles. Within the designer, a developer may Extract Form Files into a file folder, manually edit the extracted form files, and then make changes to the elements and attributes using any text editor or Visual Studio.NET. This type of modification is considered declarative. Using the InfoPath designer, a developer can also programmatically add script using MSE. This is usually done in conjunction with the InfoPath object model to extend or enhance the form template behavior. The main difference is that programmatic access is always done within the InfoPath designer or MSE, and declarative modification is completed outside the InfoPath environment and then loaded back into the designer.

The InfoPath Object Model

Using MSE, developers can write script code that is activated in response to events. The InfoPath object model provides a set of events that can occur at both the document and node level. An event is just a script function that runs in response to one of the predefined events. These functions are defined by InfoPath as an association to the event name. Both the event names and definitions are referred to in the form definition file (.xsf) and are not currently extensible. Within the  manifest.xsf , these are maintained as part of the document structure, as shown in Listing 3.6.

Listing 3.6:
start example
 <xsf:domEventHandlers>     <xsf:domEventHandler      handlerObject="msoxd_timesheet_endtime"      match="/timesheet:payinformation/timesheet:weekof/timesheet:worktime     /timesheet:endtime">     </xsf:domEventHandler>     <xsf:domEventHandler handlerObject="msoxd_timesheet_totaldayhours"     match="/timesheet:payinformation/timesheet:weekof/timesheet:worktim     e/timesheet:totaldayhours"></xsf:domEventHandler> </xsf:domEventHandlers> <xsf:scripts language="jscript">   <xsf:script src="script.js"></xsf:script> </xsf:scripts> 
end example
 
Note  

Do not change the names of your functions as this will cause your code to stop working. Function names are hard coded and should never be modified except by InfoPath.

Both the function names and parameters are hard coded within the base InfoPath engine. Once activated, the event functions are given access to the InfoPath object model, which creates an interface to the various nodes and element level data (as shown in the >< xsf:domeventhandler handlerobject XML node in Listing 3.6). Document lifecycle and node level data are two sets of events associated with all documents.

The InfoPath object model is a COM-based object model that is used to interact with InfoPath forms. It is similar to the object models of other Office applications except that it supports a more limited set of automation methods. Table 3.4 shows some of the more important InfoPath objects.

Table 3.4: Key InfoPath objects.

Object

Description

Application

Is the top-level object; provides access to lower-level objects and general-purpose functions.

XDocument

Provides a number of properties, methods, and events that are used to programmatically interact with and manipulate the source XML data of a form.

TaskPane

Provides a number of properties that allow programmatic access to working with the custom and built-in task panes.

DataObject

Provides properties and methods that are used to access and interact with data adapter objects. These include the ability to retrieve information and access the data sources they are connected to.

UI

Provides a number of properties and methods for displaying custom and built-in dialog boxes within the user interface. Based on the security model defined within InfoPath, there are security restrictions on the UI object. (More information about the security restrictions defined within the InfoPath object model is provided in Appendix A.)

Error

Provides properties that are used to programmatically interact with InfoPath-generated form or submission errors.

MailEnvelope

Provides a number of properties that are used to programmatically create custom e-mail messages using Outlook 2003 and attach the current form to the message.

Window

Provides a number of properties and methods that are used to programmatically interact with InfoPath windows . These include the ability to activate or close a window, and interact with task panes and command bar objects. This object also provides properties for accessing the underlying XML document associated with a window.

Solution

Provides properties for getting information about the form template. This includes version information, URL, and an XML DOM containing the manifest information.

View

Provides properties and methods that are used to programmatically interact with InfoPath views. These include methods for switching views, accessing data contained within the view, and executing form synchronization with the underlying data source.

ViewInfo

Exposes properties and methods that are used to get the name of a view and programmatically decide which view is being accessed.

ExternalApplication

Implements a very limited set of methods that are used to automate InfoPath by external COM-based programming languages.

Document Lifecycle

At the document level, there are a series of events that allow for global access and control over the entire document. These events are designed for document-level access and fire in the following order:

  1. OnVersionUpgrade ”This event occurs when the user opens the document and there is a new document version that is not the same as the one installed on the user s client machine.

  2. OnLoad ”This event occurs when the user first opens the document.

  3. OnSwitch ”This event occurs when the user changes views.

  4. OnSubmitRequest ”This event occurs when the user presses the submit command.

  5. OnAfterImport ”This event occurs when the user imports a form.

Node Change Data

At the node level are additional events that fire based on actions within a form. The majority of scripting within InfoPath is done at the node level in response to data changes. The order of events becomes important when you are determining where to place your code. These events fire in the following order:

  1. OnBeforeChange ”This event occurs after the data in a field is modified but before the data in the node bound to the field is changed. This event is typically used to validate information or status before continuing.

  2. OnValidate ”This event occurs after the data in a field is modified and after the data is checked against the schema. This event occurs after successful schema validation and is used to further validate the data and error reporting.

  3. OnAfterChange ”This event occurs after the data in the field is modified, after the data is checked against the schema, and after the data in the node bound to the field is changed. This is the last event and occurs after schema validation is successful, so it is used often to perform updates on the underlying template.

Extending the Timesheet

Within the Timesheet sample, one of the business requirements was to provide a form total based on the hours entered. This is a common task that many InfoPath forms provide and when done helps to cut down on both data-entry errors and time to enter the information.

Calculate Time Worked

To calculate the time worked, first make the Total Hours field read only using the properties page, as shown in Figure 3.18. This prevents users from having to enter data into this field and also will make entry much faster.

click to expand
Figure 3.18: Making a field read only.

The total calculation is implemented in the OnAfterChange event for the End Time field. You can access this field through the data validation property pages, as shown in Figure 3.19. This event provides access to the DOM values entered within the start time and end time, and can then be used to update the Total Day Hours field.


Figure 3.19: Accessing the OnAfterChange event.

Within MSE, add the code shown in Listing 3.7 to the OnAfterChange event for the End Time field. This calls the calculation function that updates the fields.

Listing 3.7: The OnAfterChange event that calls the time calculation function.
start example
 function msoxd_timesheet_endtime::OnAfterChange(eventObj) { // Write code here to restore the global state.   if (eventObj.IsUndoRedo)     {       // An undo or redo operation has occurred and the DOM is //read-only.         return;     } // A field change has occurred and the DOM is writable. Write code here  to respond to the changes.   updatehoursworked(eventObj) } 
end example
 

The eventObj function is a container object that is created by InfoPath and contains all the DOM-level data within the current form. This is passed to the update function, which uses this to calculate the total hours for the day. Once calculated, the TotalHours field is updated with the code shown in Listing 3.8.

Listing 3.8: Calculating the time worked by the employee.
start example
 function updatehoursworked(xmlitem) { var nhours = 0; varstarttime = 0; var endtime = 0; starttime = parseFloat(xmlitem.Site.previousSibling.previousSibling.text); endtime = parseFloat(xmlitem.Site.text); if (starttime==0){return;} if (starttime > endtime){   nhours += (24 - starttime) + endtime; } else{   nhours += endtime - starttime; } xmlitem.Site.nextSibling.nextSibling.text = nhours; } 
end example
 

The eventObj function contains both a Site and Source object. The Site object provides the DOM data based on a tree structure defined around the control that is currently firing the event. This allows for navigation based on the current control within the DOM structure. The Source object provides data from the entire row and isn t full updated until the current row is complete.

Calculate Total Time Entered

The last step in the creation of the Timesheet application is to calculate the total time worked as reported on this form. This is another calculated field that is a chained event fired from the update of the Total Day Hours field on each row of the table. After making the Total Day Hours read only, add the code in Listing 3.9 to the Total Day Hours within the OnAfterChange event. This ensures that the value we add or subtract includes the current field.

Listing 3.9: Calculating the time worked and updating the node fields.
start example
 var totalhours = 0 var xmlnodes =  XDocument.DOM.selectNodes("/timesheet:payinformation/timesheet:weekof/  timesheet:worktime");   for (var xmlnode=xmlnodes.nextNode();xmlnode !=null;xmlnode=xmlnodes.nextNode())   {     var totalworked = xmlnode.selectSingleNode("timesheet:totaldayhours").text;     if (totalworked >= 0) {     totalhours =  parseFloat(totalworked) + parseFloat(totalhours);     }   }   if (totalhours >= 0){   XDocument.DOM.selectSingleNode("/timesheet:payinformation/timesheet:wee kof/timesheet:totalhours").text = totalhours; 
end example
 

One of the major differences between Listings 3.9 and 3.8 is the navigation of the data nodes. Within Listing 3.9, the navigation was done through an aggregation of all the Total Day Hours within the table.

Once the form is completed, you can then deploy it within the enterprise.




Programming Microsoft Infopath. A Developers Guide
Programming Microsoft Infopath: A Developers Guide
ISBN: 1584504536
EAN: 2147483647
Year: 2006
Pages: 111
Authors: Thom Robbins

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net