Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
FormAPI
Developer’s Guide
Release 6.7.1
Service Pack 1
© 2002-2007 Interwoven, Inc. All rights reserved.
No part of this publication (hardcopy or electronic form) may be reproduced or transmitted, in any form
or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior
written consent of Interwoven. Information in this manual is furnished under license by Interwoven, Inc.
and may only be used in accordance with the terms of the license agreement. If this software or
documentation directs you to copy materials, you must first have permission from the copyright owner
of the materials to avoid violating the law which could result in damages or other remedies.
Interwoven, Inc.
160 East Tasman Dr.
San Jose CA 95134
http://www.interwoven.com
Interwoven, Inc. 4
Contents
Interwoven, Inc. 6
About This Book
Intended Audience
This book is written for those who are developing FormsPublisher forms and wish to
use API calls to enhance those forms.
Notation Conventions
This manual uses the following notation conventions:
Directory paths use UNIX conventions. These conventions mandate using forward
slashes (/) in path names. (Windows systems use backward slashes.) The Windows
convention is used when referring to a Windows-specific directory. For example:
UNIX: docroot/news/front.html
Windows: docroot\news\front.html
Manual Organization
This manual is organized as follows:
Chapter 1, “Overview,” describes FormAPI.
Chapter 2, “Using FormAPI,” describes how to set up FormAPI to be used with
FormsPublisher forms.
Chapter 3, “FormAPI Reference,” describes the FormAPI objects.
Appendix A, “Sample User Scripts,” describes the sample user scripts that ship with
FormsPublisher.
Documentation Updates
Additions and corrections to this document (when available) can be downloaded in PDF
format from the following Web site: https://support.interwoven.com.
Interwoven, Inc. 8
Chapter 1
Overview
You enable this functionality by writing a user script that is included (either in-line or
referenced) in the data capture template (DCT). A user script is custom JavaScript code
that uses FormAPI to interact with the data capture form presented by FormsPublisher.
Almost anything that can be done manually by the user entering content into a form may
be scripted (thus the name “user script”) through FormAPI.
At the heart of FormAPI are the event registry and the form item object. The event
registry allows you to associate a user script function to a user event, such as changing
the value of a selection or clicking the Save As button. The FormAPI item object
represents an individual form element, like the Name entry field or the Gender radio
button set. The item object provides methods that let you dynamically query and change
its value and other attributes. A user script author identifies an item by its address,
which is an XPath(1)-like notation that references an item relative to its position in the
DCR.
FormAPI also provides numerous other methods for operating on the form as a whole
and for querying attributes of the DCR.
FormAPI is a JavaScript API. This documentation assumes the user is familiar with
the language syntax, features and limitations. An excellent reference is JavaScript:
The Definitive Reference, 4th ed, by David Flanagan, O'Reilly and Associates, 2004.
The user script does not interact with the browser document object model (DOM)
interface to the HTML form. Instead, FormAPI provides methods to query and set
the values of items in the form.
This lets FormAPI provide a consistent interface to form items that have no DOM
analog (like VisualFormat textareas or items that are not currently on the displayed
page in multipage forms) or to features that the DOM does not support (such as
custom validation expressions for an item).
JavaScript authors familiar with the DOM will find the FormAPI interface very
similar, however.
While user scripts may interact with the user in a number of ways (like JavaScript
dialogs or new browser windows), FormAPI itself presents no visible elements to
the user.
NOTE
User scripts must be valid JavaScript code that use FormsPublisher FormAPI only as
defined in this document. Failure to do so can result in unusable templates.
The next chapter (Chapter 2, “Using FormAPI”) provides details on how to include user
scripts in templates and discusses some of the methods in detail. Chapter 3, “FormAPI
Reference” provides a complete reference to all the methods in FormAPI.
Interwoven, Inc. 10
Chapter 2
Using FormAPI
This chapter provides information on how to set up FormAPI so it can be used in your
data capture templates. It also provides information and examples on other aspects of
FormAPI that will help improve your results.
Code in the <script> tag is loaded by FormsPublisher whenever the user creates a new
data content record (DCR) or edits an existing one. The <script> tag is not read when
the user views a DCR (so user scripts are not executed). This can account for differences
in how the DCR is displayed in the view and edit modes; see “Getting and Setting Item
Values” for more details.
The <script> tag is specified in the current data capture template DTD
(datacapture6.0.dtd) as follows:
<!ELEMENT ruleset (label?, description?, script*, rootcontainer)>
...
<!ELEMENT script (#PCDATA)>
<!ATTLIST script
language CDATA "javascript"
location (webserver|template-type) CDATA "webserver"
src CDATA #IMPLIED
>
As this snippet from the DTD indicates, the <ruleset> element in the DCT now takes
any number of <script> tags. The <script> tag has three attributes: language,
location, and src, and it may also have content.
You can include the user script in the DCT in the <script> tag, as a CDATA
section. This has the advantage that the code is always with the template definition
and changes that affect both parts can be maintained in a single file.
You can keep your code separate from your DCT and point FormsPublisher to your
file using the src and location attributes. This makes it easier to share the file
across templates.
To place the code inline in a CDATA section, place the content within the XML CDATA
markers, <![CDATA[ and ]]>. For example, the following code opens an alert when the
template is first loaded:
<ruleset name="TeamSite Templating">
<itemref name="Address"/>
<script>
<![CDATA[
alert ("Hello, world!");
]]>
</script>
</ruleset>
Alternatively, you could save the script in a file called hello.js and specify its location
using the src attribute. The actual location the src attribute points to may be anywhere
on a webserver, in the same directory as the data capture template type definition, or
somewhere else on the same TeamSite server. The value of the location attribute
controls how the src attribute is interpreted:
webserver
template-type
In this case, src specifies a location relative to the template type directory. So if
hello.js lived alongside the DCT in:
/iwmnt/default/main/WORKAREA/user/templatedata/category/type/hello.js
Multiple <script> tags are allowed, in which case their user scripts are loaded into the
target frame successively.
Typically, a user script consists of a set of functions, usually with one initialization
function. The last line of the user script usually includes a call registering this
initialization function to be called when the onFormInit event occurs that indicates the
form load is complete. This call-back mechanism ensures that certain operations that
might affect form elements are not attempted until the form has been completely
processed (see “Initialization”). In any case, the JavaScript code is simply executed as it
is loaded, as it would in any browser frame.
Interwoven, Inc. 12
Chapter 2: Using FormAPI
Because FormAPI and the user script code loaded by the <script> tag all reside in the
same frame, it is important to adhere to naming conventions to avoid collisions in the
global namespace. Identifiers that start with IW, iw, or _iw are reserved for use by
FormsPublisher.
Initialization
Initialization describes the process by which FormsPublisher creates form objects that
can be manipulated with FormAPI calls. For performance reasons, user script code is
loaded at approximately the same time as the data capture form is initialized. Operations
directly affecting a visual aspect of an item, such as visibility, readonly, and collapse
state, may be sensitive to the timing of form initialization. To ensure that FormAPI
operations (perhaps to make a container invisible) occur after initialization is complete,
FormAPI provides a form event OnFormInit to defer execution of user script code.
Typically this might look like:
function init() {
var containerToHide = IWDatacapture.getItem("/myform/hidden");
if (containerToHide){
containerToHide.setVisible(false);
}
}
IWEventRegistry.addFormHandler("onFormInit", init);
It would be possible to simply call the init function; however, doing so risks that the
form has not completed initialization, and some or all of the items the user script code
will try to modify may not have been completely created. In the example init()
function above, this might result in an apparent failure of the setVisible() operation
(since the setVisible() operation will fail silently). Using the onFormInit event
ensures that the setVisible() operation is not called until the form items are properly
initialized.
Addressing
Addressing is a means of selecting an individual item in the data capture form. It is also
used to register event handlers for an item. The notation of FormAPI item addressing is
similar to the W3C XPath Recommendation (http://www.w3.org/TR/xpath).
NOTE
The similarity to XPath is limited to the simple notation for node names. Other features
of XPath such as wildcard characters, functions, and relative paths are not part of
FormAPI item addresses.
FormAPI addressing provides a single, consistent view of the DCT's item structure
regardless of its source. Hence the address of an item is directly derived from the DCT
that defines it. Each and every item that is directly in the hierarchy of an item in the
DCT needs to be included in the address regardless of whether the item has a pathid or
location attribute. This applies to both Interwoven-style templates as well as custom
DTD templates.
NOTE
Tab names are not required in data records because data records pertain only to saved
data. The location and pathid attributes in the <container> and <item> elements in
datacapture.cfg specify the data record location for the item’s data. The <tab>
element, on the other hand, does not have a location attribute. Therefore it is
non-located and has no representation in the data record.
Addressing Syntax
The notation used for item addresses is similar to basic XPath syntax, which is similar to
the UNIX file system addressing. Consider a simple XML file:
<state>
<city>
<street>This is the street node</street>
</city>
</state>
For this XML snippet, the address for node street is /state/city/street, where
street is a child of city, which is a child of state. If the path starts with a forward
slash /, then it represents an absolute path to the required element from the root element.
Absolute paths are the only notations allowed in FormAPI. Relative paths are not
supported.
Interwoven, Inc. 14
Chapter 2: Using FormAPI
If you consider an XML document to be a tree of nodes, then the address to a particular
node is /parent_node_address + /child_node_name. If a parent node has multiple
children with same name, then the address to the child node contains its position as a
number in square brackets next to its name. This address will look like:
/parent_node_address/child_node_name[position], where position is a positive
integer.
There is an important difference between FormAPI address notation and XPath. The
path consists of name attributes, instead of using the tag names to represent an address.
The .. notation can be used in addresses to access the parent node. The “Addressing
Examples” section contains more details on the usage.
FormAPI addresses only reference a single item. There is no support for wildcard
characters such as *.
To illustrate how item addresses are used, consider the following snippet from a DTD:
<data-capture-requirements name="example">
<ruleset name="example">
......
<conatiner name="a" combination="and" location="a">
<container name="b" combination="and" location="b">
<item name="e" pathid="e">
<text/>
</item>
</container>
<item name="c" pathid="c" max="unbounded" min="0">
<text/>
</item>
</container>
......
</ruleset>
</data-capture-requirements>
To intercept the onItemChange event for the form item that corresponds to node e with a
function called handle_e_changed, the user script would execute:
IWEventRegistry.addItemHandler("/a/b/e", "onItemChange",
handle_e_changed);
Because node c is a replicant, the address of the first instance is /a/c[1], while that of
second instance is /a/c[2], and so on.
To intercept the onItemChange event on all instances of node c item, register a handler
to the address /a/c:
IWEventRegistry.addItemHandler("/a/c", "onItemChange", handle_c_changed);
To register an event for only a specific instance of a replicant, give the path to that
replicant.
Addressing Examples
The address for the item Section would be /Story/Section. The address for the item
Story would be /Story.
Interwoven, Inc. 16
Chapter 2: Using FormAPI
NOTE
“and” replicants and “or” replicants are addressed in the same way.
In this example, the MixedContent item has a mixture of both PCDATA and subelements
(item j).
Note that PCDATA only appears in an address if it is part of a mixed content element.
The following userscript code returns the item object that corresponds to the element e:
item = IWDatacapture.getItem("/b/e");
To get the parent item that corresponds to the element b, use the '..' notation:
parent = IWDatacapture.getItem(item.getName() + "/..");
The items that have options use the index of their selections and not the label or the
value of their options. FormAPI provides four methods to access the options of an item:
getOptions() returns an array of JavaScript Option objects.
addOption() appends an Option to the select list for an item.
Interwoven, Inc. 18
Chapter 2: Using FormAPI
The getOptions(), addOption(), and setOptions() methods all make use of the
standard JavaScript Option object. This object has text and value properties to access
the label and value of the option, respectively. The text of an option is the label the user
sees in the form. The value of an option is the value that is saved in the DCR.
One of the most powerful features of FormAPI is the ability to dynamically change the
available options of an item. For example, suppose the DCT specifies that the city
selection has options for New York, Chicago, and Los Angeles:
<item name="city">
<label>City</label>
<select>
<option value="ny" label="New York"/>
<option value="chi" label="Chicago"/>
<option value="la" label="Los Angeles"/>
</select>
</item>
Here, we used the JavaScript Option object constructor to create the new entry for
Boston. By specifying false to both the selected and defaultSelected arguments, the
new option is added without changing the current selection.
Alternatively, you could replace the entries in the city selection with a new list of cities:
newOptions = new Array();
newOptions[0] = new Option("London", "lon", false, false);
newOptions[1] = new Option("Paris", "par", false, false);
newOptions[2] = new Option("Madrid", "mad", false, false);
IWDatacapture.getItem("/city").setOptions(newOptions);
For example, when the user selects Boston and saves the form, the value bos is entered
into the city element of the resultant DCR, as you had intended.
However, when the user reopens this DCR, the value bos does not match any of the
declared options in the DCT. In this case, FormsPublisher implicitly adds the bos option
to the city selection. However, because it has no way of knowing what the label for this
option is, the label of the new option is set to its value. Thus, when the user reopens this
DCR, the city selection looks like this:
bos
New York
Chicago
Los Angeles
Empty Options
If a single <select> item has no value (and no default value), FormsPublisher renders
the select list with an extra blank option at the top.
Even though this blank entry is physically present in the list to enable the user to make
no selection, it is not returned by the FormAPI option methods. If a single <select> or
<radio> item is unselected, getValue() returns null. Calling setValue(0) selects the
first non-blank option; calling removeOption(0) removes the first non-blank option.
The options array returned by getOptions does not include the blank option.
Interwoven, Inc. 20
Chapter 2: Using FormAPI
Because FormsPublisher uses the empty string to represent the case of no selection,
options should not have empty values. If they do, options with empty values are treated
as if no selection was made.
Multiple <select> items are unaffected by this behavior because they “natively”
support the empty selection when none of their options are selected. If a multiple
<select> has no option selected, getValue() returns an empty array.
Events
To respond to user actions dynamically, the user script needs to be notified that the user
has done something. It does so by listening for a FormAPI event, which is triggered
(generated) as the user interacts with the form. Specifically, FormAPI triggers events
when the user:
Changes the value of an item, for example, by typing text into a text field or
changing the value of a selection (onItemChange). This event is generated for the
specific item.
Tries to close the form (onClose). This event is generated for the entire form.
Clicks the callout button for an item (onCallout). This event is generated for the
specific item.
Adds, moves, deletes, collapses, or expands a replicant. This event is generated for
the specific item.
Previews or generates a form through a presentation template. The event is
generated for the entire form.
Tries to save the form, either by clicking Save or Save As, or by requesting a save
when prompted after clicking Preview or Generate (onSave). This event is
generated for the entire form.
Events are also generated at various stages of the save process (onSaveValid,
onSaveNameSpecified, and onSaveDone).
A user script registers a handler (also known as a callback) to a particular event (or, in
the case of the item-specific events, to an item and an event). A handler is a user script
function that is called when the event triggers. Depending on the event, the handler may
be passed arguments (for example, the onItemChange event handler is passed a copy of
the item object that triggered the event).
FormAPI supports multiple event handlers, allowing the processing of multiple events
from multiple servers in the same form. For example, data from MediaBin and WorkSite
servers can now be used to populate the same data form.
The user script author does not use the browser's events or DOM in any way. The user
script only needs to interact with FormAPI events.
The following sections describe the onItemChange and SaveEvents event handlers in
more detail. See “Event Registry - IWEventRegistry” for the complete list of events.
onItemChange
The most commonly used event is onItemChange. It is triggered:
On a <text> or <textarea> when the user finishes typing and the focus leaves the
item with a different value than it had before.
On a single <select>, <checkbox>, or <radio> item whenever the user makes any
selection.
On a multiple <select> list when the user leaves the item, and the set of selections
is different than it was before.
As in the browser event model, this event usually corresponds to the browser's onChange
event. The exception is multiple <select> items, which call onItemChange only when
the focus leaves the item (the browser's onBlur event) and the set of selections changes.
The handler for an onItemChange event is passed a copy of the item object that triggered
the event. This object also has a special property set, oldValue, that stores the value of
the item (as returned by getValue()) before the user made the change.
For example, if onItemChange for the /name is registered to the nameChanged() function
as above, then nameChanged() could restore the original value of the field if the user
erased it:
function nameChanged(nameItem) {
if (nameItem.getValue() == "") {
nameItem.setValue(nameItem.oldValue);
}
}
NOTE
Because of the performance penalty involved in computing VisualFormat values, the
oldValue property is unavailable on these items.
Interwoven, Inc. 22
Chapter 2: Using FormAPI
Save Events
The save process is more complicated because it involves several steps:
A save may be initiated in several ways. The user might click the Save or Save As
button. The Preview and Generate buttons also give the user the opportunity to save the
DCR before proceeding. All of these conditions trigger an onSave event.
The onSave event handler is passed an integer that indicates what button triggered the
event. In this way, the save handler can determine how the save was triggered and
behave differently if necessary:
function saveHandler(button) {
switch (button) {
case IWDatacapture.SAVE_BUTTON:
case IWDatacapture.SAVEAS_BUTTON:
case IWDatacapture.SAVECLOSE_BUTTON:
// User clicked 'Save', 'Save As' or 'Finish'
...
break;
case IWDatacapture.PREVIEW_BUTTON:
case IWDatacapture.GENERATE_BUTTON:
// User clicked 'Preview' or 'Generate'
...
break;
}
}
NOTE
Code references to SAVECLOSE_BUTTON refer to the Finish button in ContentCenter.
If an onSave event handler is registered, it must return true for the save to proceed. If it
returns false or null, the save is terminated.
If the save proceeds, FormsPublisher validates the form, using the required states and
validation expression set for each item (see “Validation and Highlight Mode”). If
validation fails, the user is alerted and the save is terminated. The form automatically
enters highlight mode, during which all invalid fields are marked with red labels.
If the form is valid, the onSaveValid event is generated, and any registered user script
function is invoked. Here, you can include code that validates the form as a whole (for
example, ensuring that the start date is before the end date):
IWEventRegistry.addFormHandler("onSaveValid", validateForm);
...
function validateForm() {
// Determine if the form is valid.
...
if (formValid) {
return true;
} else {
alert("Form is invalid ...");
return false;
}
}
Note that the onSaveValid event handler is not passed any arguments. As with the
onSave event, the save terminates if the handler returns false.
Interwoven, Inc. 24
Chapter 2: Using FormAPI
If the save proceeds, FormsPublisher next checks to see if it knows the name of the
DCR, or if it needs the user to specify one using the workarea browser. Specifically:
If the user enters the save process by clicking the Save As button, the workarea
browser always displays.
If the DCR currently has no name, either because it is a new DCR or because the
user script reset the current name by calling IWDCRInfo.setDCRName(null), the
workarea browser displays.
If the workarea browser displays and the user clicks Cancel, the save is terminated. If
the user selects a name, FormsPublisher then triggers the onSaveNameSpecified event,
and calls any registered handler. This provides you with a means to validate the user’s
file name selection:
IWEventRegistry.addFormHandler("onSaveNameSpecified", nameChosen);
...
function nameChosen(path) {
// Determine if the path is valid.
...
if (nameOK) {
return true;
} else {
alert("The filename chosen is invalid ...");
return false;
}
}
The onSaveNameSpecified event handler is passed the vpath the user selected. The
event handler can examine this path and decide if it is acceptable, and return true to
continue the save. If the onSaveNameSpecified handler returns false, the save is
terminated.
NOTE
The event handler can also change the name of the DCR by calling
IWDCRInfo.setDCRName(), but because this function is asynchronous, it cannot use the
other methods in IWDCRInfo to check the properties of the file (see “DCR Information -
IWDCRInfo”).
At this point, the system has all the information necessary to save the form, and the data
has passed validation by FormsPublisher and by any custom user script function. When
the save completes, one final event, onSaveDone, is triggered:
IWEventRegistry.addFormHandler("onSaveDone", saveDone);
...
function saveDone(success) {
if (! success) {
alert("The save did not succeed ...");
}
}
The onSaveDone handler is passed a boolean argument indicating whether the save was
successful. The user script can alert the user as needed. Because it is the last step of the
save process, the onSaveDone handler does not have to return a value.
FormAPI also provides the IWDatacapture.save() method, which allows the you to
save the form without any user interaction. This method does not generate the onSave,
onSaveValid, or onSaveNameSpecified events. It also does not validate the form. It
enters the save process near the end, checking only if the DCR name has been specified.
If not (because this is a new DCR or because setDCRName(null) was called),
IWDatacapture.save() does nothing. Otherwise, the form is saved, and the onSaveDone
event is triggered.
NOTE
FormsPublisher provides a <readonly> item type that is distinct from the dynamic
read-only state introduced by FormAPI. The <readonly> type is no longer necessary
and is not supported by FormAPI (see “<readonly> vs setReadonly()”).
Use the setVisible() and the setReadOnly() methods of the IWItem object to change
the state of an item. Use the isVisible() and isReadOnly() methods to query the state
of an item.
Interwoven, Inc. 26
Chapter 2: Using FormAPI
A read-only item is rendered exactly like a normal item, but the user is unable to change
its value (text or selections):
NOTE
FormsPublisher has no mechanism for recalling the visibility or read-only states of an
item when a DCR is reopened. That information exists only in the running user script
and is not written to the DCR. Unless the user script explicitly changes the state of an
item on load, it is visible and editable. For the same reason, view mode (which does not
enable FormAPI or load user scripts) always displays the contents of all the items in the
form, regardless of the visibility state that was set in edit mode.
More typically, you may want to make some fields invisible in response to other
selections. Consider an address entry form that is designed to accept both domestic and
international addresses. If the country field selection is set to USA, fields for state and
ZIP code should appear. For any other country, they should not be visible.
If the country field has the address /address/country, FormAPI can register an event
handler, countryChange(), on it for the onItemChange event. This function adjusts the
visibility of the state and ZIP code fields. FormAPI calls this function directly on start
up, so the initial state of the fields is set correctly.
function init() {
IWEventRegistry.addItemHandler("/address/country",
"onItemChange", countryChange);
countryChange(IWDatacapture.getItem("/address/country"));
}
The countryChange() function is passed the item object for the country field. It checks
if the value of the currently selected country is USA and sets the visibility of the state and
ZIP code fields accordingly. Finally, it forces a redraw to effect the changes:
function countryChange(item) {
var flag = item.getOptions()[item.getValue()].value == "USA";
IWDatacapture.getItem("/address/state").setVisible(flag);
IWDatacapture.getItem("/address/zip").setVisible(flag);
}
Constructions like this allow for the creation of interactive, customized forms that
significantly improve usability.
When the data a user enters fails validation, the attempt to save must be aborted and the
user must be notified which fields are invalid.
Interwoven, Inc. 28
Chapter 2: Using FormAPI
FormsPublisher provides the means to specify validation rules of the first two categories
through the required and validation-regex item attributes in the DCT. For example, you
can specify that a phone number is required and must be entered in a standard format by
declaring the item like this:
<item name="phone">
<label>Phone Number</label>
<description>Enter the phone number (###-###-####)</description>
<text required="t"
validation-regex="^\d{3}-\d{3}-\d{4}$"
maxlength="12"/>
</item>
When FormsPublisher renders this item, it appends an asterisk to its label indicating that
it is required. If the user fails to enter a valid phone number and clicks the Save button,
an alert displays and FormsPublisher enters highlight mode. In this mode, all invalid
entries are marked with red labels, both on the form and in the navigation tree.
FormsPublisher remains in highlight mode until the user corrects the error and
successfully saves the form.
FormAPI enhances these capabilities by providing you with the ability to dynamically
query and change an item’s required state (with isRequired() and setRequired()) and
validation expression (with getRegex() and setRegex()). It also provides the means to
query and change the highlight mode of the form (with IWDatacapture methods
isHighlightMode() and setHighlightMode()).
NOTE
The description of an item, which appears in a frame directly above the form, is not
dynamically accessible by FormAPI. This is important to remember if the description
includes content entry instructions that may not be accurate if the validation expression
changes. In the example above, the description says Enter the phone number
(###-###-####). If the user script calls setRegex(/\d{10}/) to require the phone
number to be entered without dashes, the description is no longer accurate. This
situation is easily avoided by not relying on the description field for content entry
instructions that are variable, and by using alerts and dialogs to inform the user instead.
Highlight mode stays in effect (with all invalid items marked red since the last redraw)
until either the user requests a save and passes validation or the user script calls
IWDatacapture.setHighlightMode(false).
Normally, an item is considered valid if it meets its required state and validation
expression rules that were set by the required and validation-regex attributes in the
DCT or the setRequired() and setRegEx() in the user script. These are the rules that
FormsPublisher employs when performing save validation of the form.
Many times it is important to be able to mark an item valid or invalid without having to
change its required state or validation expression. This kind of validation checking falls
into the third category described at the beginning of the section—ensuring that the field
value makes sense in the context of the entire form. FormAPI provides the setValid()
method to override the other validation rules and directly declare an item valid or
invalid:
setValid(true) marks this item valid, regardless of its content or required/regex
rules. The item always passes save validation and will never be marked red in
highlight mode.
setValid(false) marks this item invalid, regardless of its content or
required/regex rules. The item always fails save validation and will always be
marked red in highlight mode.
setValid(null) turns off any override previously set on this item. Save validation
examines the required/regex rules on this item to determine if it is invalid.
The isValid() method returns the current validation state of the item. If the item was
explicitly marked with setValid(), that state is returned. Otherwise, the required/regex
rules are examined.
Like labels on dynamically inserted options (see “Getting and Setting Item Values”) and
visibility and read-only states (see “Visibility and Read-Only”), the user script must
restore any dynamically modified validation states or rules on load, or a reopened form
will behave differently from when it was last saved.
Examples
To prevent FormsPublisher from flagging the contents of the /b item, regardless of what
was entered, register handlers for the onSave and onSaveDone events:
IWEventRegistry.addFormHandler("onSave", saveHandler);
IWEventRegistry.addFormHandler("onSaveDone", saveFinished);
The event handler overrides the validation state during the save process:
function saveHandler(item) {
IWDatacapture.getItem("/b").setValid(true);
}
function saveFinished(item) {
IWDatacapture.getItem("/b").setValid(null);
}
To ensure that the date in the /start field is before the date in the /end field, register a
handler on the onSaveValid event:
IWEventRegistry.addFormHandler("onSaveValid", validateForm);
Interwoven, Inc. 30
Chapter 2: Using FormAPI
return result;
}
It is important to return false from the validation, so that FormsPublisher aborts the
save request.
Most commonly, the user script needs to run a database query and use the results to set
the value of an item. The canonical example is the address entry form that automatically
populates the city and state fields after the user has entered the ZIP code. There is no
way the user script can include the entire city/state/ZIP database in the code; that
information is best obtained from a server.
FormAPI provides the callServer() method to make an HTTP request with a set of
attributes-value pairs. The request may take the form of either an HTTP POST or an
HTTP GET call. The target server (which can be any process that can handle an HTTP
request and make a response, such as a servlet or CGI) reads the request and returns
JavaScript code embedded in an HTML page. This page is loaded into a hidden frame,
distinct from the frame that contains the user script and FormAPI. FormsPublisher
provides a special parent.getScriptFrame() function to this hidden frame that returns
the user script frame. In this way, the code returned by the server coexists with the user
script and has full access to its methods and data.
NOTE
FormsPublisher also provides the cgi-callout mechanism to access remote resources
from the client form. The FormAPI callServer() method supersedes CGI callouts (see
“CGI Callouts”).
The callServer() method is asynchronous. A new thread is started with the HTTP
request and completes only when it finishes executing the code returned by the server.
The user script code that made the request continues executing immediately after the
call to callServer(). For this reason, callServer() is usually the last line of code in
an event handler; the logic “picks up” in the hidden frame after the post is complete.
The fillCityState() handler is a function that queries a remote server for city and
state:
function fillCityState(zipItem) {
if (zipItem.isValid()) {
var parameters = new Object();
parameters.zip = zipItem.getValue();
// Make an HTTP GET to the server.
callServer("http://myserver/getCityState", parameters, true);
}
}
The result from a call to the server (which will be given the request like
http://myserver/getCityState?zip=94086) returns code similar to this:
<html>
<head>
<script language="javascript">
</script>
Interwoven, Inc. 32
Chapter 2: Using FormAPI
</head>
<body>
</body>
</html>
One of the hazards of making a remote server request is that it may take too long to
return. Worse, it may not return at all. To guard against this problem, a user script can
use the JavaScript setTimeOut() function to handle a request that does not return within
a specified amount of time. Before it calls the server, setTimeOut() is instructed to
execute an error handler function. The code that returns from the server cancels the
pending error handler call (if it is running, the request succeeded). If the server does not
return in time, the error handler is executed.
Adjust the user script fillCityState() function to set up the time out:
...
// Error handler called in 1 minute. Save ID in global variable
// for hidden frame to cancel if it succeeds.
timeout = setTimeOut("callServerFailed", 60000);
Finally, modify the JavaScript returned from the server to cancel the time out:
...
// Get handle to the FormAPI/userscript frame.
api = parent.getScriptFrame();
This does not handle the case where the server is not down, but simply slow. In this
case, after one minute the user is prompted that the ZIP code lookup failed, but several
moments later may suddenly see the city and state fields automatically change. To guard
against this possibility, modify the callServerFailed() function to cancel the server
call:
function callServerFailed() {
alert("ZIP code lookup failed. Be sure to enter city and state.");
This request cancels the previous request by making a new one to an empty file. This
illustrates an important point about the callServer() method: only one call can be
active at a time. Subsequent calls to callServer() will cancel any previous calls.
Auto-DCR Functionality
The Auto-DCR function enables unnamed DCRs to be saved with automatically
generated names. When this feature is used, the user does not need to provide a name for
the DCR that is being saved.
Auto-DCR naming:
Is applicable when saving a DCR using the Save or Finish buttons, but not when
saving with the Save As button (because this signifies intent to specify a name for
the DCR file).
Can be configured for a specific category and type.
Is turned off by default.
The Auto-DCR function uses an algorithm based on timestamps that returns unique file
names in the form iwDCRnumber_timestamp. This function may be replaced by a
user-written function that is used to automatically get the names of the saved DCR files.
See “Name Factory - IWNameFactory” on page 67 for more information.
NOTE
All DCR file names generated by Auto-DCR naming are relative to the data directory
of the specified category and type.
Conversely, invisibility is a state of an item. An invisible item is any item that has been
made invisible by using the FormAPI method IWItem.setVisible(false). Unless
Interwoven, Inc. 34
Chapter 2: Using FormAPI
setVisible(false) is called when the user script is first loaded, the item will be visible
when the user opens the form. Note that items that are not on the current page or that are
scrolled out of view are considered visible, even though the user cannot see them.
Hidden items and invisible text items appear to have similar behavior. Use hidden items
in templates to store a value that the user must never change or see, like internal ID
numbers. Use invisible items for fields that are only applicable under certain conditions.
NOTE
Because there is no FormAPI in view mode, all items, whether hidden or previously
invisible, are visible in view mode.
<readonly> vs setReadonly()
Before FormAPI was available, the only way to show uneditable content was to use the
<readonly> item instance. Data in a <readonly> item had to be text because
<readonly> items do not allow selections or options, and it was rendered as a simple
text string in the form.
The template designer can easily change the read-only item back to its editable state by
calling setReadOnly(false).
CGI Callouts
Before FormAPI was available, the only way to dynamically change the form was to use
a CGI callout, defined in the DCT using the <callout> element. An item with a CGI
callout is rendered with a button beside it. Clicking the button opens a new window that
the template designer can use to present the user with a dialog. The content of the new
window is specified in the url attribute of the <callout> element. This new window
then updates the data capture form.
NOTE
Before FormAPI was available, the url attribute of the <callout> subelement was
required. It is now optional.
With FormAPI, much of the need for the CGI callout is eliminated.The template
designer can achieve the same functionality more easily and with much greater
flexibility in a user script. A user script can open a new window by calling the browser’s
open() command, dynamically specifying any URL it needs. This new window can
access the user script code and FormAPI methods of its parent window by calling
opener().
There, are, however, two reasons why the <callout> element is still important to
FormAPI:
1. You may already have callouts that you need to reuse with templates that have user
scripts.
2. The <callout> element renders a button beside a form element. This is the only
way to get a simple button on the form that does not directly change the value of the
data (unlike a check box or radio button).
If the onCallout event is registered and a url attribute is specified to the <callout>
element in the DCT, then the event handler is called first. If it returns true, the callout
specified in the url is called by opening a new window. If the event handler returns
false, the callout window is not opened.
In this way, FormAPI fully supports callouts, allowing them to be executed or not as
determined by the user script at runtime.
Note again that a <callout> element in the DCT is the only way to get a simple button
on the form. To have the button appear rendered by itself (and not beside any particular
input element) set the callout on a hidden item. For example, the DCT may look like
this:
<item name="myButton">
<hidden>
<callout label="My Button"/>
</hidden>
</item>
If the buttons do not need to be on the same window as the template, user script code
can also write HTML to a new browser window to create a custom dialog with buttons,
links, and images.
Interwoven, Inc. 36
Chapter 3
FormAPI Reference
This chapter provides details about the various FormAPI objects. Before using these
objects, you should be aware of the following information.
There are eight different objects exposed in this API. These objects are:
API (page 38)
Data Capture Form (page 39)
Item (page 47)
Event Registry (page 58)
DCR Information (page 63)
Name Factory (page 67)
Page Generation (page 68)
Presentation Template (page 70)
Five of these objects, API, Datacapture, Event Registry, DCR Information and Name
Factory, are singletons—users access their methods from a single instance of the object
bearing the name of the class. Methods of the item object IWItem are accessed from a
particular instance of the item.
NOTES
All paths are relative to the data directory of the template.
For all methods that require a path, the path delimiter should be / (forward slash).
string IWAPI.getTSTVersion ()
Arguments:
None.
Returns:
A string representing the version of FormsPublisher.
string IWAPI.getVersion ()
Arguments:
None.
Returns:
A string representing the version of the API.
Interwoven, Inc. 38
Chapter 3: FormAPI Reference
It also defines constants that represent the buttons on the form. These may be used by
user script functions that register handlers to the onSave event (see “DCT Items -
IWItem”).
Calls url with data using an HTTP POST or HTTP GET, as specified by isGet. The target
of the submit operation is a hidden frame. The response from the post should be
JavaScript that manipulates the form or creates and populates data structures.
The hidden frame where the response is rendered should not be considered a safe place
to hold data; data that spans multiple submit operations (including save) should be
relocated to the script frame:
var scriptFrame = parent.getScriptFrame();
scriptFrame.myData = "from the server";
Arguments:
url
Boolean indicating whether the data should be sent using an HTTP GET (true)
or an HTTP POST (false).
Returns:
Nothing.
IWDatacapture.close (confirmClose)
Closes the current window. Does not trigger the onClose event.
Arguments:
confirmClose
Boolean indicating if close() should behave like clicking the Close button, and
prompt the user to save or regenerate (if necessary) before closing.
Returns:
Nothing.
IWDatacapture.displayMessage (message)
Arguments:
message
A string message. If null or omitted, the information frame displays the default
information.
Returns:
Nothing.
Enables (or disables) display of thumbnail preview images for browse items whose
extension includes one of .gif, .jpg, .jpeg, .avi, .emf, .mov, .mpg, .png, .wmf, .xbm, or
.bmp.
This should be invoked immediately and not deferred until the onFormInit event.
Arguments:
enable
Returns:
Nothing.
Interwoven, Inc. 40
Chapter 3: FormAPI Reference
number IWDatacapture.getCurrentPageNumber ()
Arguments:
None.
Returns:
A number representing the page number of the current page. Page numbers start at
1.
string IWDatacapture.getDCRPath ()
Returns the vpath of the data content record. If no vpath was set, the empty string ("") is
returned.
Arguments:
None.
Returns:
The vpath of the data content record.
string IWDatacapture.getDCTPath ()
Arguments:
None.
Returns:
The vpath to the datacapture template.
string IWDatacapture.getFormType ()
Arguments:
None.
Returns:
The form type.
string IWDatacapture.getGroups ()
Returns the group(s) that the currently logged-in user is a member of.
Arguments:
None.
Returns:
An array of the names of the current user’s groups.
Arguments:
name
NOTE
If a data capture template uses tabs (through the <tab> element in
datacapture.cfg) you must include the tab’s name in the item address/xpath. See
“Addressing and Form Tabs” on page 14 for more information.
Returns:
An IWItem object that represents the replicant instance container and supports the
setVisible and isVisible operations. Returns null if the item cannot be found.
number IWDatacapture.getPageCount ()
Arguments:
None.
Returns:
A number representing the number of pages in this form.
string IWDatacapture.getRole ()
Interwoven, Inc. 42
Chapter 3: FormAPI Reference
string IWDatacapture.getRoles ()
Returns the role(s) that the currently logged-in user of this form has in the current
workarea.
Arguments:
None.
Returns:
An array of the current user’s role names.
IWItem[] IWDatacapture.getRootItems ()
Returns an array of IWItem objects representing all the items at the top level of the entire
form. Custom DTD templates always return an array of exactly one element because
there may be only one top-level node. Use getChildren() for the individual item to
iterate into a replicant or container.
Arguments:
None.
Returns:
An array of IWItem objects representing the items at the top level of the entire form.
This function is defined at the top level of a data capture form. If this is being called
from JavaScript returned by callServer(), you will probably need to invoke it from the
parent object.
Returns the frame containing the API and user scripts. It is designed to be used in the
JavaScript returned by the callServer() method to access functions and variables in
the user script frame.
Be careful when using the returned object, as it is possible to completely delete the
contents of this frame and the user scripts in it.
Arguments:
None.
Returns:
The JavaScript frame object where the API and user script reside.
string IWDatacapture.getUser ()
Arguments:
None.
Returns:
A string representing the currently logged in user of this form. On a Windows
server, the returned name is in the form domain\user.
string IWDatacapture.getWorkarea ()
Arguments:
None.
Returns:
The current workarea.
IWDatacapture.gotoPage (pagenumber)
Arguments:
pagenumber
Returns:
Nothing.
Interwoven, Inc. 44
Chapter 3: FormAPI Reference
boolean IWDatacapture.isHighlightMode ()
Determines whether the form is in highlight mode. In highlight mode, items that are
invalid as determined by isValid() have their labels highlighted in red.
A form may be in highlight mode because either 1) it entered it automatically after the
form failed save validation, or 2) an explicit call to setHighlightMode(true) was
made.
Arguments:
None.
Returns:
True if the form is in highlight mode, false if not.
boolean IWDatacapture.isModified ()
Arguments:
None.
Returns:
True if the DCR has been modified (that is, should be saved), false if not.
IWDatacapture.save ()
Saves the current DCR if there is a name to save it to. Does not trigger onSave,
onSaveValid, or onSaveNameSpecified events. Does invoke onSaveDone event.
Arguments:
None.
Returns:
Nothing.
IWDatacapture.setHighlightMode (highlightMode)
Sets the current highlight mode. In highlight mode, items that are invalid (as determined
by isValid()) have their labels highlighted in red.
Arguments:
highlightMode
Returns:
Nothing.
IWDatacapture.setIsModified ()
Saves a DCR even if the form has not been modified. This feature is useful if the form
contains acceptable defaults and the DCR name is automatically determined by
FormAPI. In this situation, the user clicks Finish or Next without making any changes
to the form.
Arguments:
None.
Returns:
Nothing.
Interwoven, Inc. 46
Chapter 3: FormAPI Reference
Unlike the other objects in FormAPI, IWItem is not a singleton; each element has its
own IWItem instance. Where the following documentation refers to “this item,” it means
the IWItem instance in the current context.
Inserts a new replicant instance at index, with choice_name as an optional argument for
“or” containers. Applies only to replicant containers.
Arguments:
index
A whole number of your choice for the index of the new instance. The index is
not zero-based. If index is passed as 0 or less, it is treated as if index=1. If
index is greater than the number of instances, it is appended to the end.
choice_name
Returns:
IWItem of the instance added, or null if unable to complete the operation.
IWItem.addOption (option)
Adds an entry to the list of options for this item. This method applies only to <select>,
<checkbox>, and <radio> items.
Arguments:
option
Returns:
Nothing.
Arguments:
index
The whole-number index of the instance to delete. The index is not zero-based.
It is ignored if index is passed as 0 or is greater than the number of current
instances.
Returns:
False if unable to complete the operation, or if the index argument is out of bounds.
Arguments:
name
Returns:
The first immediate child of the item whose name matches the name argument.
IWItem[] IWItem.getChildren ()
Arguments:
None.
Returns:
An array of IWItem objects representing the children of this item or null if it does
not have children.
Interwoven, Inc. 48
Chapter 3: FormAPI Reference
string IWItem.getDescription ()
Arguments:
None.
Returns:
The string representing the description of this item.
string IWItem.getLabel ()
Arguments:
None.
Returns:
The the string representing the label for this item.
string IWItem.getName ()
Arguments:
None.
Returns:
The XPath-like address of this item.
Option[] IWItem.getOptions ()
Returns the options for this item. This method applies only to <select>, <checkbox>,
and <radio> items.
Arguments:
None.
Returns:
An array of JavaScript Option objects representing the list of options in this select,
checkbox, or radio item, in order. Returns null if this item has no options.
RegExp IWItem.getRegex ()
Arguments:
None.
Returns:
A JavaScript RegExp object representing the validation expression for this item, or
null if there is none.
string IWItem.getType ()
Arguments:
None.
Returns:
A string representing this item’s type. Possible values are:
textarea
text
radio
checkbox
select
hidden
browser
andreplicant
orreplicant
andcontainer
orcontainer
andreplicantcontainer
orreplicantcontainer
The string unknown is returned for unsupported item types (such as the <readonly>
item type).
Interwoven, Inc. 50
Chapter 3: FormAPI Reference
Returns the value of this item. For <text> items, including <browser> and <hidden>
items, a string value is returned. For items with options, a number representing the index
(or an array indicating the indices, if this item supports multiple selections) is returned.
For all other items, including <replicants> and <containers>, this method returns
null.
Arguments:
None.
Returns:
String value for <text>, <textarea>, <browser>, or <hidden> items.
Number of selected index (zero-based) for single <select> and <radio> items.
Array of numbers of selected indices (zero-based) for multiple <select> and
<checkbox> items.
boolean IWItem.isCollapsed ()
Arguments:
None.
Returns:
True if this item is collapsed, false if the item is expanded.
boolean IWItem.isMultiSelect ()
Arguments:
None.
Returns:
True if this item is a multiple <select> or <checkbox>, false if not.
boolean IWItem.isReadOnly ()
Returns the value of the read-only flag for this item. This method is not related to the
<readonly> item type, which FormAPI does not support.
Arguments:
None.
Returns:
True if the read-only flag of this item is set, false otherwise.
boolean IWItem.isRequired ()
Arguments:
None.
Returns:
True if this item is a required item, false if not.
boolean IWItem.isValid ()
Arguments:
None.
Returns:
True if this item is valid, false if not. If setValid() has been called with true or
false, that value is returned. If setValid() has not been called or was called with
null, the system determines validity by checking the requirement status and regular
expression validation rule for this item.
boolean IWItem.isVisible ()
Arguments:
None.
Returns:
True if this item has a true visibility state, false if it is invisible. Note that an item
can have a true visibility state and still not be seen on the screen. For example, it
may be on a different page or scrolled out of view.
Interwoven, Inc. 52
Chapter 3: FormAPI Reference
boolean IWItem.isVisualFormat ()
Arguments:
None.
Returns:
True if this item is a VisualFormat control, false if not.
Moves an instance from one index to another. No action is taken if the indexes evaluate
to equivalent values. Applies only to replicant containers.
Arguments:
from_index
A whole number of your choice for the index of the instance. The index is not
zero-based. If index is passed as less than 1, it is interpreted as 1. If the index is
greater than the number of current instances, the item at from_index is moved to
the last position.
Returns:
False if unable to complete the operation.
IWItem.removeOption (index)
Removes an option from the list of options for this item. This method applies only to
<select>, <checkbox>, and <radio> items.
Arguments:
index
Returns:
Nothing.
IWItem.setCollapsed (boolean)
Arguments:
None.
Returns:
Nothing.
IWItem.setDescription (text)
Arguments:
text
Returns:
Nothing.
IWItem.setFocus ()
Sets the focus to this item. If this item is not on the current page, the form is first
redrawn at the correct page. setFocus() has no effect if this item is currently read-only.
Arguments:
None.
Returns:
Nothing.
IWItem.setLabel (text)
Arguments:
text
Returns:
Nothing.
Interwoven, Inc. 54
Chapter 3: FormAPI Reference
IWItem.setOptions (options)
Sets the option list for this item. This method applies only to <select>, <checkbox>,
and <radio> items.
Arguments:
options
An array of JavaScript Option objects to set as the new list of options for this
item. An invalid or missing argument does nothing.
Returns:
Nothing.
Sets the read-only property of this item. Depending on the value of recursive, it either
sets the readOnly attribute or recursively sets the readOnly property on all descendent
items. A read-only replicant container has all replicant buttons disabled, on both the
container and the instances themselves. This method is not related to the <readonly>
item type, which is unrelated to FormAPI.
Arguments:
readonly
Returns:
Nothing.
IWItem.setRegex (regex)
Sets the regular expression for validation of this item. This method is only valid for
<text>, <textarea>, <hidden>, and <browser> items.
Arguments:
regex
Returns:
Nothing.
IWItem.setRequired (required)
Sets whether this item should be required (empty value fails validation). Required items
are marked with an asterisk (*) in their label.
Arguments:
required
Returns:
Nothing.
IWItem.setValid (value)
Specifies whether the value in this item is valid. A true argument overrides results of
standard validity tests.
Arguments:
value
• null: Do not mark this item. The isValid() method determines validity by
checking the required status and validation regular expression.
Returns:
Nothing.
Interwoven, Inc. 56
Chapter 3: FormAPI Reference
IWItem.setValue (value)
Arguments:
value
Returns:
Nothing.
IWItem.setVisible (visible)
Arguments:
visible
Returns:
Nothing.
string IWItem.toString ()
Arguments:
None.
Returns:
A descriptive string showing the type and name properties.
A handler registered to a replicant is called whenever the specified event occurs on any
instance of that replicant.
FormAPI supports multiple event handlers, allowing the processing of multiple events
from multiple servers in the same form. For example, data from MediaBin and WorkSite
servers can now be used to populate the same data form.
Interwoven, Inc. 58
Chapter 3: FormAPI Reference
Interwoven, Inc. 60
Chapter 3: FormAPI Reference
Specifies an event handler for a form event, replacing any previously registered function
(for this event.
Arguments:
eventname
A string representing the name of the event this handler will intercept (see
preceding table).
func
Returns:
Nothing.
Specifies a event handler for an event on a particular item, replacing any previously
registered function for this event on this item. Accepts special path expressions
registering default item handlers that are children of replicants. These expressions look
very similar to the XPath-like expressions passed to IWDatacapture.getItem(), except
that they contain no index expressions such as [1]. They are useful for registering event
handlers that will be invoked by default for all indexes of a replicant.
For example, suppose that each phone replicant has a child text field named cell. One
can register an item handler on all the cell fields for all instances of phone with an
expression such as /contact/phone/cell. More specific calls for specific instances can
be made, for example /contact/phone[1]/cell. Any calls to
IWEventRegistry.addItemHandler() with a more specific path expression will
override the default.
Arguments:
itemname
A string representing the name of the event this handler will intercept (see
preceding table).
func
Returns:
Nothing.
IWEventRegistry.removeFormHandler (eventname)
Removes the event handler for the given event from the form.
Arguments:
eventname
Returns:
Nothing.
Removes the event handler for the given event from the given item.
Arguments:
itemname
Returns:
Nothing.
Interwoven, Inc. 62
Chapter 3: FormAPI Reference
NOTE
All of the query methods in this object rely on the most recent setDCRName() to have
populated the information field when the DCR was most recently named. setDCRName()
is implicitly called when:
The form is first loaded.
The form is saved either by the user or by calling IWDatacapture.save().
string IWDCRInfo.getDCRName ()
Arguments:
None.
Returns:
The current name of the DCR, or null if the DCR is currently unnamed.
number IWDCRInfo.getFileSize ()
Arguments:
None.
Returns:
A number representing the size of the file in bytes. Returns null if the DCR is
currently unnamed.
Date IWDCRInfo.getModificationDate ()
Arguments:
None
Returns:
A JavaScript Date object which contains the last modified date of the DCR file.
Returns null if the DCR is currently unnamed.
string IWDCRInfo.getOwner ()
Determines the owner of the file. In the TeamSite file system, the owner of the file is the
last user to have modified the file.
Arguments:
None.
Returns:
A string representing the owner of the file. Returns null if the DCR is currently
unnamed.
number IWDCRInfo.getStatus ()
Determines whether meta information is available. Should be checked before calling the
other methods in this object.
Arguments:
None
Returns:
IWDCRInfo.AVAILABLE: information is available; use the other methods in this
object to obtain it.
IWDCRInfo.UNAVAILABLE: there is no information available for the current DCR
name (probably because the file does not exist).
IWDCRInfo.PENDING: the request to the server to retrieve information for the
current DCR name has not completed yet.
IWDCRInfo.ERROR: the request to the server to retrieve information for the
current DCR name did not return in time (1 minute) and has been cancelled.
Interwoven, Inc. 64
Chapter 3: FormAPI Reference
NOTE
When checking for the status of IWDCRInfo object, do not use a tight infinite loop.
Instead, use the setTimeOut() method in Java to poll for the status change. For
example:
function checkInfoStatus()
{
if (IWDCRInfo.getStatus == IWDCRInfo.PENDING)
{
//Check again in 2 sec
setTimeout("checkInfoStatus()",2000);
}
else
{
//Do what you were about to do with the status.
}
}
boolean IWDCRInfo.isModifiedInWA ()
Determines whether the DCR file is marked as modified in the TeamSite workarea
(different from staging).
Arguments:
None.
Returns:
True if the DCR file is marked as modified in the TeamSite workarea, false if it is
not. Returns null if the DCR is currently unnamed.
Sets the name of the DCR to the given path and initiates a server request for information
about that file. The path is relative to the current template’s data directory.
NOTE
Do not specify a path with references to the parent directory (..). Doing so can lead to
unpredictable results.
While the request is in progress, its status may be tracked with the getStatus() method,
as described above.
Because it involves an HTTP POST, this is an asynchronous call that spawns a new
thread. To synchronize execution with the completion of this method, specify a callback
function. The callback executes when the request completes or times out (1 minute).
If a request is still pending and setDCRName() is called again, the original request is
cancelled and the new one is initiated.
If path is null, the DCR name is explicitly unset. The callback is not executed if the
path is null. The system prompts the user for a DCR name when the Save button is
clicked.
setDCRName() is implicitly called when the form is opened, and when the form is saved.
Therefore, calls to IWDatacapture.save() followed immediately by a call to
setDCRName() are not safe because when the save completes, the new name will be lost.
Arguments:
path
A function to execute when the implicit request to refresh the DCR information
returns or times out.
Returns:
Nothing.
Interwoven, Inc. 66
Chapter 3: FormAPI Reference
NOTE
The file paths that the function generator returns must be relative to the data directory
of the relevant data capture form. A default function is provided that uses a simple
algorithm based on timestamps to ensure unique file names.
Sets the automatic DCR path generator function to be equal to the functionname
argument. This user-written automatic DCR path generator function needs to return a
name relative to the “data” directory of the relevant category and type to which this
DCR belongs.
Arguments:
function
The function will automatically return the name of the file that should be used to save
the current DCR.
function IWNameFactory.getAutoDCRPathGenerator ()
Returns:
The user-set automatic DCR path generator function. If a user has not previously set
the automatic DCR path generator function, then null will be returned.
IWPresentationTemplate IWPageGeneration.getPresentationTemplate()
Arguments:
None.
Returns:
An IWPresentationTemplate object of the current presentation template. Null is
returned if there is no current presentation template.
IWPresentationTemplate
IWPageGeneration.getValidPresentationTemplates ()
Gets an array of valid presentation templates for this data content record.
Arguments:
None.
Returns:
An array of presentation templates.
string IWPageGeneration.getOutputFile ()
Gets the output file name to be used for previewing and generating.
Arguments:
None.
Returns:
The string path representing the templatedata relative path of the file. The empty
string ("") is returned if the output file has not been set.
Interwoven, Inc. 68
Chapter 3: FormAPI Reference
Sets the output file name to be used for previewing and generating. This modifies the
corresponding form settings option.
Arguments:
filename
The string path representing the templatedata relative path of the file.
create_directories
Creates the directory paths for filename if they do not exist (optional).
Returns:
Nothing.
Sets the presentation template to be used for previewing and generating. This modifies
the corresponding form settings option.
Arguments:
template
Returns:
False if the presentation template is invalid.
string IWPresentationTemplate.getExtension ()
Arguments:
None.
Returns:
The extension attribute of the presentation template as defined in the
templating.cfg file.
string IWPresentationTemplate.getName ()
Arguments:
None.
Returns:
The name of the presentation template as defined in the templating.cfg file.
string IWPresentationTemplate.getPath ()
Gets the workarea-relative path to the presentation template. To get the full vpath to the
presentation template, concatenate this result to IWDatacapture.getWorkarea ().
Arguments:
None.
Returns:
The workarea-relative path of the presentation template.
Interwoven, Inc. 70
Appendix A
The following sections contain descriptions of the sample user scripts that are
packaged with FormAPI.
The Script
The following is contact.js, the user script for this example.
// File contact.js
// Userscript for the 'userscript/contact' Templating FormAPI example.
//
//-----------------------------------------------------------------------
function init() {
// Register a function to popup a confirmation window on save
// *after* the form has passed basic validation.
IWEventRegistry.addFormHandler("onSaveValid", displayContact);
IWEventRegistry.addItemHandler("/contact/phone", "onItemChange",
checkPhoneNumbers);
}
// This function is called when the user tries to save the form. It
// displays the contact details and request confirmation.
function displayContact() {
var i = 1;
var phoneItem;
while (phoneItem = IWDatacapture.getItem("/contact/phone[" + i + "]"))
{
message += "\nPhone(" + i++ + "): " + phoneItem.getValue();
}
return confirm(message);
}
function checkPhoneNumbers(phoneItem) {
if (! phoneItem.isValid()) {
Interwoven, Inc. 72
Appendix A: Sample User Scripts
var i = phoneItem.getName().match(/\d+/)[0];
The DCT
The following is datacapture.cfg, the data capture template that invokes contact.js.
Installation
The Location user script requires the following installation steps:
1. Copy the getLocations.cgi to iw-home/httpd/iw-bin.
2. Edit the first line of getLocations.ipl to point to the path for the iwperl interpreter
and replace '__IW_HOME__' with the location of iw-home.
3. Change the dtd-system-identifier attribute in the datacapture.cfg file to point
to the correct location of location.dtd.
Interwoven, Inc. 74
Appendix A: Sample User Scripts
The Script
The following is the user script for this example.
<script>
<![CDATA[
function init() {
// Register a function to validate data before for gets submitted.
IWEventRegistry.addItemHandler("/location/region", "onItemChange",
fetchLocations);
// Set the City list for the selected region(if any)
var regionItem = IWDatacapture.getItem("/location/region");
var cityItem = IWDatacapture.getItem("/location/city");
var myOptions = cityItem.getOptions();
fetchLocations(regionItem,
cityItem.getOptions()[parseInt(cityItem.getValue())].value);
}
function populateLocations(locations) {
//Clear the message display...
IWDatacapture.displayMessage();
var locationsItem = IWDatacapture.getItem("/location/city");
locationsItem.setOptions(locations);
}
The DCT
The following is datacapture.cfg, the data capture template that invokes the above
script.
NOTE
For this example the script is contained in the datacapture.cfg file.
Interwoven, Inc. 76
Appendix A: Sample User Scripts
The Script
The following is organization.js the user script for this example.
function init() {
IWEventRegistry.addFormHandler("onSave", saveHandler);
IWEventRegistry.addItemHandler("/organization/department",
"onItemChange", departmentHandler);
departmentHandler(IWDatacapture.getItem("/organization/department"));
}
function departmentHandler(item) {
IWDCRInfo.setDCRName(department, null);
}
}
// This function is called when user saves the form. It sets the DCR
// name, if not set already. It also ensures that someone else's
// changes are not being inadvertently overwritten (which can happen
// in shared workareas).
function saveHandler() {
var result;
switch (IWDCRInfo.getStatus()) {
case IWDCRInfo.AVAILABLE:
Interwoven, Inc. 78
Appendix A: Sample User Scripts
if (IWDCRInfo.isModifiedInWA() &&
IWDCRInfo.getOwner() != IWDatacapture.getUser()) {
} else {
result = true;
}
break;
case IWDCRInfo.PENDING:
result = confirm(message);
break;
case IWDCRInfo.UNAVAILABLE:
default:
result = true;
}
return result;
}
IWEventRegistry.addFormHandler("onFormInit", init);
The DCT
The following is datacapture.cfg, the data capture template that invokes
organization.js.
Interwoven, Inc. 80
Appendix A: Sample User Scripts
The Script
The following is position.js the script for this example.
// File position.js
// Userscript for the 'userscript/position' Templating FormAPI example.
//
//-----------------------------------------------------------------------
------
IWEventRegistry.addItemHandler("/position/type",
"onItemChange", typeHandler);
IWEventRegistry.addItemHandler("/position/title",
"onItemChange", titleHandler);
IWEventRegistry.addFormHandler("onSaveValid", validateForm);
typeHandler(IWDatacapture.getItem("/position/type"));
titleHandler(IWDatacapture.getItem("/position/title"));
}
function typeHandler(typeItem) {
// Turn off highlight mode. If the user entered invalid data, and
// then attempted to save, highlight mode is automatically turned
// on. If at this point they decide to change the position type,
// we shut off highlight mode so fields that were previously
// hidden don't appear to be the cause of the validation failure.
IWDatacapture.setHighlightMode(false);
Interwoven, Inc. 82
Appendix A: Sample User Scripts
if (! status) {
item.setValue("");
}
}
function titleHandler(titleItem) {
yearlyItem.setRegex(/^[1-9]\d{6,9}$/);
var message = "Yearly compensation for executives must be at
least $1,000,000.";
} else {
yearlyItem.setRegex(/^[1-9]\d{2,4}$/);
var message = "Yearly compensation range is $100-$99,999.";
}
IWDatacapture.displayMessage(message);
setTimeout("IWDatacapture.displayMessage()", 5000);
}
}
function validateForm() {
return false;
}
}
if (isPositionTemporary(typeItem)) {
var rate = IWDatacapture.getItem("/position/rate").getValue();
message += "\nHourly rate: " + rate;
var hours = IWDatacapture.getItem("/position/hours").getValue();
message += "\nWeekly hours: " + hours;
} else {
Interwoven, Inc. 84
Appendix A: Sample User Scripts
return confirm(message);
}
IWEventRegistry.addFormHandler("onFormInit", init);
The DCT
The following is datacapture.cfg, the data capture template that invokes
position.js.
</item>
<item max="1" min="1" name="rate" pathid="rate">
<label>Hourly Rate</label>
<description>Hourly rate (required for temporary positions only)
</description>
<text maxlength="4" validation-regex="^\d+$" />
</item>
<item max="1" min="1" name="hours" pathid="hours">
<label>Hours Per Week</label>
<description>Number of hours per week(required for temporary
positions only)</description>
<text maxlength="2" validation-regex="^[0-9]+$"></text>
</item>
<item max="1" min="1" name="yearly" pathid="yearly">
<label>Yearly Salary</label>
<description>Job Listing(required for permanent positions only)
</description>
<text maxlength="10" validation-regex="^\d{3,5}$" />
</item>
<description>Job Listing</description>
</root-container>
<script language="javascript" location="template-type"
src="position.js"/>
</ruleset>
</data-capture-requirements>
Interwoven, Inc. 86
Index
A DTD
changes to 11
addFormHandler 61
dynamic options 19
addInstance 47
addItemHandler 61
addOption 18, 47 E
addressing 13 eableImagePreview 40
syntax 14 errata 8
using item 15 error handling
API version 38 server time-out 33
event handlers 21, 58
B onSave 24
registering 13
buttons
removing 62
defining 39
specifying 61
EventRegistry 58
C events 59
callServer 32, 39 available to user scripts 58
CGI callouts 35 onCallout 36, 58
close 40 onClose 58
contact user script 71 onCollapseOrExpand 58
OnGenerate 58
onItemChange 22, 59
D OnPreview 59
data capture template OnReplicantAdded 59
path 41 OnReplicantBeforeMove 59
DCR OnReplicantDelete 59
file size 63 OnReplicantMoved 60
generate names 67 onSave 23, 60
information 63 onSaveDone 25, 60
meta information 64 onSaveNameSpecified 25, 60
modification date 64 onSaveValid 24, 60
modified 45, 65 when triggered 21
name 63, 66
obtaining information 63
owner 64
path 41
path generator 67
saving 45, 67
saving unchanged 46
DCT
path 41
debugging 57
deleteInstance 48
displayMessage 40
F getValue 18, 51
Form Settings getVersion 38
modify 68 getWorkarea 44
form type gotoPage 44
obtaining 41 groups 42
FormAPI
changes to FormsPublisher 34 H
forms
highlighted 46 handler 21
items in 43
items on 47 I
methods for 39 instances
redrawing 44 moving 53
validation 24 invalid items
FormsPublisher version 38 highlighting 45
frame isCollapsed 51
obtaining 43 isHighlightMode 45
isModified 45
G isModifiedInWA 65
isMultiSelect 51
getAutoDCRPathGenerator 67
isReadOnly 26, 52
getChildByName 48
isRequired 52
getChildren 48
isValid 30, 52
getCurrentPageNumber 41
isVisible 26, 52
getDCRName 63 items
getDCRPath 41 children 48
getDCTPath 41 collapsed 51
getDescription 49 multiple selections 51
getExtension 70 name 49
getFileSize 63 options 47, 49
getFormType 41 read-only 55
getGroups 42 removing options 53
getItem 42, 50 required 52, 56
getLabel 49 setting description 54
getModificationDate 64 setting focus 54
getName 49, 70 setting label 54
getOptions 18, 49 setting value of 57
getOutputFile 68 type of 50
getOwner 64 valid 52
getPageCount 42 value of 51
getPath 70 visible 52, 57
getPresentationTemplate 68 VisualFormat 53
getRegex 50 IWAPI 38
getRoles 43 IWDatacapture 15, 19, 39
getRootItems 43 IWDCRInfo 63
getScriptFrame 43 constants 63
getStatus 64 IWEventRegistry 15, 21, 58
getTSTVersion 38 IWItem 26, 47
getUser 44 IWNameFactory 67
getValidPresentationTemplates 68 IWPageGeneration 68
IWPresentationTemplate 70
Interwoven, Inc. 88
Index
L iscCollapsed 51
labels isHighlightMode 45
highlighted in red 45, 46 isModified 45
lists of options 47 isModifiedInWA 65
location user script 74 isMultiSelect 51
isReadOnly 26, 52
isRequired 52
M isValid 30, 52
message isVisible 26, 52
displaying 40 isVisualFormat 53
methods moveInstance 53
addFormHandler 61 removeFormHandler 62
addInstance 47 removeItemHandler 62
addItemHandler 61 removeOption 18, 53
addOption 18, 47 save 45
callServer 32, 39 setAutoDCRPathGenerator 67
close 40 setCollapsed 54
deleteInstance 48 setDCRName 66
displayMessage 40 setDescription 54
enableImagePreview 40 setFocus 54
getAutoDCRPathGenerator 67 setHighlightMode 46
getChildByName 48 setIsModified 46
getChildren 48 setLabel 54
getCurrentPageNumber 41 setOptions 18
getDCRName 63 setOutputFile 69
getDCRPath 41 setPresentationTemplate 69
getDCTPath 41 setReadOnly 26, 55
getDescription 49 setRegex 55
getExtension 70 setRequired 56
getFileSize 63 setValid 30
getFormType 41 setValue 18, 57
getGroups 42 setVisible 26, 57
getItem 42, 50 toString 57
getLabel 49 moveInstance 53
getModificationDate 64
getName 49, 70
getOptions 18, 49
O
getOutputFile 68 objects
getOwner 64 IWAPI 38
getPageCount 42 IWDatacapture 15, 19, 39
getPath 70 IWDCRInfo 63
getPresentationTemplate 68 IWEventRegistry 15, 21
getRegex 50 IWItem 26, 47
getRoles 43 IWNameFactory 67
getRootItems 43 IWPageGeneration 68
getScriptFrame 43 IWPresentationTemplate 70
getStatus 64 returning 42
getTSTVersion 38 onCallout 36, 58
getUser 44 onClose 58
getValidPresentationTemplates 68 onCollapseOrExpand 58
getValue 18, 51 OnGenerate 58
getVersion 38 onItemChange 22, 59
getWorkarea 44 OnPreview 59
gotoPage 44 OnReplicantAdded 59
OnReplicantBeforeAdd 59 S
OnReplicantBeforeMove 59 save 45
OnReplicantDelete 59 script tag 11
OnReplicantMoved 60 server
onSave 23, 60 time-out 33
onSaveDone 25, 60 setAutoDCRPathGenerator 67
onSaveNameSpecified 60 setCollapsed 54
onSavenameSpecified 25 setDCRName 66
onSaveValid 24, 60 setDescription 54
options setFocus 54
IWEventRegistry 58 setHighlightMode 46
removing 53 setIsModified 46
organization user script 77 setLabel 54
output file 69 setOptions 18
outputfile 68 setOutputFile 69
setPresentationTemplate 69
P setReadOnly 26, 55
page number setRegex 55
obtaining 41 setRequired 56
pages setValid 30
number of 42 setValue 18, 57
paths setVisible 26, 57
absolute 14
position user script 81 T
presentation template 68, 69, 70
extension 70 thumbnails
name 70 displaying 40
path 70 toString 57
previewing 68, 69
U
R URL 39
read-only 26 user 42, 43
example 27 groups 42
read-only flag 52 obtaining name 44
read-only items 55 obtaining workarea 44
redraw roles 43
specified page 44 user script
regular expressions 50, 55 contact 71
removeFormHandler 62 location 74
removeItemHandler 62 location of 11
removeOption 18, 53 naming guidelines 13
replicants organization 77
adding 47 position 81
collapsing 54
deleting 48
expanding 54
required items 52, 56
roles 43
Interwoven, Inc. 90
Index
V
validation 50, 52, 55
dynamic 30
form 24
save 30
version
API 38
FormsPublisher 38
visibility 26, 52, 57
VisualFormat control 53
W
window
close 40
Interwoven, Inc. 92