2 Introduction to XForms
XForms has been designed on the basis of several years' experience with HTML forms. HTML forms have formed the backbone of the e-commerce revolution, and having shown their worth, have also indicated numerous ways they could be improved.
The primary difference when comparing XForms with HTML forms, apart from XForms being in XML, is the separation of the data being collected from the markup of the controls collecting the individual values. By doing this, it not only makes XForms more tractable by making it clear what is being submitted where, it also eases reuse of forms, since the underlying essential part of a Form is no longer irretrievably bound to the page it is used in.
A second major difference is that XForms, while designed to be integrated into XHTML, is no longer restricted only to be a part of that language, but may be integrated into any suitable markup language.
XForms has striven to improve authoring, reuse, internationalization, accessibility, usability, and device independence. Here is a summary of the primary benefits of using XForms:
- Strong typing
Submitted data is strongly typed and can be checked using off-the-shelf tools. This speeds up form filling since it reduces the need for round trips to the server for validation.
- XML submission
This obviates the need for custom server-side logic to marshal the submitted data to the application back-end. The received XML instance document can be directly validated and processed by the application back-end.
- Existing schema re-use
This obviates duplication, and ensures that updating the validation rules as a result of a change in the underlying business logic does not require re-authoring validation constraints within the XForms application.
- External schema augmentation
This enables the XForms author to go beyond the basic set of constraints available from the back-end. Providing such additional constraints as part of the XForms Model enhances the overall usability of the resulting Web application.
- Internationalization
Using XML 1.0 for instance data ensures that the submitted data is internationalization ready.
- Enhanced accessibility
XForms separates content and presentation. User interface controls encapsulate all relevant metadata such as labels, thereby enhancing accessibility of the application when using different modalities. XForms user interface controls are generic and suited for device-independence.
- Multiple device support
The high-level nature of the user interface controls, and the consequent intent-based authoring of the user interface makes it possible to re-target the user interaction to different devices.
- Less use of scripting
By defining XML-based declarative event handlers that cover common use cases, the majority of XForms documents can be statically analyzed, reducing the need for imperative scripts for event handlers.
2.1 An Example
In the XForms approach, forms are comprised of a section that describes what the form does, called the XForms Model, and another section that describes how the form is to be presented.
Consider a simple electronic commerce form that might be rendered as follows:

It is clear that we are collecting a value that represents whether cash or a credit card is being used, and if a credit card, its number and expiration date.
This can be represented in the XForms model element, which in XHTML would typically be contained within the head section:
<xforms:model>
<xforms:instance>
<ecommerce xmlns="">
<method/>
<number/>
<expiry/>
</ecommerce>
</xforms:instance>
<xforms:submission action="http://example.com/submit" method="post" id="submit" includenamespaceprefixes=""/>
</xforms:model> This simply says that we are collecting three pieces of information (note that we have as yet not said anything about their types), and that they will be submitted using the URL in the action attribute.
XForms defines a device-neutral, platform-independent set of form controls suitable for general-purpose use. The controls are bound to the XForms Model via the XForms binding mechanism, in this simple case using the ref attribute on the controls. In XHTML, this markup would typically appear within the body section (note that we have intentionally defaulted the XForms namespace prefix here):
<select1 ref="method">
<label>Select Payment Method:</label>
<item>
<label>Cash</label>
<value>cash</value>
</item>
<item>
<label>Credit</label>
<value>cc</value>
</item>
</select1>
<input ref="number">
<label>Credit Card Number:</label>
</input>
<input ref="expiry">
<label>Expiration Date:</label>
</input>
<submit submission="submit">
<label>Submit</label>
</submit>Notice the following features of this design:
The user interface is not hard-coded to use radio buttons. Different devices (such as voice browsers) can render the concept of "select one" as appropriate.
Core form controls always have labels directly associated with them as child elements— this is a key feature designed to enhance accessibility.
There is no need for an enclosing
formelement, as in HTML. (See 2.4 Multiple Forms per Document for details on how to author multiple forms per document)Markup for specifying form controls has been simplified in comparison with HTML forms.
The fact that you can bind form controls to the model like this simplifies integrating XForms into other host languages, since any form control markup may be used to bind to the model.
2.2 Providing XML Instance Data
The XForms Processor can directly submit the data collected as XML. In the example, the submitted data would look like this:
Submitted Data
<ecommerce> <method>cc</method> <number>1235467789012345</number> <expiry>2001-08</expiry> </ecommerce>
XForms processing keeps track of the state of the partially filled form through this instance data. Initial values for the instance data may be provided or left empty as in the example. Element instance essentially holds a skeleton XML document that gets updated as the user fills out the form. It gives the author full control on the structure of the submitted XML data, including namespace information. When the form is submitted, the instance data is serialized as an XML document. Here is an alternative version of the earlier example:
Model
<xforms:model>
<xforms:instance>
<payment method="cc" xmlns="http://commerce.example.com/payment">
<number/>
<expiry/>
</payment>
</xforms:instance>
<xforms:submission action="http://example.com/submit" method="post" includenamespaceprefixes="#default"/>
</xforms:model>In this case the submitted data would look like this:
Submitted Data
<payment method="cc" xmlns="http://commerce.example.com/payment"> <number>1235467789012345</number> <expiry>2001-08</expiry> </payment>
This design has features worth calling out:
There is complete flexibility in the structure of the XML instance data, including the use of attributes. Notice that XML namespaces are used, and that a wrapper element of the author's choosing contains the instance data.
Empty elements
numberandexpiryserve as place-holders in the XML structure, and will be filled in with form data provided by the user.An initial value (
"cc") for the form control is provided through the instance data, in this case an attributemethod. In the submitted XML, this initial value will be replaced by the user input, if the user changes the form control displaying that data.
To connect this instance data with form controls, the ref attributes on the form controls need to be changed to point to the proper part of the instance data, using binding expressions:
Binding Form Controls to Instance Nodes with ref
... xmlns:my="http://commerce.example.com/payment" ... <xforms:select1 ref="@method">...</xforms:select1> ... <xforms:input ref="my:number">...</xforms:input> ... <xforms:input ref="/my:payment/my:expiry">...</xforms:input>
Binding expressions are based on XPath [XPath 1.0], including the use of the @ character to refer to attributes, as seen here. Note that for illustrative purposes, the first two expressions make use of the XPath context node, which defaults to the top-level element (here my:payment). The third expression shows an absolute path.
2.3 Constraining Values
XForms allows data to be checked for validity as the form is being filled. In the absence of specific information about the types of values being collected, all values are returned as strings, but it is possible to assign types to values in the instance data. In this example, number should accept digits only, and should have between 14 and 18 digits and expiry should accept only valid month/date combinations.
Furthermore, the credit card information form controls for number and expiry are only relevant if the "cc" option is chosen for method, but are required in that case.
By specifying an additional component, model item properties, authors can include rich declarative validation information in forms. Such information can be taken from XML Schemas as well as XForms-specific additions, such as relevant. Such properties appear on bind elements, while Schema constraints are expressed in an XML Schema fragment, either inline or external. For example:
Declarative Validation with Model Item Properties
... xmlns:my="http://commerce.example.com/payment"...
<xforms:model>
...
<xforms:bind nodeset="/my:payment/my:number"
relevant="/my:payment/@method = 'cc'"
required="true()"
type="my:ccnumber"/>
<xforms:bind nodeset="/my:payment/my:expiry"
relevant="/my:payment/@method = 'cc'"
required="true()"
type="xsd:gYearMonth"/>
<xs:schema ...>
...
<xs:simpleType name="ccnumber">
<xs:restriction base="xsd:string">
<xs:pattern value="\d{14,18}"/>
</xs:restriction>
</xs:simpleType>
...
</xs:schema>
</xforms:model>Note:
In the above example, the relevant expression uses absolute XPath notation (beginning with /) because the evaluation context nodes for computed expressions are determined by the binding expression (see 7.2 Evaluation Context), and so any relative node path in the first bind relevant above would be relative to /my:payment/my:number
2.4 Multiple Forms per Document
XForms processing places no limits on the number of individual forms that can be placed in a single containing document. When a single document contains multiple forms, each form needs a separate model element, each with an id attribute so that they can be referenced from elsewhere in the containing document.
In addition, form controls should specify which model element contains the instance data to which they bind. This is accomplished through a model attribute that is part of the binding attributes. If no model attribute is specified on the binding element, the nearest ancestor binding element's model attribute is used, and failing that, the first XForms Model in document order is used. This technique is called 'scoped resolution', and is used frequently in XForms.
The next example adds an opinion poll to our electronic commerce form.
Adding a poll model
<xforms:model>
<xforms:instance>
...payment instance data...
</xforms:instance>
<xforms:submission action="http://example.com/submit" method="post"/>
</xforms:model>
<xforms:model id="poll">
<xforms:instance>
<helpful/>
</xforms:instance>
<xforms:submission id="pollsubmit" .../>
</xforms:model>Additionally, the following markup would appear in the body section of the document:
Form Controls for poll model
<xforms:select1 ref="/helpful" model="poll">
<xforms:label>How useful is this page to you?</xforms:label>
<xforms:item>
<xforms:label>Not at all helpful</xforms:label>
<xforms:value>0</xforms:value>
</xforms:item>
<xforms:item>
<xforms:label>Barely helpful</xforms:label>
<xforms:value>1</xforms:value>
</xforms:item>
<xforms:item>
<xforms:label>Somewhat helpful</xforms:label>
<xforms:value>2</xforms:value>
</xforms:item>
<xforms:item>
<xforms:label>Very helpful</xforms:label>
<xforms:value>3</xforms:value>
</xforms:item>
</xforms:select1>
<xforms:submit submission="pollsubmit">
<xforms:label>Submit</xforms:label>
</xforms:submit>The main difference here is the use of model="poll", which identifies the instance. Note that submit refers to the submission element by ID and does not require binding attributes.
More XForms examples can be found in H Complete XForms Examples.
7 XPath Expressions in XForms
XForms uses XPath to address instance data nodes in binding expressions, to express constraints, and to specify calculations. XPath expressions in XForms are based on [XPath 1.0]. A future version of XForms is expected to enable use of [XPath 2.0]. At the time of evaluation, an XPath expression must be syntactically correct. In addition, the namespaces the expression references must be in scope and the functions and variables it references must be defined. If any of these conditions is not satisfied, an exception (4.5.2 The xforms-compute-exception Event) is raised, except for binding expressions, which produce a different exception (4.5.1 The xforms-binding-exception Event).
7.1 XPath Datatypes
XPath datatypes are used only in binding expressions and computed expressions. XForms uses XPath datatypes boolean, string, number, and node-set. Additionally, the type object is used to denote a parameter or return value that can be any one of the four XPath datatypes. A future version of XForms is expected to use XPath 2.0, which includes support for XML Schema datatypes.
7.2 Evaluation Context
Within XForms, the default model is the first model in document order. The default instance of any model is the first child instance in document order within that model. XPath expressions appearing in various XForms attributes are used to reference instance data. Every XPath expression requires an evaluation context consisting of a node, position, size, variable bindings, function set, and namespace context. For all evaluation contexts in XForms,
No variable bindings are in place.
The available function library is defined below in 7.5 The XForms Function Library.
Any namespace declarations in scope for the attribute that defines the expression are applied to the expression.
The context node, position and size are determined according to rules described below.
A binding element is any element that is explicitly allowed to have a binding expression attribute, and a bound element is any element that explicitly declares a binding expression attribute. A binding expression attribute contains an XPath expression that references zero or more nodes of instance data. Every XPath expression requires an evaluation context. The in-scope evaluation context of a binding element provides an evaluation context for the binding expression attribute. The following rules are used in determining the node, position and size of the in-scope evaluation context:
A binding element is "outermost" if the element has no ancestor binding elements. If an outermost binding element is contained by a
model, then the context node for the outermost binding element is the top-level document element node of the default instance of the containingmodelelement. Otherwise, the context node for outermost binding elements is the top-level document element node of the default instance in the default model. For outermost binding elements, the context size and position are 1.The context node, position and size for non-outermost binding elements is determined using the binding expression attribute or in-scope evaluation context of the nearest ancestor binding element. This is also referred to as "scoped resolution". For a non-outermost binding element:
If the nearest ancestor binding element is not a bound element, then the in-scope evaluation context of the non-outermost binding element is equivalent to the in-scope evaluation context of the nearest ancestor binding element.
If the nearest ancestor binding element expresses a Single-Node binding, then the in-scope evaluation context of the non-outermost binding element has a context size and position of 1 and the context node is the one resulting from the Single-Node binding of the nearest ancestor binding element.
If the nearest ancestor binding element expresses a Node Set binding, then the XForms processor dynamically generates an occurrence of the non-outermost binding element for each of the nodes in the Node Set Binding of the nearest ancestor binding element. The dynamic in-scope evaluation context for each generated occurrence of the non-outermost binding element has a context size equal to the size of the nodeset identified by the Node Set Binding of the nearest ancestor binding element, the context node is the node for which the occurrence of the non-outermost binding element was generated, and the position is equal to the position of the generator node in the nodeset identified by the Node Set Binding of the nearest ancestor binding element.
If the nearest ancestor binding element expresses a Node Set binding, then the non-outermost binding element has its own in-scope evaluation context separately from those of its dynamically generated occurences described above. The in-scope evaluation context has a context position of 1, and the context node and size are set by the first node and the size of the nodeset identified by the Node Set binding of the nearest ancestor binding element.
Once the context node of the in-scope evaluation context has been determined according to the rules above, if the binding element expresses a
modelattribute that refers to amodelother than the one containing the context node, then the context node of the in-scope evaluation context is changed to be the top-level document element node of the default instance of the referencedmodel, and the context position and size are changed to 1.
The in-scope evaluation context of an element that is not a binding element is the same as if the element were a binding element. For example, the in-scope evaluation context for the setindex action element is required to provide the context for evaluating the index attribute, so it is determined as if the element could contain a binding expression attribute.
XPath expressions also appear in model item property attributes of the bind element to define computed expressions. If the bind element does not express a Node Set binding, then the in-scope evaluation context for model item property attributes of the bind is equal to the in-scope evaluation context for the bind. Otherwise, the bind has a Node Set binding, and computed expressions for each model item property attribute are generated for each node. For each computed expression generated, the evaluation context node, position and size are determined by the same method as dynamic in-scope evaluation context rule above, except the computed expression is used in lieu of a binding expression attribute such that the bind element is the nearest ancestor binding element.
XPath expressions also appear in the special attributes of several other XForms elements, such as the value attribute on setvalue and output, the at attribute of insert and delete, or the index attribute of setindex. Generally, if the containing element does not express a Single Node Binding or Node Set Binding, then the special attribute is evaluated using the in-scope evaluation context. Special attributes may be evaluated using the in-scope evaluation context even if the containing element expresses a Single Node Binding or Node Set Binding. However, for some special attributes, the evaluation context node, position and size are based on the result of the Single Node Binding or Node set Binding. Each special attribute that contains an XPath expression describes how its evaluation context node, position and size are determined.
In the following example, the group has a binding expression of level2/level3. According to the rules above, this outermost element node would have a context node of /level1, which is the document element node of the instance data. The select1 form control then inherits a context node from the parent group.
Sample XML Instance Data
<level1>
<level2>
<level3 attr="xyz"/>
</level2>
</level1>Binding Expression Context Nodes
<group ref="level2/level3">
<select1 ref="@attr" ... >
<label>...</label>
</select1>
</group>This section describes how the in-scope evaluation context of an element is determined, not whether the in-scope evaluation will be used. The Single-Node Binding or Node Set Binding of a non-outermost binding element is not evaluated if the in-scope evaluation context does not contain a context node. This can occur if the Single-Node Binding or Node Set Binding of the nearest ancestor bound element produces an empty nodeset. Also, if the Single-Node Binding or Node Set Binding of an element is expressed with the bind attribute, then the resulting node or nodeset is obtained from the referenced bind element. The nodeset attribute of a bind element is evaluated using the in-scope evaluation of the bind element, not the in-scope evaluation context of an element that references it with a bind attribute.
7.3 References, Dependencies, and Dynamic Dependencies
An XPath expression references a node of instance data if the node is selected during the evaluation of the expression. A node is selected by matching an XPath NodeTest or by being returned by a function call. For examples, a node can match a name test, a wildcard test, a node type test, or it can be returned by or used as a parameter to a function, or it can appear in a filter expression (where all of the prior examples recursively apply). Once selected, a node is considered to be referenced even if a filter expression subsequently excludes the node from further participation in the expression evaluation. The reference list of an XPath expression is the set of instance nodes that it references.
Example of References and Non-References
Given the following default instance:
<xforms:instance>
<data xmlns="">
<a attr="X">
<b attr="Y">
<c/>
</b>
<d/>
</a>
<a attr="Z">
<b attr="Z">
<c/>
</b>
<d/>
</a>
</data>
</xforms:instance>
and the following XPath expression:
a[@attr='X']/b[@attr='X']/c
Both nodes named a are referenced since both are matched by a NameTest. The attr attribute in each element a
is referenced during the evaluation of the filter expression. The filter expression rejects the second element a, but that element is still considered
to have been referenced because it was selected for further processing during the expression evaluation.
The element named b in the first element a is referenced, but element b in the second a is not referenced
because the expression evaluation did not proceed beyond the filter expression that rejected the second a element.
While performing the NameTest for element b, observe that an XPath expression evaluator may visit all the children of the first element a
in order to perform the NodeTest. However, a node is not referenced if it is only visited but fails the NodeTest. In this case, the NodeTest is a NameTest for b,
which the element d fails. Therefore, d is not referenced.
The filter expression test on b rejects the only element b that has been selected so far because the attribute value of attr
does not match the equality test. Still, b and its attribute attr have been referenced by this expression.
Element c is not considered to be referenced by this expression given this data. Although a NameTest for c appears in the expression,
the evaluation of the expression did not proceed to perform the NameTest due to the rejection of b by the filter expression.
Finally, note that an XPath expression can reference many nodes even if its final result is an empty nodeset.
Note:
Defining a reference in terms of matching a NodeTest was a deliberate design decision that creates more references than necessary in order to make the computation system more responsive to certain types of changes without needing a rebuild operation. When a leaf node is filtered from an expression by a predicate, the leaf node is still considered to be referenced so that if the condition changes such that the leaf node would be included in the result value of the expression, then the expression will be recalculated without needing a rebuild. However, once a node is rejected from an expression, further location steps are not evaluated relative to the rejected node, so references for that location step are only created based on its execution relative to accepted nodes. For example, if the above expression were in a calculate, and if the attribute of either b element changes to the value X, the expression would be recalculated but it still does not record a reference to any c elements until the references are obtained in the next rebuild operation. Moreover, the excess references created by the definition may cause some recalculation constructs to cease operation due to circular references that would not be created with a stricter definition of a reference. A future version of XForms may use a stricter version of referencing for recalculation and a less strict definition of referencing for the purpose of detecting and performing automatic rebuild operations.
The referencing of a repeat index by the index() function is handled as a special case. Implementations must behave as if each occurrence of a repeat is associated with an implicitly managed instance data node containing the repeat index. If a repeat identified as R1 contains a repeat identified as R2, then a repeat index instance node is managed for each occurrence of R2 that is generated by R1. An invocation of the function index() in an XPath expression is considered to reference the repeat index instance node corresponding to the repeat index value that it returns.
If an XPath expression references an instance node, then the expression result is dependent on the instance node. A dependency list for an instance node is the list of XPath expressions of a given category that are dependent upon the instance node. For example, in Section 4.3.2 The xforms-recalculate Event, the dependency list of computed expressions for each instance node helps establish the recalculation order for the computed expressions when the values of instance data nodes are changed.
The references of an XPath expression may be altered by insertion of instance nodes since the new nodes may be referenced by the XPath expression if it is re-evaluated. Similarly, the references of an XPath expression may be altered by deletion of instance nodes that are being referenced by the XPath expression. An XPath expression is dynamically dependent on an instance node if its reference list is altered by inserting, deleting or changing the value of the instance node. An instance node is a dynamic dependency for an XPath expression if the expression is dynamically dependent on the instance node. If an XPath expression contains a dynamic dependency and the XForms processor is maintaining dependency lists for the category of the XPath expression, then changing the dynamic dependency implies a change to the dependency lists of instance nodes referenced by the XPath expression.
The computational dependency data structure described in Section 4.3.2 The xforms-recalculate Event essentially stores the dependency lists of instance nodes corresponding to all the references made by computed expressions (see Appendix C Recalculation Sequence Algorithm for details). The computational dependency data structure is not reconstructed in response to a dynamic dependency change. Instead, the form author may request a rebuild of the computational dependency data structures using the rebuild action. Additionally, the insert and delete actions set a rebuild flag so that computational dependency data structures will be rebuild at the end of an action sequence.
Due to the rebuild flag setting on insert and delete, a form author can use many kinds of dynamic dependencies in model binding expressions and computed expressions without ever explicitly invoking the rebuild action. This includes the use of functions such as position(), last(), and count() on element and attribute nodes because the return values of the functions in these cases is fixed except when an insert or delete occurs. By comparison, functions such as id(), instance(), and index() can establish dynamic dependencies that can necessitate invoking a rebuild if they are used in model binding expressions or computed expressions because the results of the functions are affected by changing the values of instance nodes, not by inserting or deleting nodes.
7.4 Expression Categories
There are several different categories of XPath expressions used in XForms, and they are processed at different times depending on the category. A binding expression is an XPath expression used to bind a model item property to one or more instance nodes, or to bind a form control to instance data, or to specify the node or node set for operation by an action. The evaluation schedule for binding expressions differs based on whether the binding expression is a model binding expression, UI binding expression, or a binding expression for an XForms action. XPath expressions are also used in various other attributes of XForms binds, actions, form controls, and submissions, and their descendant elements. These expressions follow one of the three schedules associated with binding expressions as described below.
7.4.1 Model Binding Expressions and Computed Expressions
A model binding expression is a kind of binding expression that can be used to declare model item properties, and is used in the Node-Set binding of the bind element. A computed expression is an XPath expression used to determine the value of a model item property based on instance data. Several of the attributes of bind are computed expressions, including calculate, readonly, relevant, and required.
Dynamic dependencies in model binding expressions and computed expressions will require manual rebuilding of dependencies.
Note:
If the index() function is being invoked from a model binding expression or computed expression, it will be necessary to invoke rebuild manually. If the repeat index change occurs due to an implicit behavior such as a change to the focused form control, then the rebuild (along with recalculate, revalidate and refresh) can be invoked from a handler for DOMFocusIn attached to the repeat or each repeat object.
7.4.2 Expressions in Actions and Submissions
Binding expressions on XForms actions and XPath expressions appearing in other attributes of XForms actions are evaluated at the time the XForms action is performed. In some cases, XForms actions have child elements that allow the values of some of their attributes to be determined based on instance data. In these cases, the value attribute of the child element is evaluated at the time the corresponding attribute is needed in the processing model of the containing XForms action.
Similarly, XPath expressions used in the attributes of submission and its child elements (other than XForms actions) are evaluated as needed within the submission processing model.
Form authors can use dynamic dependencies in the XPath expressions of XForms Actions and Submissions without invoking any special data structure reconstruction actions because implementations must behave as if these expressions are evaluated as needed.
7.4.3 UI Expressions
A UI Binding Expression is a Single Node Binding or Node Set Binding in a form control.
A UI expression is a UI Binding Expression or an XPath expression appearing in a descendant element of a form control, except for XPath expressions in the categories described above (such as XForms action expressions). These include the Single Node Bindings and Node Set Bindings of the additional elements that contribute to the behavior of a form control (including label, help, hint and alert, filename and mediatype) and the selection helper elements (itemset, label, value and copy). This also includes the value attribute on output and value elements.
Form authors can use dynamic dependencies in UI Expressions without invoking any special data structure reconstruction actions because the state of the user interface at the end of processing xforms-refresh is required to reflect the instance data as if all UI Expressions had been re-evaluated.
Note:
Implementations may record UI Expression dependency lists on instance nodes to help streamline detection of the need to re-evaluate a UI Expression at the beginning of processing for xforms-refresh. Such implementations may determine that a UI Expression is stale (needs re-evaluation) when a node on which it depends has been changed. An implementation may also indicate that all UI Expressions are stale if a node of instance data is inserted, deleted or replaced, or the implementation may streamline detection of which UI Expressions may be affected by the insertion, deletion or replacement of an instance data node.
7.4.4 UI Binding in other XML vocabularies
The XForms binding mechanism allows other XML vocabularies to make single node bindings between custom user interface controls and XForms instance data. As an example, XForms binding attribute bind might be used within XHTML 1.x user interface controls as shown below. See 3.2.3 Single-Node Binding Attributes.
XForms Binding In XHTML 1.x User Interface Controls
<html:input type="text" name="..." xforms:bind="fn"/>
7.4.5 Binding Examples
Consider the following document with the one-and-only XForms model:
<xforms:model id="orders">
<xforms:instance xmlns="">
<orderForm>
<shipTo>
<firstName>John</firstName>
</shipTo>
</orderForm>
</xforms:instance>
<xforms:bind nodeset="/orderForm/shipTo/firstName" id="fn" />
</xforms:model>The following examples show three ways of binding user interface control xforms:input to instance element firstName declared in the model shown above.
UI Binding Using Attribute ref
<xforms:input ref="/orderForm/shipTo/firstName">...
UI Binding Using Attribute bind
<xforms:input bind="fn">...
Specifies Model Containing The Instance Explicitly
<xforms:input model="orders" ref="/orderForm/shipTo/firstName">...
7.5 The XForms Function Library
The XForms Function Library includes the entire [XPath 1.0] Core Function Library, including operations on node-sets, strings, numbers, and booleans.
The following sections define additional required functions for use within XForms : 7.6 Boolean Functions, 7.7 Number Functions, 7.8 String Functions, 7.9 Date and Time Functions, 7.10 Node-set Functions , and 7.11 Object Functions.
The function library provided by an XForms processor may also contain other extension functions as described in 7.12 Extension Functions.
If an error occurs in an XPath function, then an 4.5.2 The xforms-compute-exception Event or 4.5.1 The xforms-binding-exception Event occurs..
7.6 Boolean Functions
7.6.1 The boolean-from-string() Function
boolean boolean-from-string(string)
Function boolean-from-string returns true if the required parameter string is
"true" or "1", or false if parameter string is "false", or "0". This is useful when referencing a
Schema xsd:boolean datatype in an XPath expression. If the parameter string matches none of the above strings,
according to a case-insensitive comparison, the return value is false.
7.6.2 The is-card-number() Function
boolean is-card-number(string?)
If the string parameter conforms to the pattern restriction of the card-number datatype, then this function applies the Luhn algorithm described in [Luhn Patent] and returns true if the number satisfies the formula. Otherwise, false is returned. If the parameter is omitted, it defaults to the string-value of the current context node.
Examples (see also 5.2.7 xforms:card-number):
returns true if and only if the context node contains a string that contains of zero or more digits and satisfies the formula.
is-card-number('4111111111111111')returns true. Other examples of string constants that will return true are : 5431111111111111, 341111111111111 and 6011601160116611.
returns false.
7.7 Number Functions
7.7.1 The avg() Function
number avg(node-set)
Function avg returns the arithmetic average of the result of converting the string-values of each node in
the argument node-set to a number. The sum is computed with sum(), and divided with div by the
value computed with count(). If the parameter is an empty node-set, or if any of the nodes evaluate to NaN,
the return value is NaN.
7.7.2 The min() Function
number min(node-set)
Function min returns the minimum value of the result of converting the string-values of each node in argument node-set to a number. "Minimum" is determined with the < operator. If the parameter is an empty node-set, or if any of the nodes evaluate to NaN, the return value is NaN.
7.7.3 The max() Function
number max(node-set)
Function max returns the maximum value of the result of converting the string-values of each node in argument node-set to a number. "Maximum" is determined with the < operator. If the parameter is an empty node-set, or if any of the nodes evaluate to NaN, the return value is NaN.
7.7.4 The count-non-empty() Function
number count-non-empty(node-set)
Function count-non-empty returns the number of non-empty nodes in argument node-set. A node is considered non-empty if it is convertible into a string with a greater-than zero length.
7.7.5 The index() Function
number index(string)
Function index takes a string argument that is the IDREF of a repeat and returns the
current 1-based position of the repeat index for the identified repeat—see 9.3.1 The repeat Element for details on
repeat and its associated repeat index. If the specified argument does not identify a repeat,
the function returns NaN.
Note:
The IDREF obtained from the function parameter may not uniquely identify
the desired repeat if the repeat element bearing the
matching ID resides
in a repeating construct such as element repeat.
The general method described in
4.7 Resolving ID References in XForms
is used to determine the desired run-time repeat object.
index
<xforms:trigger>
<xforms:label>Add to Shopping Cart</xforms:label>
<xforms:insert ev:event="DOMActivate" position="after"
nodeset="items/item" at="index('cartUI')"/>
</xforms:trigger>7.7.6 The power() Function
number power(number, number)
Raises the first argument to the power of the second argument, returning the result. If
the calculation does not result in a real number, then NaN is returned.
Examples:
returns 8
returns NaN.
if (prin>0 and dur>0 and rate>0, prin*rate/(1-power(1+rate, -dur)), 0)
returns a compounded interest payment value given a non-zero principal (prin),
duration (dur) and periodic interest rate (rate).
7.7.7 The random() Function
number random(boolean?)
This function generates and returns a uniformly distributed random or pseudorandom number in the
range from 0.0 up to but excluding 1.0.
This function accepts an author-optional boolean parameter that is false by default. If true, the
random number generator for this function is first seeded with a source of randomness before generating the return value.
A typical implementation may seed the random number generator with the current system time in milliseconds when
random(true) is invoked, and it may apply a linear congruential formula to generate return values on
successive invocations of the function.
Example:
could return 0.14159265358979
7.7.8 The compare() Function
number compare(string, string)
This function returns -1, 0, or 1, depending on whether the value of the first argument is respectively less than, equal to, or greater than the value of second argument based on lexicographic comparison using Unicode code point values [Unicode Collation Algorithm].
Example:
compare('apple', 'orange')returns -1
7.8 String Functions
7.8.1 The if() Function
string if(boolean, string, string)
Function if evaluates the first parameter as boolean, returning the second parameter when true, otherwise the third parameter.
Note:
This function is deprecated because a future version of XForms is expected to be based on [XPath 2.0], which contains an if construct that is incompatible with this function.Form authors and design tools are encouraged to use the function choose() from Section 7.11.1 The choose() Function instead of this function.
7.8.2 The property() Function
string property(string)
This function accepts a string identifying a property name. If the property name is not recognized, empty string is returned. The property definitions for this function are as follows:
| Property | Return Value |
|---|---|
version | 1.1 |
conformance-level | full, basic or a string beginning with full or basic |
| Any other NCName | Reserved. Their use results in an exception (see 7.5 The XForms Function Library for the exception type) |
| QNameButNotNCName | An implementation-specific property value, such as a locale or timezone for the user agent. If the implementation does not support the property, then empty string is returned. |
Examples:
returns 1.1
property('conformance-level')may return full
7.8.3 The digest() Function
string digest(string, string, string?)
This function accepts a string of data, a string indicating a cryptographic hashing algorithm, and an author-optional string indicating an encoding method. The data string is serialized as UTF-8, the hash value is then computed using the indicated hash algorithm, and the hash value is then encoded by the indicated method, and the result is returned by the function. The following table presents the keywords for the second string parameter and the corresponding hash algorithms:
This recommendation defines the values hex and base64 for the third string parameter that indicates
the encoding method. If the parameter is missing, then the default is base64. The hex and base64
encoding methods of this function correspond to the encodings defined in [XML Schema part 2] for the datatypes hexBinary
and base64Binary, respectively. For the hexadecimal encoding, the digits 'a' through 'f'
are encoded with lower case letters. Any other string value given for the encoding method results in an exception
(see 7.5 The XForms Function Library for the exception type).
digest('abc', 'SHA-1', 'hex')returns a9993e364706816aba3e25717850c26c9cd0d89d.
digest('abc', 'MD5', 'hex')returns 900150983cd24fb0d6963f7d28e17f72.
digest('abc', 'SHA-256', 'hex')returns ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
7.8.4 The hmac() Function
string hmac(string, string, string, string?)
This function accepts a string for a key or shared secret, a string of data, a string indicating a cryptographic hashing algorithm, and an author-optional string indicating an encoding method. The key and data strings are serialized as UTF-8, and they are subjected to the HMAC algorithm defined in [HMAC] and parameterized by the the hash algorithm indicated by the third parameter. The result is encoded with the method indicated by the fourth parameter, and the result is returned by the function.
The following table presents the keywords for the third string parameter and the corresponding hash algorithms:
This recommendation defines the values hex and base64 for the fourth string parameter that indicates
the encoding method. If the parameter is missing, then the default is base64. The hex and base64
encoding methods of this function correspond to the encodings defined in [XML Schema part 2] for the datatypes hexBinary
and base64Binary, respectively. For the hexadecimal encoding, the digits 'a' through 'f'
are encoded with lower case letters. Any other string value given for the encoding method results in an exception
(see 7.5 The XForms Function Library for the exception type).
hmac('Jefe', 'what do ya want for nothing?', 'SHA-1', 'hex')returns effcdf6ae5eb2fa2d27416d5f184df9c259a7c79
hmac('Jefe', 'what do ya want for nothing?', 'MD5', 'hex')returns 750c783e6ab0b503eaa86e310a5db738
hmac('Jefe', 'what do ya want for nothing?', 'SHA-256', 'hex')returns 5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843
7.9 Date and Time Functions
Note:
The following XML Schema datatypes do not have specific functions for manipulation within XForms expressions:
xsd:time, xsd:gYearMonth, xsd:gYear, xsd:gMonthDay,
xsd:gDay, xsd:gMonth. Extension functions (7.12 Extension Functions) may
be used to perform needed operations on these datatypes.
7.9.1 The local-date() Function
string local-date()
This function returns a lexical xsd:date obtained as if by the following rules: the result of now() is
converted to a local date based on the user agent time zone information. If no time zone information is available, then the date portion
of the result of now() is returned.
Example:
could return 2006-10-13-07:00
substring(local-date(), 1, 10)
could return 2006-10-13
days-to-date(days-from-date(local-date()) + 31)
returns a date that is 31 days from today. For example, if local-date() returns 2006-10-13-07:00, then the result is 2006-11-13.
7.9.2 The local-dateTime() Function
string local-dateTime()
This function returns a lexical xsd:dateTime obtained as if by the following rules: the result of now() is
converted to a local dateTime based on the user agent time zone information. If no time zone information is available, then the result of
now() is returned.
Example:
could return 2006-10-13T16:04:17-07:00
adjust-dateTime-to-timezone(seconds-to-dateTime(seconds-from-dateTime(local-dateTime()) + 7200))
Adds two hours (7200 seconds) to the local date and time, returning the result in the local time zone. For example, if local-dateTime()
returns 2007-10-02T14:26:43-07:00, then the above expression returns 2007-10-02T16:26:43-07:00
7.9.3 The now() Function
string now()
The now function returns the current UTC date and time as a string value in the canonical
XML Schema xsd:dateTime format. If time zone information is available, it is used to convert the date and
time to UTC.
If no time zone information is available, then the date and time are assumed to be in UTC.
Note:
Attaching a calculation of "now()" to an instance data node would not result in a stream of continuous
recalculations of the XForms Model.
returns 2006-10-14T01:04:17Z if local-dateTime() returns 2006-10-13T18:04:17-07:00
seconds-to-dateTime(seconds-from-dateTime(now()) + 7200)
Computes two hours from now, returning the result in UTC time. For example, if now()
returns 2007-10-02T21:26:43Z, then the above expression returns 2007-10-02T23:26:43Z
7.9.4 The days-from-date() Function
number days-from-date(string)
This function returns a whole number of days, according to the following rules:
If the string parameter represents a legal lexical xsd:date or xsd:dateTime, the return value
is equal to the number of days difference between the specified date or dateTime (normalized to UTC) and 1970-01-01.
Hour, minute, and second components are ignored after normalization. Any other input parameter causes a return value of NaN.
Note:
If an xsd:date is given as the parameter, the timezone is ignored if provided because there is no way to normalize
to the date in the UTC timezone without both the time and timezone.
Examples:
days-from-date("2002-01-01")returns 11688
days-from-date("2002-01-01-07:00")returns 11688
days-from-date("1969-12-31")returns -1
7.9.5 The days-to-date() Function
string days-to-date(number)
This function returns a string containing a lexical xsd:date that corresponds to the number of days passed as the parameter according to the following rules:
The number parameter is rounded to the nearest whole number, and the result is interpreted as the difference between the desired date and
1970-01-01. An input parameter value of NaN results in output of the empty string.
Examples:
returns 2002-01-01
returns 1969-12-31
7.9.6 The seconds-from-dateTime() Function
number seconds-from-dateTime(string)
This function returns a possibly fractional number of seconds, according to the following rules:
If the string parameter represents a legal lexical xsd:dateTime, the return value is equal to the number of seconds difference
between the specified dateTime (normalized to UTC) and 1970-01-01T00:00:00Z.
If no time zone is specified, UTC is used.
Any other input string parameter causes a return value of NaN.
This function does not support leap seconds.
Example:
seconds-from-dateTime('1970-01-01T00:00:00Z')returns 0
seconds-from-dateTime('1970-01-01T00:00:00-08:00')returns 28800
7.9.7 The seconds-to-dateTime() Function
string seconds-to-dateTime(number)
This function returns a string containing a lexical xsd:dateTime that corresponds to the number of seconds
passed as the parameter according to the following rules:
The number parameter is rounded to the nearest whole number, and the result is interpreted as the difference between
the desired UTC dateTime and 1970-01-01T00:00:00Z.
An input parameter value of NaN results in output of the empty string.
This function does not support leap seconds.
Examples:
returns 1970-01-01T00:00:00Z
seconds-from-dateTime(28800)
returns 1970-01-01T08:00:00Z
seconds-to-dateTime(seconds-from-dateTime(now()) + 7200)
Computes two hours from now, returning the result in UTC time. For example, if now()
returns 2007-10-02T21:26:43Z, then the above expression returns 2007-10-02T23:26:43Z
adjust-dateTime-to-timezone(seconds-to-dateTime(seconds-from-dateTime(now()) + 7200))
Computes two hours from now, returning the result in the local time zone. For example, if now()
returns 2007-10-02T21:26:43Z and the local date and time is 2007-10-02T14:26:43-07:00, then the
above expression returns 2007-10-02T16:26:43-07:00
7.9.8 The adjust-dateTime-to-timezone() Function
string adjust-dateTime-to-timezone(string)
This function adjusts a legal lexical xsd:dateTime received as the string parameter to the local time zone of the implementation,
and returns the result. If the string argument contains no time zone, then the result is the string argument with the local time zone as the
time zone component. If the implementation does not have access to time zone information, UTC is used.
The result is empty string if the string argument is the empty sequence or not a legal lexical xsd:dateTime.
Examples:
adjust-dateTime-to-timezone('2007-10-07T02:22:00')returns 2007-10-07T02:22:00-07:00 in the Pacific time zone since daylight savings time applies.
adjust-dateTime-to-timezone('2007-10-02T21:26:43Z')returns 2007-10-02T14:26:43-07:00 in the Pacific time zone since daylight savings time applies.
adjust-dateTime-to-timezone(seconds-to-dateTime(seconds-from-dateTime(now()) + 7200))
Computes two hours from now, returning the result in the local time zone. For example, if now()
returns 2007-10-02T21:26:43Z and the local date and time is 2007-10-02T14:26:43-07:00, then the
above expression returns 2007-10-02T16:26:43-07:00
7.9.9 The seconds() Function
number seconds(string)
This function returns a possibly fractional number of seconds, according to the following rules:
If the string parameter represents a legal lexical xsd:duration, the return value is equal to the number specified in the
seconds component plus 60 * the number specified in the minutes component, plus 60 * 60 * the number specified in the hours component,
plus 60 * 60 * 24 * the number specified in the days component. The sign of the result will match the sign of the duration. Year and month
components, if present, are ignored. Any other input parameter causes a return value of NaN.
Note:
Even though this function is defined based on a lexical xsd:duration, it is intended for use only with
derived-from-xsd:duration datatypes, specifically xforms:dayTimeDuration.
Examples:
seconds("P3DT10H30M1.5S")returns 297001.5 (3 days, 10 hours, 30 minutes, and 1.5 seconds)
returns 0 because the year and month parts of the duration are ignored and the remaining portions are unspecified and default to 0
returns NaN because the parameter is not a lexically valid duration
7.9.10 The months() Function
number months(string)
This function returns a whole number of months, according to the following rules:
If the string parameter represents a legal lexical xsd:duration, the return value is equal to the number specified in the
months component plus 12 * the number specified in the years component. The sign of the result will match the sign of the duration.
Day, hour, minute, and second components, if present, are ignored. Any other input parameter causes a return value of NaN.
Note:
Even though this function is defined based on a lexical xsd:duration, it is intended for use only with
derived-from-xsd:duration datatypes, specifically xforms:yearMonthDuration.
Examples:
Examples:
returns 14 (1 year and 2 months)
returns -19 because the duration is negative and expresses 0 years and 19 months
7.10 Node-set Functions
7.10.1 The instance() Function
node-set instance(string?)
An XForms Model can contain more than one instance. This function allows access to instance data, within the same XForms Model, but outside the instance data containing the context node.
If the argument is omitted or is equal to the empty string, then the root element node (also called the document element node) is returned for the default instance in the model that contains the current context node.
Otherwise, the argument is converted to a string as if by a call to the string function.
This string is treated as an IDREF, which is matched against instance elements in the containing document. If a match is located,
and the matching instance data is associated with the same XForms Model as the current context node, this function returns a node-set
containing just the root element node (also called the document element node) of the referenced instance data. In all other cases,
an empty node-set is returned.
Example:
For instance data corresponding to this XML:
<xforms:instance xmlns="" id="orderform">
<orderForm>
<shipTo>
<firstName>John</firstName>
</shipTo>
</orderForm>
</xforms:instance>The following expression selects the firstName node. Note that the instance function returns an element node, effectively replacing the leftmost location step from the path:
ref="instance('orderform')/shipTo/firstName"7.10.2 The current() Function
node-set current()
Returns the context node used to initialize the evaluation of the containing XPath expression.
Examples:
For the following instance data:
<xforms:instance xmlns="">
<converter>
<amount>100</amount>
<currency>jpy</currency>
<convertedAmount></convertedAmount>
</converter>
</xforms:instance>
<xforms:instance xmlns="" id="convTable">
<convTable date="20040212" currency="cdn">
<rate currency="eur">0.59376</rate>
<rate currency="mxn">8.37597</rate>
<rate currency="jpy">80.23451</rate>
<rate currency="usd">0.76138</rate>
</convTable>
</xforms:instance>and the following value calculation bind:
<bind nodeset="convertedAmount"
calculate="../amount *
instance('convTable')/rate[@currency=current()/../currency]"/>the content value of /converter/convertedAmount is the product of /converter/amount
and the conversion table rate given by the rate element whose currency attribute value
matches the content of /converter/currency.
For the following instance data:
<xforms:instance xmlns="" id="i1">
<months>
<mon>01</mon>
<mon>02</mon>
<mon>03</mon>
</months>
</xforms:instance>
<xforms:instance xmlns="" id="i2">
<months>
<month code="01">Jan</month>
<month code="02">Feb</month>
<month code="03">Mar</month>
</months>
</xforms:instance>and the following repeat structure:
<repeat nodeset="mon">
<output value="instance('i2')/month[@code = current()]/>
</repeat>
the output should contain Jan Feb Mar.
7.10.3 The id() Function
node-set id(object, node-set?)
The object parameter provides one or more IDREFs. This may be in the form of a string containing
a space-separated list of IDREFs or a node-set, each node of which contains an IDREF. The node-set
parameter provides nodes in one or more instance data documents to be searched.
If the node-set parameter is not given or is empty, then the instance data document to be
searched is the one containing the context node of the function call. For each node in the
node-set parameter (or its default), the set of element nodes are collected with IDs that match the IDREFs from the
object parameter. The result of this function is a node-set containing the union of the collected element
nodes from each string. An element node can be assigned an ID by means of an xml:id attribute or an
attribute that is assigned the type ID by a DTD or xsd:ID or any type derived from xsd:ID by an XML schema,
or the type model item property.
Example:
Returns nodes identified by X or Y from the instance data document associated with the root element of the instance identified by Z.
7.10.4 The context() Function
node-set context()
This function returns the in-scope evaluation context node of the nearest ancestor element of the node containing the XPath expression that invokes this function. The nearest ancestor element may have been created dynamically as part of the run-time expansion of repeated content as described in Section 4.7 Resolving ID References in XForms.
Example:
<setvalue ref="x" value="context()/y"/>
This action sets node x to the value of node y, where both nodes are children of the in-scope evaluation context node for the setvalue element.
Note:
An intended use of this function is in conjunction with the repeat element (Section 9.3.1 The repeat Element and the setvalue action element (Section 10.2 The setvalue Element). The intent is to provide form authors with a means of expressing a value attribute that is relative to the repeat context node when the Single Node Binding result is not.
7.11 Object Functions
7.11.1 The choose() Function
object choose(boolean, object, object)
This function provides a conditional test that chooses an object to return based on the boolean parameter. If the boolean parameter is true, then the first object is returned, otherwise the second object is returned. Each of the object parameters can be of any XPath datatype as described in Section 7.1 XPath Datatypes, and this function does no type conversion of the parameter it chooses to return.
Note:
All parameters of an XPath function are evaluated, so the parameter that is not returned by this function is still evaluated, and its result is discarded by this function.
Note:
Form authors and design tools are encouraged to use this function instead of the function if() described in Section 7.8.1 The if() Function, which has been deprecated. Because this function returns an object instead of a string, migrating from if() to choose() may occasionally require conversion of the return result using the string() function.
Example:
choose(count(x) > 0, x, y)
Returns the node-set of matching x if it is non-empty and the node-set matching y otherwise.
If the context node of the function contains attribute x, then the nodeset containing that attribute is returned. Otherwise, the number 0 is returned.
7.11.2 The event() Function
object event(string)
Function event returns context specific information determined by the string
argument. The returned context information is an XPath object whose type and content
depends upon the requested property. Each event describes what properties can be accessed by this function
and the type and value that will be returned as the result.
The event context properties available for each event are provided in the sections that describe the events.
This function is intended for use in the XPath expressions of XForms actions. If invoked for any other XPath expression, such as a binding expression or model item property expression, this function returns the empty string. If this function is invoked from an XPath expression for an XForms action, then event context information is used from the most recently dispatched event whose action handler contains the XForms action.
Some properties defined for an event may be unavailable if certain prerequisite conditions were not met prior to the event being dispatched. Implementations may also add custom properties. If the event context information does not contain the property indicated by the string argument, then an empty node-set is returned.
Examples:
If called from an xforms-insert event handler, a nodeset is returned containing the instance data node or nodes inserted.
7.12 Extension Functions
XForms documents may use additional XPath extension functions beyond those described here. A number of useful community extensions are defined at [EXSLT]. The names of any such extension functions must be declared in attribute functions on element model. Such declarations are used by the XForms Processor to check against available extension functions. XForms Processors perform this check at the time the document is loaded, and halt processing by signaling an exception (4.5.2 The xforms-compute-exception Event) if the XForms document declares an extension function for which the processor does not have an implementation.
Note:
Explicitly declaring extension functions enables XForms Processors to detect the use of unimplemented extension functions at document load-time, rather than throwing a fatal exception (4.5.1 The xforms-binding-exception Event or 4.5.2 The xforms-compute-exception Event) during user interaction. Failure by authors to declare extension functions will result in an XForms Processor potentially halting processing during user interaction with a fatal error.
10 XForms Actions
This chapter defines the controller layer of XForms, an XML Events-based [XML Events] common set of actions that can be invoked in response to events.
Note:
XForms itself defines no method for script-based event handling. The definition of such facilities is a responsibility of the hosting language.
All form controls as well as other elements defined in this specification have a set of common behaviors that encourage consistent authoring and look and feel for XForms-based applications. This consistency comes from attaching a common set of behaviors to the various form controls. In conjunction with the event binding mechanism provided by XML Events, these handlers provide a flexible means for forms authors to specify event processing at appropriate points within the XForms user interface. XForms Actions are declarative XML event handlers that capture high-level semantics. As a consequence, they significantly enhance the accessibility of XForms-based applications in comparison to previous Web technologies that relied exclusively on scripting.
The elements and attributes included in this module are:
| Element | Attributes | Minimal Content Model |
|---|---|---|
| action | Common, Events, Action Common | (Action)* |
| setvalue | Common, Events, Action Common, Single Node Binding, value (string XPath Expression) | PCDATA |
| insert | Common, Events, Action Common, Node Set Binding, context (node XPath Expresson), at (number XPath Expression), position ("before"|"after"), origin (nodeset XPath Expresson) | EMPTY |
| delete | Common, Events, Action Common, Node Set Binding, context (node XPath Expresson), at (number XPath Expression) | EMPTY |
| setindex | Common, Events, Action Common, repeat (xsd:IDREF), index (number XPath Expression) | EMPTY |
| toggle | Common, Events, Action Common, case (xsd:IDREF) | case? |
| setfocus | Common, Events, Action Common, control (xsd:IDREF) | control? |
| dispatch | Common, Events, Action Common, name (xsd:NMTOKEN), targetid (xsd:IDREF), delay (xsd:nonNegativeInteger), bubbles (xsd:boolean), cancelable (xsd:boolean) | name?, targetid?, delay? [in any order] |
| rebuild | Common, Events, Action Common, model (xsd:IDREF) | EMPTY |
| recalculate | Common, Events, Action Common, model (xsd:IDREF) | EMPTY |
| revalidate | Common, Events, Action Common, model (xsd:IDREF) | EMPTY |
| refresh | Common, Events, Action Common, model (xsd:IDREF) | EMPTY |
| reset | Common, Events, Action Common, model (xsd:IDREF) | EMPTY |
| load | Common, Events, Action Common, Single Node Binding (author-optional), resource (xsd:anyURI), show ("new" | "replace") | resource? |
| send | Common, Events, Action Common, submission (xsd:IDREF) | EMPTY |
| message | Common, Events, Action Common, Single Node Binding (author-optional), level ("ephemeral" | "modeless" | "modal"|QNameButNotNCName) | (PCDATA|UI Inline)* |
This module also defines the content set "Action", which includes the following elements:
(action|setvalue|insert|delete|setindex|toggle|setfocus|dispatch|rebuild|recalculate|revalidate|refresh|reset| load||send|message)*
The following group of attributes, here called Action Common, are available to all Action elements:
| Element | Attributes |
|---|---|
| Action | if (boolean XPath Expression), while (boolean XPath Expression) |
- if
Author-optional attribute defined in Section 10.17 Conditional Execution of XForms Actions.
- while
Author-optional attribute defined in Section 10.18 Iteration of XForms Actions.
Additionally, this module defines the attribute group "XML Events", which includes all of the "global" attributes defined in the [XML Events] specification.
The following example shows how events can be used:
Action Syntax
<xforms:trigger> <xforms:label>Reset</xforms:label> <xforms:reset ev:event="DOMActivate" model="thismodel"/> </xforms:trigger>
This example recreates the behavior of the HTML reset control, which this specification does not define as an independent form control.
For each built-in XForms Action, this chapter lists the following:
Name
Common Attributes
Special Attributes
Description of behavior
All elements defined in this chapter explicitly allow global attributes from the XML Events namespace, and apply the processing defined in that specification in section 2.3 [XML Events].
An outermost action handler is an action that is activated when the XForms processor is not executing any other action handlers.
An inner action handler is an action that is activated when the XForms processor is executing the declared actions of an outermost action handler. An inner action handler may be within the content of the outermost action handler, or it may be executed as the response to an event dispatched while performing all of the actions initiated by the outermost action handler.
Deferred Updates: Sequences of one or more XForms Actions have a deferred effect on XForms model and user interface processing. Implementations are free to use any strategy to accomplish deferred updates, but the end result must be as follows: Instance data changes performed by a set of actions do not result in immediate computation dependency rebuilding, recalculation, revalidate and form control refreshing until the termination of the outermost action handler, as described here. Each XForms model can be thought of as having a set of deferred update Boolean flags, initially false at the start of an outermost action handler, to indicate whether each of the actions rebuild, recalculate, revalidate, and refresh are required for that model upon termination of the outermost action handler.
By default, the behavior of an action handler is performed one time when the action is encountered in the execution sequence. However, execution of an action handler may be conditional or iterated, as described in 10.17 Conditional Execution of XForms Actions and 10.18 Iteration of XForms Actions.
Execution of an outermost action handler begins by setting the XForms processor into the state of executing an outermost action handler. The outermost action handler is then performed, which may include the execution of inner action handlers. Finally, the XForms processor is set into the state of not executing an outermost action handler and then the deferred update is performed for each model.
The deferred update behavior for a model consists of examining each deferred update Boolean flag in the order of rebuild, recalculate, revalidate, and refresh, and for each true flag, set the flag to false and then dispatch the proper event to the model for that deferred update flag (i.e. dispatch xforms-rebuild for a true rebuild flag, xforms-recalculate for a true recalculate flag, xforms-revalidate for a true revalidate flag, and xforms-refresh for a true refresh flag).
Note:
The XForms processor is not considered to be executing an outermost action handler at the time that it performs deferred update behavior for XForms models. Therefore, event handlers for events dispatched to the user interface during the deferred refresh behavior are considered to be new outermost action handler.
Actions that manipulate properties of the XForms view layer begin by invoking the deferred update behavior so that the model and all data are up to date prior to performing the action. The XForms Actions in this category are:
setfocustogglesetindex
Actions that directly invoke rebuild, recalculate, revalidate, or refresh always have an immediate effect, and clear the corresponding deferred update flag. The XForms Actions in this category are:
rebuildrecalculaterevalidaterefresh
Similarly, if the default processing of any of the events xforms-rebuild, xforms-recalculate, xforms-revalidate, or xforms-refresh are performed, then the corresponding deferred update flag is cleared. The XForms Actions that can dispatch these events are:
resetdispatch
XForms Actions that change the tree structure of instance data result in setting all four deferred update flags to true for the model over which they operate. The XForms Actions in this category are:
insertdelete
XForms Actions that change only the value of an instance node results in setting the deferred update flags for recalculate, revalidate, and refresh to true and making no change to the deferred update flag for rebuild for the model over which they operate. The XForms Actions in this category are:
setvalue
setindex
Finally, the XForms submission process can affect deferred update behavior. See Section 11.2 The xforms-submit Event for details. XForms actions that are capable of initiating an XForms submission are:
send
dispatch
10.1 The action Element
This action causes its child actions to be invoked in the order that they are specified in the document.
Common Attributes: Common, Events, Action Common
Grouping Actions
<trigger>
<label>Click me</label>
<action ev:event="DOMActivate">
<reset model="thismodel"/>
<setvalue ref="."/>
</action>
</trigger>10.2 The setvalue Element
This action explicitly sets the value of the specified instance data node.
This action has no effect if the Single Node Binding does not select an instance data node or if a readonly instance data node is selected.
An xforms-binding-exception occurs if the Single Node Binding indicates a node
whose content is not simpleContent (i.e., a node that has element children).
Common Attributes: Common, Events, Action Common, Single Node Binding
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate, with the result stored in the selected instance data node. The evaluation context for this XPath expression is the result from the Single Node Binding. To obtain the value, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
The element content of setvalue specifies the literal value to set; this is an alternative to specifying a computed value via attribute value. If neither a value attribute nor text content are present, the effect is to set the value of the selected node to the empty string (""). If both are present, the value attribute is used. The following examples contrast these approaches:
setvalue with Expression
<setvalue bind="put-here" value="a/b/c"/>
This causes the string value at a/b/c in the instance data to be placed on the single node selected by the bind element with id="put-here".
setvalue with Literal
<setvalue bind="put-here">literal string</setvalue>
This causes the value "literal string" to be placed on the single node selected by the bind element with id="put-here".
Note:
See Section 7.10.4 The context() Function for an example in which the context() function is used to
provide the same initial evaluation context node to both the ref and value attributes.
See Appendix B Patterns for Data Mutations for numerous further usage patterns for
sevalue, insert and delete.
All strings are inserted into the instance data as follows:
Element nodes: If element child nodes are present, then an
xforms-binding-exceptionoccurs. Otherwise, regardless of how many child nodes the element has, the result is that the string becomes the new content of the element. In accord with the data model of [XPath 1.0], the element will have either a single non-empty text node child, or no children string was empty.Attribute nodes: The string-value of the attribute is replaced with a string corresponding to the new value.
Text nodes: The text node is replaced with a new one corresponding to the new value, or the text node is eliminated if the new value is the empty string.
Namespace, processing instruction, and comment nodes: behavior is undefined (implementation-dependent).
the XPath root node: an
xforms-binding-exceptionoccurs.
Note:
This action affects deferred updates by setting the deferred update flags for recalculate, revalidate and refresh.
10.3 The insert Element
The insert action is used to create one or more nodes of instance data by cloning one or more existing
instance nodes. Attributes of the insert action specify the node or nodes to be cloned and the
location within instance data where the clones will appear. The clones are deep copies of the original nodes
except the contents of nodes of type xsd:ID are modified to remain as unique values in the
instance data after the clones are inserted.
Common Attributes: Common, Events, Action Common, Node Set Binding (author-optional)
Special Attributes:
- context
Author-optional attribute containing an XPath expression evaluated using the in-scope evaluation context. If the
modelattribute is present, then it is processed as described in 7.2 Evaluation Context before evaluating this attribute. The Node Set Binding is required unless this attribute is present. The result of the XPath expression is used to override the in-scope evaluation context. If the result is an empty nodeset or not a nodeset, then the insert action is terminated with no effect. Otherwise, the first node of the nodeset is used as the new in-scope evaluation context node, and the context position and size are set to 1. By adjusting the in-scope evaluation context, this attribute affects the subsequent evaluation of many other attributes that can appear oninsert, includingif,while,nodesetandorigin.- origin
Author-optional attribute containing an XPath expression evaluated using the in-scope evaluation context , which may have been amended by the
contextattribute. Theorigin node-setis the set of one or more nodes to be cloned by theinsertaction. If this attribute is present and resolves to a non-empty nodeset, then the result overrides the default setting of theorigin node-setas described below in the processing of theinsertaction.- at
Author-optional attribute containing an XPath expression evaluated using the Node Set Binding node-set to help determine the
insert location node. This attribute is ignored if the Node Set Binding is not specified or specifies an empty node-set. Theinsert location nodeis a node within the Node Set Binding node-set that is used to help determine where in the instance to insert each node cloned by theinsert. If this attribute is present, then its result is used to override the default setting of theinsert location nodeas described below in the processing of theinsertaction.- position
Author-optional selector that indicates where to put the cloned node or nodes relative to the
insert location node. Valid values arebeforeandafter, and the latter is the default. This attribute is ignored if the Node Set Binding node-set is not specified or empty. If the node at theinsert location nodewithin the Node Set Binding node-set is the document element of an instance, then this attribute is ignored.
Processing for the insert action is as follows:
The
insert contextis determined. If thecontextattribute is not given, theinsert contextis the in-scope evaluation context. Otherwise, the XPath expression provided by thecontextattribute is evaluated using the in-scope evaluation context, and the first node rule is applied to obtain theinsert context. Theinsertaction is terminated with no effect if theinsert contextis the empty node-set.The Node Set Binding node-set is determined. If a
bindattribute is present, it directly determines the Node Set Binding node-set. If anodesetattribute is present, it is evaluated within theinsert contextto determine the Node Set Binding node-set. If the Node Set Binding attributes are not present, then the Node Set Binding node-set is the empty node-set. Theinsertaction is terminated with no effect if any of the following conditions is true:The
contextattribute is not given and the Node Set Binding node-set is the empty node-set.The
contextattribute is given, theinsert contextdoes not evaluate to an element node and the Node Set Binding node-set is the empty node-set.
The
origin node-setis determined. If theoriginattribute is not given and the Node Set Binding node-set is empty, then theorigin node-setis the empty node-set. Otherwise, if theoriginattribute is not given, then theorigin node-setconsists of the last node of the Node Set Binding node-set. If theoriginattribute is given, theorigin node-setis the result of the evaluation of theoriginattribute in theinsert context. Namespace nodes and root nodes (parents of document elements) are removed from theorigin node-set. Theinsertaction is terminated with no effect if theorigin node-setis the empty node-set.The
insert location nodeis determined. If the Node Set Binding node-set is not specified or empty, theinsert location nodeis theinsert contextnode. Otherwise, if theatattribute is not given, then theinsert location nodeis the last node of the Node Set Binding node-set. Otherwise, aninsert location nodeis determined from theatattribute as follows:The evaluation context node is the first node in document order from the Node Set Binding node-set, the context size is the size of the Node Set Binding node-set, and the context position is
1.The return value is processed according to the rules of the XPath function
round(). For example, the literal1.5becomes2, and the literal'string'becomesNaN.If the result is in the range 1 to the Node Set Binding node-set size, then the
insert locationis equal to the result. If the result is non-positive, then theinsert locationis1. Otherwise, the result isNaNor exceeds the Node Set Binding node-set size, so theinsert locationis the Node Set Binding node-set size.The
insert location nodeis the node in the Node Set Binding node-set at the position given by theinsert location.
The
insertaction is terminated with no effect if the insertion will create nodes whose parent is readonly. This occurs if theinsert location nodeis readonly and the Node Set Binding node-set is not specified or empty, or otherwise if the parent of theinsert location nodeis readonly.Each node in the
origin node-setis cloned in the order it appears in theorigin node-set.The
target locationof each of the cloned nodes is determined as follows:If the Node Set Binding node-set is not specified or empty, then the
insert location nodeprovided by thecontextattribute is intended to be the parent of the cloned node. Thetarget locationis dependent on the types of the cloned node and theinsert location nodeas follows:If the
insert location nodeis not an element node or root node, then it cannot be the parent of the cloned node, so thetarget locationis undefined.If the
insert location nodeis the root node of an instance (which is the parent of the root element), and the cloned node is an element, then thetarget locationis the root element of the instance.If the
insert location nodeis the root node of an instance (which is the parent of the root element), and the cloned node is not an element, then thetarget locationis before the first child of theinsert location node.If the
insert location nodeis an element, and the cloned node is an attribute, then thetarget locationis the attribute list of theinsert location node.If the
insert location nodeis an element, and the cloned node is not an attribute, then thetarget locationis before the first child of theinsert location node, or the child list of theinsert location nodeif it is empty.
Otherwise, the Node Set Binding node-set is specified and non-empty, so the
insert location nodeprovided by the Node Set Binding and author-optionalatattribute is intended to be the sibling of the cloned node. If theinsert location nodeis an attribute or root node, then thetarget locationis undefined. If theinsert location nodeis not an attribute or root node, then thetarget locationis immediately before or after theinsert location node, based on thepositionattribute setting or its default.
The cloned node or nodes are inserted in the order they were cloned into their
target locationsdepending on their node type. If the parent node of the target location is the instance root node (which is the parent of the root document element of the instance), and if the cloned node is an element, then the instance root element is deleted before the cloned node is inserted at the target location. If the cloned node is a duplicate of another attribute in its parent element, then either the duplicate attribute is first removed or the existing attribute value is updated. If a cloned node cannot be placed at thetarget locationdue to a node type conflict or because thetarget locationis undefined, then the insertion for that particular cloned node is ignored. Each cloned node that is inserted is added to theinserted-nodeslist that will be provided in thexforms-insertevent context information. For each cloned node used to update an existing attribute node, the existing attribute node is added to the list ofinserted-nodes.Note:
A node type conflict is a mismatch between the XPath node type and the
target location. For example, an attribute cannot be inserted as a sibling before or after an element.If the list of
inserted-nodesis empty, then theinsertaction is terminated with no effect.The XForms action system's deferred update flags for rebuild, recalculate, revalidate and refresh are set.
The
insertaction is successfully completed by dispatching thexforms-insertevent with appropriate context information.Note:
A
repeatupdates its index in response to this event if its repeat collection changes size as a result of the insertion. See Section 9.3.3 Repeat Processing for details.
Note:
This action affects deferred updates by setting the deferred update flags for rebuild, recalculate, revalidate and refresh.
Examples:
Inserting into a repeat, whether or not it is empty
When the repeat is empty, the at index is zero so a new item is prepended to the child elements of purchaseOrder.
When the repeat is non-empty, the new item is added after the node currently indexed by repeat R.
...
<xforms:instance>
<purchaseOrder xmlns="">
<subtotal/>
<tax/>
<total/>
</purchaseOrder>
</xforms:instance>
<xforms:instance id="prototypes">
<prototypes xmlns="">
...
<item>
<product/>
<quantity/>
<unitcost/>
<price/>
</item>
...
</prototypes>
</xforms:instance>
...
<repeat nodeset="/purchaseOrder/item" id="R">
...
</repeat>
...
<xforms:trigger>
<xforms:label>Add to purchase order</xforms:label>
<xforms:action ev:event="DOMActivate>
<xforms:insert context="/purchaseOrder" nodeset="item" at="index('R')" origin="instance('prototypes')/item"/>
<xforms:setfocus control="R"/>
</xforms:action>
</xforms:trigger>
Insert and Read-Only Content
<model xmlns:my="http://example.org">
<instance>
<my:data>
<my:name>
<my:first-name>John</my:first-name>
<my:last-name>Doe</my:last-name>
</my:name>
<my:address>
<my:street>123 Main St.</my:street>
<my:city>Smallville</my:city>
</my:address>
</my:data>
</instance>
<bind nodeset="/my:data/my:name/" readonly="true()"/>
<bind nodeset="/my:data/my:address/my:street" readonly="true()"/>
<action ev:event="xforms-model-construct-done">
<insert id="I1" nodeset="my:name/*" ... />
<insert id="I2" nodeset="my:address/my:street" at="1" >
</action>
</model>
Insert I1 fails because it attempts to insert into the content of a readonly node (my:name).
Insert I2 succeeds even though the insert location is a readonly node because the new node is placed as a sibling into the content of the parent, which is not readonly.
See 10.4 The delete Element for an example that uses insert and delete to make a repeat that always shows at least one repeat item. See Appendix B Patterns for Data Mutations for numerous further usage patterns for sevalue, insert and delete.
10.4 The delete Element
This action deletes one or more nodes from instance data.
Common Attributes: Common, Events, Action Common, Node Set Binding
Special Attributes:
- context
Author-optional attribute containing an XPath expression evaluated using the in-scope evaluation context. If the
modelattribute is present, then it is processed as described in 7.2 Evaluation Context before evaluating this attribute. The Node Set Binding is required unless this attribute is present. The result of the XPath expression is used to override the in-scope evaluation context. If the result is an empty nodeset or not a nodeset, then thedeleteaction is terminated with no effect. Otherwise, the first node of the nodeset is used as the new in-scope evaluation context node, and the context position and size are set to 1. By adjusting the in-scope evaluation context, this attribute affects the evaluation of subsequent attributes that may appear ondelete, includingif,while, andnodeset.- at
Author-optional attribute containing an XPath expression evaluated using the Node Set Binding node-set to determine the
delete location. If the Node Set Binding node-set is empty, then this attribute is ignored.
Processing for the delete action is as follows:
The
delete contextis determined. It is set to the in-scope evaluation context, possibly overridden by thecontextattribute if that attribute is present. Thedeleteaction is terminated with no effect if thedelete contextis the empty node-set.The Node Set Binding node-set is determined. If a
bindattribute is present, it directly determines the Node Set Binding node-set. If anodesetattribute is present, it is evaluated within thedelete contextto determine the Node Set Binding node-set. The behavior of thedeleteaction is undefined if the Node Set Binding node-set contains nodes from more than oneinstance. Thedeleteaction is terminated with no effect if the Node Set Binding is expressed and the Node Set Binding node-set is the empty node-set. Otherwise, the Node Set Binding is not expressed, so the Node Set Binding node-set is set equal to the delete context node with a position and size of 1.The
delete locationis determined. If theatattribute is not specified, there is nodelete location. Otherwise, thedelete locationis determined by evaluating the XPath expression specified by theatattribute as follows:The evaluation context node is the first node in document order from the Node Set Binding node-set, the context size is the size of the Node Set Binding node-set, and the context position is
1.The return value is processed according to the rules of the XPath function
round(). For example, the literal1.5becomes2, and the literal'string'becomesNaN.If the result is in the range 1 to the Node Set Binding node-set size, then the
delete locationis equal to the result. If the result is non-positive, then thedelete locationis1. Otherwise, if the result isNaNor exceeds the Node Set Binding node-set size, thedelete locationis the Node Set Binding node-set size.
If there is no
delete location, each node in the Node Set Binding node-set is deleted, except if the node is a readonly node, a namespace node, a root node, or the root document element of an instance, then that particular node is not deleted. Otherwise, if there is adelete location, the node at thedelete locationin the Node Set Binding node-set is deleted, except if the node is the root document element of an instance or has a readonly parent node, then that node is not deleted. The delete action is terminated with no effect if no node is deleted.The XForms action system's deferred update flags for rebuild, recalculate, revalidate and refresh are set.
The
deleteaction is successfully completed by dispatching thexforms-deleteevent with appropriate context information.
Note:
This action affects deferred updates by setting the deferred update flags for rebuild, recalculate, revalidate and refresh.
Examples:
Using delete and insert to Maintain a Non-empty repeat repeat
In this example, the trigger is not in the repeat. When it is activated, the indexed item in the repeat is first deleted.
Next, if that was the last item, then a new prototypical item is inserted so that the repeat does not become empty.
The focus is then sent back to the repeat from the trigger.
...
<xforms:trigger>
<xforms:label>Delete from purchase order</xforms:label>
<xforms:action ev:event="DOMActivate">
<xforms:delete context="/purchaseOrder" nodeset="item" at="index('R')"/>
<xforms:insert context="/purchaseOrder" if="not(item)"
nodeset="item" origin="instance('prototypes')/item"/>
<xforms:setfocus control="R"/>
</xforms:action>
</xforms:trigger>
Note:
The form author could have written nodeset="/purchaseOrder/item" in
the delete action, but the context attribute was added for consistency
with the insert action.
Delete and Read-Only Content
<model xmlns:my="http://example.org">
<instance>
<my:data>
<my:name>
<my:first-name>John</my:first-name>
<my:last-name>Doe</my:last-name>
</my:name>
<my:address>
<my:street>123 Main St.</my:street>
<my:city>Smallville</my:city>
</my:address>
</my:data>
</instance>
<bind nodeset="/my:data/my:name/" readonly="true()"/>
<bind nodeset="/my:data/my:address/my:street" readonly="true()"/>
<action ev:event="xforms-model-construct-done">
<delete id="D1" nodeset="my:name/*" ... />
<delete id="D2" nodeset="my:address/my:street" at="1" >
<delete id="D3" nodeset="my:address" at="1" >
</action>
</model>
Delete D1 fails because it attempts to delete from the content of a readonly node (my:name).
Delete D2 succeeds even though the node to delete is readonly because the node is not being changed, but rather removed from the content of the parent, which is not readonly.
Delete D3 succeeds even though it contains a readonly node because a node can be deleted if its parent is not readonly, and node deletion includes deletion of its attributes and content, regardless of whether or not the attributes or content nodes are readonly.
See Appendix B Patterns for Data Mutations for numerous further usage patterns for sevalue, insert and delete.
10.5 The setindex Element
This XForms Action begins by invoking the deferred update behavior. This action then marks a specific item as current in a repeating sequence (within 9.3.1 The repeat Element).
Common Attributes: Common, Events, Action Common
Special Attributes:
- repeat
Required reference to a repeating element.
- index
Required XPath expression that evaluates to a 1-based offset into the sequence. The evaluation context is determined in the same manner as the evaluation context for a Single-Node Binding (see 7.2 Evaluation Context).
If the selected index is 0 or less, an xforms-scroll-first event is dispatched and the index is set to 1. If the selected index is greater than the index of the last repeat item, an xforms-scroll-last event is dispatched and the index is set to that of the last item. If the index evaluates to NaN the action has no effect.
Note:
The IDREF from the repeat attribute may not uniquely identify the desired repeat
if the repeat element bearing the matching ID resides within the content of another repeat.
The general method described in 4.7 Resolving ID References in XForms is used to determine the desired run-time repeat object.
Note:
This action affects deferred updates by performing deferred update in its initialization and by setting the deferred update flags for recalculate, revalidate and refresh.
10.6 The toggle Element
This XForms Action begins by invoking the deferred update behavior.
This action then selects one possible case from an exclusive list of alternatives in a switch.
This action performs the following:
Dispatches an
xforms-deselectevent to the currently selectedcasein theswitchcontaining the identifiedcase.Adjusts the
selectedstates (not the attribute values) on the affected cases to reflect the new state of theswitchcontaining the identifiedcase.Dispatches an
xform-selectevent to thecasejust selected.
Common Attributes: Common, Events, Action Common
Special Attributes:
- case
Author-optional reference to a
caseelement. The case to select is specified by this attribute or by the child element case.
The case to be selected by the switch is identified by IDREF either by the attribute case or by a child case element. If no case element contains the given identifier, then this action has no effect.
Note:
Whether the IDREF is obtained from the case attribute or element, the IDREF may not uniquely identify
the desired case if the case element bearing the matching ID resides
in a repeating construct such as element repeat.
The general method described in 4.7 Resolving ID References in XForms is used to determine the desired run-time case object.
Note:
This action affects deferred updates by performing deferred update in its initialization.
10.6.1 The case Element Child of the toggle Element
This section defines a child element of toggle named case that is an alternate means of providing the identity of a
case element to select with a switch.
Element: case
Common attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the case identity, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
Content: PCDATA
The case to be selected by the toggle action is given by the
case attribute or the case element.
If both are given, the element takes precedence. Due to the addition of the element, the case attribute is no longer required,
but either the case attribute or the case element must appear.
The case element can provide the identity of a case with either its string content
or the value attribute. If both are given, then the value attribute takes precedence.
<toggle>
<case value="concat('case_', ../addressBlockType)"/>
</toggle>10.7 The setfocus Element
This XForms Action begins by invoking the deferred update behavior.
This action then dispatches an xforms-focus event (4.3.7 The xforms-focus Event) to the element
identified by attribute control or child element control.
Common Attributes: Common, Events, Action Common
Special Attributes:
- control
Author-optional reference to a form control. The form control is specified by this attribute or by the child element control.
The identity of the element to which the setfocus action dispatches xforms-focus is given by
the control attribute or the control element.
If no such element contains the given identifier, then this action has no effect.
Note:
Whether the IDREF is obtained from the control attribute or element, the IDREF may not uniquely identify
the desired form control if the element bearing the matching ID resides in a repeating construct such as element repeat.
The general method described in 4.7 Resolving ID References in XForms is used to determine the desired form control.
Note:
Changing the focus to a form control within a repeat object may cause one or more repeat index values to be changed as described in Section 9.3.4 User Interface Interaction.
10.7.1 The control Element Child of the setfocus Element
This section defines a child element of setfocus named control that is an alternate means of providing the
element that receives the xforms-focus event.
Element: control
Common attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the desired element identifier, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
Content: PCDATA
The identity of the element to which the setfocus action dispatches xforms-focus is given by
the control attribute or the control element.
If both are given, the element takes precedence. Due to the addition of the element, the control attribute is no longer required,
but either the control attribute or the control element must appear.
The control element can provide the desired element identifier with either its string content or the value attribute.
If both are given, then the value attribute takes precedence.
<setfocus>
<control value="concat('input_', ../paymentType)"/>
</setfocus>10.8 The dispatch Element
This action dispatches an XML Event to a specific target element. Two kinds of event can be dispatched:
Predefined XForms events (i.e., xforms-event-name), in which case the
bubblesandcancelableattributes are ignored and the standard semantics as defined in 4 Processing Model apply.An event created by the XForms author with no predefined XForms semantics and as such not handled by default by the XForms Processor.
Common Attributes: Common, Events, Action Common
Special Attributes:
- name
Author-optional attribute for specifying the name of the event to dispatch.
- targetid
Author-optional attribute for specifying the reference to the event target.
- delay
Author-optional attribute that indicates the minimum number of milliseconds to delay dispatching of the event to the target. The default is the empty string, which indicates no delay.
- bubbles
Author-optional attribute containing a boolean indicating if this event bubbles—as defined in [DOM2 Events]. The default value is
truefor a custom event. For predefined events, this attribute has no effect.- cancelable
Author-optional attribute containing a boolean indicating if this event is cancelable—as defined in [DOM2 Events]. The default value is
truefor a custom event. For predefined events, this attribute has no effect.
The event to be dispatched is given by the name attribute or the name child element.
Due to the addition of the name element, the name attribute is not required, but either the name attribute or the name element must appear.
If the event name is not specified or empty string, then this action has no effect.
The element to which the event is to be dispatched is identified by the targetid attribute or the
targetid chlid element. Due to the addition of the
targetid element, the targetid attribute is not required,
but this action has no effect unless the target identifier is specified by the element or attribute.
For backwards compatibility with documents created for earlier versions of the specification, the processor of the
dispatch element may allow the attribute named target and the child element
target to be used. The attribute and element named target provide exactly the same behaviors as the
targetid attribute and element, except that the target attribute and element are ignored if the
dispatch element also bears a targetid attribute or contains a targetid child element.
Note:
Whether the IDREF is obtained from the targetid attribute or targetid element,
the IDREF may not uniquely identify the desired target object if the element bearing the matching ID resides in a repeating construct
such as element repeat. The general method described in 4.7 Resolving ID References in XForms is used to determine the desired target object.
The event may be dispatched immediately or after a specified non-negative number of milliseconds of delay. The event delay is specified
the delay attribute or by the child element delay.
If the delay is not specified or if the given value does not conform to xsd:nonNegativeInteger, then the event is dispatched
immediately as the result of the dispatch action.
Otherwise, the specified event is added to the delayed event queue
unless an event with the same name and target element already exists on the delayed event queue. The dispatch
action has no effect if the event delay is a non-negative integer and the specified event is already in the delayed event queue.
Note:
Since an element bearing a particular ID may be repeated, the delayed event queue may contain more than one event with the same name and target IDREF. It is the name and the target run-time element that must be unique.
If a run-time element is destroyed, then any delayed events targeted at that element are removed from the delayed event queue.
A run-time element may be destroyed for a number of reasons, including shutdown of the form or removal of form controls
associated by a repeat with an instance data node that is destroyed.
As soon as possible after the specified delay in milliseconds has elapsed, the event is removed from the delayed event queue and then dispatched. In the same manner used to handle user-generated events or the completion of an asynchronous submission, the dispatch and processing of delayed events is done without interrupting the processing of another event and its event handlers.
Note:
Because the delayed event is first removed from the delayed event queue and then dispatched, a handler for a given
event may dispatch the event again with a delay. This can be used to perform simple polling and asynchronous looping
operations. Moreover, the if attribute can be applied to the dispatch action to decide when to
discontinue the polling or looping based on a setting in instance data.
10.8.1 The name Child Element
This section defines a new child element of dispatch that provides an alternate
means of specifying the name of the event to dispatch.
Element: name
Common attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the event name, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
Content: PCDATA
The event name of the dispatch action is given by the name attribute or the name element.
If both are given, the element takes precedence.
The name element can provide the event name with either its string content or the value attribute.
If both are given, then the value attribute takes precedence.
10.8.2 The targetid Child Element
This section defines a new child element of dispatch that provides an alternate means of specifying the
target of the event to be dispatched.
Element: targetid
Common attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the event target, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
Content: PCDATA
The event target of the dispatch action is given by the targetid attribute or the
targetid element.
If both are given, the element takes precedence.
The targetid element can provide an IDREF for the event target with either its string content or
the value attribute. If both are given, then the value attribute takes precedence.
10.8.3 The delay Child Element
This section defines a new child element of dispatch that provides an alternate means of specifying the
delay imposed on the event to be dispatched.
Element: delay
Common attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the event delay, the result of the expression is processed as if by call to the XPath
stringfunction. If the result does not conform lexically toxsd:nonNegativeInteger, then the result of empty string is used. An empty string is used if the XPath evaluation fails.
Content: PCDATA
The event delay of the dispatch action is given by the delay attribute or the delay element.
If both are given, the element takes precedence. The delay element can provide the delay with either its string content or the value attribute.
If both are given, then the value attribute takes precedence.
10.9 The rebuild Element
This action causes the default processing of xforms-rebuild to happen, bypassing the normal event flow (i.e. the behavior occurs without dispatching the xforms-rebuild event). This action results in the XForms Processor rebuilding any internal data structures used to track computational dependencies among instance data nodes —see 4.3.1 The xforms-rebuild Event.
Common Attributes: Common, Events, Action Common
Special Attributes:
- model
Author-optional XForms Model selector, as defined in 3.2.3 Single-Node Binding Attributes. If this attribute is omitted, then the default is the
modelassociated with the in-scope evaluation context node.
10.10 The recalculate Element
This action causes the default processing of xforms-recalculate to happen, bypassing the normal event flow (i.e. the behavior occurs without dispatching the xforms-recalculate event). As a result, instance data nodes whose values need to be recalculated are updated as specified in the processing model—see 4.3.2 The xforms-recalculate Event.
Common Attributes: Common, Events, Action Common
Special Attributes:
- model
Author-optional XForms Model selector, as defined in 3.2.3 Single-Node Binding Attributes. If this attribute is omitted, then the default is the
modelassociated with the in-scope evaluation context node.
10.11 The revalidate Element
This action causes the default processing of xforms-revalidate to happen, bypassing the normal event flow (i.e. the behavior occurs without dispatching the xforms-revalidate event). This results in the instance data being revalidated as specified by the processing model—see 4.3.3 The xforms-revalidate Event.
Common Attributes: Common, Events, Action Common
Special Attributes:
- model
Author-optional XForms Model selector, as defined in 3.2.3 Single-Node Binding Attributes. If this attribute is omitted, then the default is the
modelassociated with the in-scope evaluation context node.
10.12 The refresh Element
This action causes the default processing of xforms-refresh to happen, bypassing the normal event flow (i.e. the behavior occurs without dispatching the xforms-refresh event). This action results in the XForms user interface being refreshed, and the presentation of user interface controls being updated to reflect the state of the underlying instance data—see 4.3.4 The xforms-refresh Event.
Common Attributes: Common, Events, Action Common
Special Attributes:
- model
Author-optional XForms Model selector, as defined in 3.2.3 Single-Node Binding Attributes. If this attribute is omitted, then the default is the
modelassociated with the in-scope evaluation context node.
10.13 The reset Element
This action initiates reset processing by dispatching an xforms-reset event to the specified model. Processing of event xforms-reset is defined in the processing model—see 4.3.5 The xforms-reset Event.
Common Attributes: Common, Events, Action Common
Special Attributes:
- model
Author-optional XForms Model selector, as defined in 3.2.3 Single-Node Binding Attributes. If this attribute is omitted, then the default is the
modelassociated with the in-scope evaluation context node.
10.14 The load Element
This action traverses the specified link.
Common Attributes: Common, Events, Action Common, Single-Node Binding (author-optional)
Special Attributes:
- resource
Author-optional attribute. Link to an external resource to load.
- show
Author-optional link behavior specifier. The allowed values are "replace" and "new". If this attribute is missing, a default value of "replace" is assumed.
The URI specifying the link to traverse may be pointed to by the Single Node Binding attributes, if given, or by the
resource attribute or the name child element.
Individually, the Single Node Binding, resource element and resource attribute are not required.
If none are given, the action has no effect. If the Single Node Binding is present and does not select an instance
data node, then this action has no effect. If the Single Node Binding is given in addition to one of the
resource attribute or resource element, then the action has no effect.
The URI obtained in this manner is treated as a link to an external resource, defined as an [XLink 1.0] link between
the load element and the remote resource indicated. No XLink actuate value is defined, since control of actuation is
defined by XML Events. The XLink show value depends on the show attribute.
The link indidicated by the URI obtained above is traversed.
If the link traversal fails, then an implementation-specific means of conveying the link
traversal failure occurs.
Otherwise, processing for the document (or portion of the document) reached by traversing the link is specified by the show attribute.
The following are the possible values for the show attribute and the corresponding processing behaviors:
- new
The document is loaded into a new presentation context, e.g., a new window. Form processing in the original window continues.
- replace
The document is loaded into the current window. Form processing is interrupted, exactly as if the user had manually requested navigating to a new document.
10.14.1 The resource Element child of load
When it appears as the first child element of load, the resource element provides the URI of the link,
overriding the resource attribute. As stated above, the load action has no effect if
both a resource and a Single Node Binding are given.
This element allows the URI used by the load to be dynamically calculated based on instance data.
Common Attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the URI, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
Content: PCDATA
The URI to be used by the load can be specified with either the value attribute or
the string content of the resource element. If both are specified, then the value attribute takes precedence.
If the load does not have a resource element as its first child, then the URI is obtained from
the resource attribute or the Single Node Binding, if given.
10.15 The send Element
This action initiates submit processing by dispatching an xforms-submit event. Processing of event xforms-submit is defined in the processing model—see 4.3.9 The xforms-submit Event.
Common Attributes: Common, Events, Action Common
Special Attributes:
- submission
Author-optional attribute containing a reference to a
submissionelement. If this attribute is given but does not identify asubmissionelement, then thesendaction has no effect. If this attribute is omitted, then the firstsubmissionin document order from themodelassociated with the in-scope evaluation context is used.
10.16 The message Element
This action encapsulates a message to be displayed to the to the user.
Common Attributes: Common, Events, Action Common, Single Node Binding (author-optional)
Special Attributes:
- level
Author-optional attribute containing a message level identifier, one of ("ephemeral"|"modeless"|"modal"|QNameButNotNCName). The default is "modal" if the attribute is not specified. This specification does not define behavior for QNameButNotNCName values.
The message specified can exist in instance data or as inline text. If more than one source of message is specified in this element, the order of precedence is: single node binding attributes, inline text.
The user interface for the message action is considered to be created at the time the action occurs. If the message is obtained from the inline content of the message action, then the output of any output controls in the message content is determined based on the instance data available when the message action occurs. For example, the following example displays the message Hello, world! as the form starts up:
<model>
<instance>
<data xmlns="">
<name>John</name>
</data>
</instance>
<action ev:event="xforms-ready">
<setvalue ref="name">world</setvalue>
<message level="modal">Hello, <output ref="name"/>!</message>
...</action>
</model>In this example, the message includes the latest user input even though other form controls not in the message action are not guaranteed to be updated until the end of the xforms-refresh event processing:
<input ref="birthday">
<label>Enter birthday:</label>
<message ev:event="xforms-invalid"><output ref="."/> isn't a valid birthday</message>
</input>
Note:
Due to deferred update behavior, if a message action is preceded in an action sequence by other actions that change instance nodes, and the message references nodes that are computationally dependent on the changed nodes, then the form author should invoke the recalculate action before the message action. Moreover, if the computational dependencies involved nodes that were inserted or deleted, then the form author should invoke rebuild prior to the recalculate.
A graphical browser might render a modal message as follows:
<model> <message level="modal" ev:event="xforms-ready">This is not a drill!</message> ... </model>

A modeless message is the foundation for displaying a help message, which a graphical browser might render as follows:
<secret ref="/login/password">
<label>Password</label>
<help>Have you forgotten your password? Simply call 1-900-555-1212 and have
a major credit card handy.</help>
</secret> 
An ephemeral message is the foundation for displaying a hint message, which a graphical browser might render as follows:
<input ref="po/address/street1"> <label>Street</label> <hint>Please enter the number and street name</hint> </input>

10.17 Conditional Execution of XForms Actions
The if attribute can be added to any XForms action. It contains an [XPath 1.0] expression
that is evaluated using the in-scope evaluation context before the action is executed. The result of the expression is
converted to a boolean as if converted with the boolean() function defined by the
[XPath 1.0] specification.
If the converted result of the expression evaluates to false, then the action is not performed. If the
converted result is true, then the action is performed.
If this attribute is applied to an XForms action element and the converted result of evaluation is
false, then all of the actions within the action element are omitted from the execution
of the XForms action sequence that invoked the action element. If the result is true,
then the contained actions are performed according to the normal processing rules such as deferred update behavior
and applicability of conditional and iterative attributes.
Note:
In actions insert and delete, the attribute context is evaluated before the if attribute.
Automatic Focus Advancement
The setfocus action in each input control is executed only if the node bound to the control
is a number of a particular length. The exacting form author could perform further validity tests.
... <input ref="areaCode" id="AreaCodeControl" incremental="true"> <label>Area Code</label> <setfocus ev:event="xforms-value-changed" control="ExchangeControl" if="string-length(.)=3 and . > 0"/> </input> <input ref="exchange" id="ExchangeControl" incremental="true"> <label>Exchange</label> <setfocus ev:event="xforms-value-changed" control="LocalControl" if="string-length(.)=3 and . > 0"/> </input> <input ref="local" id="LocalControl" incremental="true"> <label>Local</label> <setfocus ev:event="xforms-value-changed" control="ExtensionControl" if="string-length(.)=4 and . > 0"/> </input> ...
Handling Focus for Empty Repeats
The trigger that performs a delete conditionally sets the focus to a control outside of the repeat if
the repeat becomes empty due to the deletion. The setfocus is called first because the
delete removes the context node.
...
<trigger id="InsertControl">
<label>Insert Row</label>
<action ev:event="DOMActivate">
<insert context="purchaseOrder/lines" nodeset="line"
at="index('PurchaseOrderRepeat')" origin="instance('prototype')"/>
<setfocus control="PurchaseOrderRepeat"/>
</action>
</trigger>
<repeat nodeset="purchaseOrder/lines/line" id="PurchaseOrderRepeat">
...
<trigger>
<label>Delete Row</label>
<action ev:event="DOMActivate">
<setfocus control="InsertControl" if="last()=1"/>
<delete nodeset="../line" at="index('PurchaseOrderRepeat')"/>
</action>
</trigger>
...
</repeat>
10.18 Iteration of XForms Actions
The while attribute can be added to any XForms action. It contains an [XPath 1.0] expression
that is evaluated using the in-scope evaluation context before the action is executed. The result of the expression is
converted to a boolean as if converted with the boolean() function defined by the
[XPath 1.0] specification.
If the converted result of the expression is true, then the XForms action is performed and then the
expression is re-evaluated. The XForms action is executed repeatedly until the converted result of the expression
evaluates to false.
If this attribute is applied to an XForms action element, then the sequence of XForms actions in its content are
executed repeatedly once for each time the immediately preceding evaluation of the expression yields a result of true.
When XForms actions are iteratively executed, they are still subject to the normal action processing rules such as deferred update and applicability of conditional and iterative attributes.
An XForms action may be executed zero times due to this attribute. Furthermore, if an action bears this attribute and the
if attribute, then the expressions of both attributes must evaluate to true before each iterative
execution of the action.
Note:
In actions insert and delete, the attribute context is evaluated before the while attribute.
Therefore, context is re-evaluated before each iteration of the actions controlled by the while attribute.
Summing Selected Results
Counter and accumlator variables are created in instance data to sum a selection of values chosen by the user
<trigger>
<label>Get Sum</label>
<action ev:event="DOMActivate">
<setvalue ref="instance('temps')/counter" value="1"/>
<setvalue ref="instance('temps')/accumulator" value="0"/>
<action while="instance('temps')/counter <= count(/some/nodes)">
<setvalue ref="instance('temps')/accumulator"
value=". + instance('default')/some/nodes[number(instance('temps')/counter)]"
if="boolean-from-string(/some/nodes[number(instance('temps')/counter)]/@selected)"/>
<setvalue ref="instance('temps')/counter" value=". + 1"/>
</action>
</action>
</trigger>
11 The XForms Submission Module
XForms is designed to gather instance data, serialize it into an external representation, and submit it with a protocol. XForms defines a set of options for serialization and submission. The following sections define the processing of instance data for submission, and the behavior for the serialization and submission options.
11.1 The submission Element
The submission element represents declarative instructions on what to submit, and how.
| Element | Overview of Attributes | Overview of Content Model |
|---|---|---|
| submission |
| (resource | method | header)*, Action* |
Below is a more detailed decription of each attribute whose name and datatype information appears above.
Common Attributes: Common
Special Attributes:
- resource
Attribute indicating the destination URI for submitting instance data. This attribute is not author-optional unless the destination URI is provided by the
resourceelement, which can dynamically specify the URI based on instance data, or theactionattribute. This attribute should be used in place of theactionattribute. Behavior of relative URIs in links is determined by the host language, although [XML Base] processing is strongly recommended.- action
Deprecated author-optional attribute indicating the destination URI for submitting instance data. Behavior of relative URIs in links is determined by the host language, although [XML Base] processing is strongly recommended. Due to the addition of the
resourceattribute, this attribute is deprecated and optional. However, the destination URI must be specified by this attribute or by either theresourceattribute or theresourceelement.- ref
Author-optional selector binding expression enabling submission of a portion of the instance data. The selected node, and all descendants, are selected for submission. The default value is "/".
- bind
Author-optional reference to a
bindelement. When present, the binding reference on this attribute is used in preference to any binding reference from therefattribute.- mode
Author-optional attribute defaulting to "asynchronous" and with legal values of "synchronous" and "asynchronous". This attribute controls whether or not the submission response processing is performed as part of the default processing of event
xforms-submit. An asynchronous submission can complete default processing for this event before the submission response is received; in this case, submission response is processed once it is completely received asynchronously. For a "synchronous" submission, the submission response is received and processed during the default processing of eventxforms-submit.- method
Author-optional attribute specifying the protocol operation to be used to transmit the serialized instance data. There is no default value because either the attribute
methodor the elementmethodmust be specified. See Section 11.9 Submission Options for information on how this attribute affects the default serialization of instance data and the HTTP method [RFC 2616].- validate
Author-optional boolean attribute that indicates whether or not the data validation checks of the submission are performed. The default value is "false" if the value of
serializationis "none" and "true" otherwise.- relevant
Author-optional boolean attribute that indicates whether or not the relevance pruning of the submission is performed. The default value is "false" if the value of
serializationis "none" and "true" otherwise.- serialization
Author-optional attribute that controls how and whether to serialize instance data as part of the submission. The default value of this attribute is based on the submission
methodas described in Section 11.9 Submission Options. If the attribute value is "none", then instance data is not serialized as part of the submission. This can be useful for requests that either require no data or that have the data already gathered in the URI.Note:
Setting
serializationto "none" will also have the default effect of preventing relevance pruning and validation. However, the author is free to override this by settingrelevantand/orvalidateattributes to "true".- version
Author-optional attribute specifying the
versionof XML to be serialized. The default is "1.0".- indent
Author-optional attribute specifying whether the serializer should add extra white space nodes for readability. The default is "false".
- mediatype
Author-optional attribute specifying the mediatype for XML serialization of instance data. Authors should ensure that the type specified is compatible with the data being submitted, such as
application/xmlfor posted XML data. The default is "application/xml".Note:
This attribute does not affect serialization and cannot be used to override the
serializationattribute. It is only used to provide additional information about the submission data serialization when the serialization isapplication/xml. For example, this attribute could be used to indicate that the content type of the XML serialization istext/xml.- encoding
Author-optional attribute specifying an encoding for serialization. The default is "UTF-8".
- omit-xml-declaration
Author-optional attribute specifying whether to omit the XML declaration on the serialized instance data. The default value is "false".
- standalone
Author-optional attribute specifying whether to include a standalone declaration in the serialized XML.If the
omit-xml-declarationattribute has the valuetrue, then this attribute is ignored. Otherwise, if this attribute is omitted, then the XML declaration does not include a standalone document declaration, and if this attribute is specified, then the XML declaration includes a standalone document declaration with the same value as this attribute.- cdata-section-elements
Author-optional attribute specifying element names to be serialized with CDATA sections. The default is empty string.
- replace
Author-optional attribute specifying how the information returned after submit should be applied. In the absence of this attribute, "all" is assumed. The legal values are "all", "instance", "text" and "none".
- instance
Author-optional attribute specifying the instance to replace when the
replaceattribute value is "instance". When the attribute is absent, then the default is the instance that contains the submission data. An xforms-binding-exception (4.5.1 The xforms-binding-exception Event) occurs if this attribute does not indicate an instance in the same model as the submission.- targetref
Author-optional attribute containing an XPath expression that indicates the target node for data replacement. The in-scope evaluation context of the
submissionelement is used to evaluate the expression. Ifreplaceis "instance", then the target node is replaced by the submission result. Ifreplaceis "text", then the content of the target node is replaced by the submission result. For other values of thereplaceattribute, this attribute is ignored. By default, the target node is the document element of the instance indicated by theinstanceattribute.- separator
Author-optional attribute specifying the separator character between name/value pairs in urlencoding. The default value is '&'. To express the default, character entity encoding is used:
separator='&'.- includenamespaceprefixes
Author-optional attribute providing control over namespace serialization. If absent, all namespace nodes present in the instance data are considered for serialization. If present, specifies list of namespace prefixes to consider for serialization, in addition to those visibly utilized. As in [Exc-C14N], the special value
#defaultspecifies the default namespace.
The following examples show how various options on element submission can affect serialization as application/xml. Given the following XForms fragment:
<xforms:model xmlns:xforms="http://www.w3.org/2002/xforms"
xmlns:my="http://ns.example.org/2003">
<xforms:instance>
<qname xmlns="">my:sample</qname>
</xforms:instance>
<xforms:submission method="post" resource="..."/>
</xforms:model>Note that the includenamespaceprefixes attribute is not present, which causes all namespace nodes to be serialized, resulting in the following serialized instance data:
<qname xmlns:xforms="http://www.w3.org/2002/xforms"
xmlns:my="http://ns.example.org/2003">my:sample</qname>In particular, note that the XForms namespace has been serialized. To prevent this example from including the unneeded XForms namespace while maintaining the needed my prefix, includenamespaceprefixes="my" must be added to the submission element. When this attribute is present, the author takes responsibility to list all namespace prefixes not visibly utilized by the submitted instance data.
The following attributes correspond (in spelling, processing, and default values) to attributes on the output element of [XSLT 1.0], with the exception of using xsd:boolean to replace "yes"|"no":
version
indent
encoding
omit-xml-declaration
cdata-section-elements
Note:
The following XSLT attributes have no counterpart in XForms:
doctype-system
doctype-public
The table below provides an overview of the child elements of the XForms submission element, including their attributes and content models. Elements defined in the XForms Actions module are also allowed in the content model of submission.
| Element | Overview of Attributes | Overview of Content Model |
|---|---|---|
| resource | value (string XPath Expression) | PCDATA |
| method | value (string XPath Expression) | PCDATA |
| header | nodeset (nodeset XPath Expression) | name, value+ |
| Action | various | various |
11.2 The xforms-submit Event
Target: submission
Bubbles: Yes
Cancelable: Yes
Context Info: None
Under no circumstances can more than a single concurrent submit process be
under way for a particular
XForms submission. From the start of the default action of xforms-submit for a submission,
until immediately before xforms-submit-done or xforms-submit-error is dispatched to that
submission, the default action for subsequent xforms-submit events dispatched to that
submission is to dispatch xforms-submit-error to that submission with context
information containing an error-type of submission-in-progress.
Otherwise, the default action for this event results in the following steps:
The data model is updated based on some of the flags defined for deferred updates.. Specifically, if the deferred update
rebuildflag is set for themodelcontaining thissubmission, then the rebuild operation is performed without dispatching an event to invoke the operation. Then, if the deferred updaterecalculateflag is set for themodelcontaining thissubmission, then the recalculate operation is performed without dispatching an event to invoke the operation. This sequence of operations affects the deferred update behavior by clearing the deferred update flags associated with the operations performed.If the binding attributes of
submissionindicate an empty nodeset or a node other than an element or an instance document root node, then submission processing is stopped after dispatching eventxforms-submit-errorwith context information containing anerror-typeofno-data. Otherwise, the binding attributes ofsubmissionindicate a node of instance data.The indicated node and all nodes for which it is an ancestor are selected. If the attribute
relevantistrue, whether by default or declaration, then any selected node which is not relevant as defined in 6.1.4 The relevant Property is deselected (pruned). If all instance nodes are deselected, then submission processing is stopped after dispatching eventxforms-submit-errorwith context information containing anerror-typeofno-data.If the attribute
validateistrue,whether by default or declaration, then all selected instance data nodes are checked for validity according to the definition in 4.3.3 The xforms-revalidate Event (no notification events are marked for dispatching due to this operation). Any selected instance data node that is found to be invalid stops submission processing after dispatching eventxforms-submit-errorwith context information containing anerror-typeofvalidation-error.The submission method is determined.
The submission resource is determined. If the resource is not specified, then submission processing stops after dispatching even
xforms-submit-errorwith context information containing anerror-typeofresource-error.If the
serializationattribute value is"none", then the submission data serialization is the empty string. Otherwise, the submission data serialization is determined as follows. The eventxforms-submit-serializeis dispatched. If thesubmission-bodyproperty of the event is changed from the initial value of empty string, then the content of thesubmission-bodyproperty string is used as thesubmission data serialization. Otherwise, thesubmission data serializationconsists of a serialization of the selected instance data according to the rules stated in 11.9 Submission Options.The
submission headersare determined using the header entries produced by theheaderelement(s) in the submission and themediatypeattribute or its default.The submission is performed based on the
submission headers, submission method, submission resource, andsubmission data serialization. The exact rules of submission are based on the URI scheme and the submission method, as defined in 11.9 Submission Options.
Note:
A submission with no resource specification can be used to test validity of data. If the
selected data is invalid, then the xforms-submit-error has an error-type of
validation-error. If the selected data is valid, then the xforms-submit-error has
an error-type of resource-error.
If the mode of the submission is asynchronous, then default processing for this event
ends after the above steps, and submission processing is resumed once the response from the submission is returned.
In the same manner used to handle user-generated events or the dispatch and processing of delayed events,
the processing of the asynchronous submission response is done without interrupting the processing of any other event and its event handlers.
If the mode of the submission is synchronous, then the XForms processor suspends user interaction with all form controls
of the document and action processing is blocked within the default processing for this event until the response from the submission is returned.
The response returned from the submission is applied as follows:
For a success response including a body, when the value of the
replaceattribute on elementsubmissionis "all", the eventxforms-submit-donemay be dispatched with appropriate context information, and submit processing concludes with entire containing document being replaced with the returned body.For a success response including a body of an XML media type (as defined by the content type specifiers in [RFC 3023]), when the value of the
replaceattribute on elementsubmissionis "instance", the response is parsed as XML. If the parse fails, then submission processing concludes after dispatchingxforms-submit-errorwith appropriate context information, including anerror-typeofparse-error. However, if the XML parse succeeds, then instance data replacement is performed according to the rules specified in 11.10 Replacing Data with the Submission Response. This operation may fail for a number of reasons, including if processing of thetargetrefattribute yields a readonly node (ifreplace="text") or a node that either has a readonly parent or is not an element (ifreplace="instance"). In this case, submission ends after dispatching eventxforms-submit-errorwith appropriate context information, including anerror-typeoftarget-error. Otherwise, the instance data replacement succeeds. Submission processing then concludes after dispatchingxforms-submit-donewith appropriate context information.For a success response including a body of a non-XML media type (i.e. with a content type not matching any of the specifiers in [RFC 3023]), when the value of the
replaceattribute on elementsubmissionis "instance", nothing in the document is replaced and submission processing concludes after dispatchingxforms-submit-errorwith appropriate context information, including anerror-typeofresource-error.For a success response including a body of an XML media type (as defined by the content type specifiers in [RFC 3023]) or a text media type (as defined by a content type of
text/*), when the value of thereplaceattribute on elementsubmissionis "text", the response is encoded as text. Then, the content replacement is performed according to the rules specified in 11.10 Replacing Data with the Submission Response. If the processing of thetargetrefattribute (including its default) fails, then the submission processing concludes after dispatchingxforms-submit-errorwith appropriate context information, including anerror-typeoftarget-error. Otherwise, submission processing then concludes after dispatchingxforms-submit-donewith appropriate context information.For a success response including a body that is both a non-XML media type (i.e. with a content type not matching any of the specifiers in [RFC 3023]) and a non-text type (i.e. with a content type not matching
text/*), when the value of thereplaceattribute on elementsubmissionis "text", nothing in the document is replaced and submission processing concludes after dispatchingxforms-submit-errorwith appropriate context information, including anerror-typeofresource-error.For a success response including a body, when the value of the
replaceattribute on elementsubmissionis "none", submission processing concludes after dispatchingxforms-submit-donewith appropriate context information.For a success response not including a body, submission processing concludes after dispatching
xforms-submit-donewith appropriate context information.Behaviors of other possible values for attribute
replaceare not defined in this specification.For an error response, when the value of the
replaceattribute on elementsubmissionis "all", either the document is replaced with an implementation-specific indication of an error or submission processing concludes after dispatchingxforms-submit-errorwith appropriate context information, including anerror-typeofresource-error.For an error response, when the value of the
replaceattribute on elementsubmissionis not "all", nothing in the document is replaced, and submission processing concludes after dispatchingxforms-submit-errorwith appropriate context information, including anerror-typeofresource-error.
In addition to initiating a submission with its default processing, XForms actions can also provide handlers for the xforms-submit event to peform tasks such as data preparation.
Example:
Preparing data for submission
<submission resource="http://example.com/searchDoctors" method="post" ref="instance('doctorSearchParams')"
replace="instance" targetref="instance('doctorList')" >
<action ev:event="xforms-submit">
<setvalue ref="diagnosis" value="instance('patientRecord')/malady"/>
<setvalue ref="city" value="instance('patientRecord')/city"/>
</action>
</submission>The schema for the doctor search service requires certain portions of the patient record in order to provide a list of specialists who could treat the patient. The server-side module may perform database searches for doctors with the required specialties as well as implement business rules such as providing doctors that are within an acceptable distance of the given city. The resulting list is provided to a separate instance so it can be presented to the user for selection or used in subsequent availability searches.
11.3 The xforms-submit-serialize Event
Dispatched at the beginning of submission serialization (see 11.2 The xforms-submit Event).
Target: submission
Bubbles: Yes
Cancelable: No
Context Info:
| Property | Type | Value |
|---|---|---|
| submission-body | node-set | A document element node with a QName of submission-body. The node initially contains an empty string. Event handlers can write data into the node. If the string value of this node is non-empty, then the string value is used in the submission in lieu of the default instance data serialization. |
Note:
The submission-body property is a string, but the event() function encapsulates
the string in a text node so that the string can be modified by the setvalue action,
which sets a value into a node determined by its Single Node Binding.
Note:
Since the submission-body is a string, this feature may be used to submit non-XML data.
Default Action: If the event context submission-body property string is empty, then no operation is performed so that the submission will use the normal serialization data
(see 11.2 The xforms-submit Event).
Otherwise, if the event context submission-body property string is non-empty, then the serialization data for the submission is set to be the content of the submission-body string.
Example:
Submitting plain text
<submission resource="http://example.com/greeter" method="post" mediatype="text/plain">
<setvalue ev:event="xforms-submit-serialize" ref="event('submission-body')" value="my/text"/>
</submission>The string value of the element my/text is placed into the node representing the submission body, so that is the text posted by the submission. In this example, the result returned by the submission replaces the document. This feature could be used to submit plain text, but it could also be used to allow a document to submit its serialization rather than just submitting instance data.
11.4 The xforms-submit-done Event
Dispatched as an indication of: successful completion of a submission process
Target: submission
Bubbles: Yes
Cancelable: No
Context Info:
| Property | Type | Value |
|---|---|---|
| resource-uri | string | The submission resource URI that succeeded (xsd:anyURI) |
| response-status-code | number | The protocol return code of the success response, or NaN if the submission did not receive a success response. |
| response-headers | node-set | Zero or more elements, each one representing a content header in the success response received by the submission. The returned node-set is empty if the submission did not receive a response or if there were no headers. Each element has a local name of header with no namespace URI and two child elements, name and value, whose string contents are the name and value of the header, respectively. |
| response-reason-phrase | string | The protocol response reason phrase of the success response. The string is empty if the submission did not receive a response or if the response did not contain a reason phrase. |
Default Action: None; notification event only.
Example:
Submission Sequencing
<submission resource="https://example.com/getRecord" method="post" replace="instance" instance="record">
<send ev:event="xforms-submit-done" submission="chargeForRecord"/>
</submission>
<submission id="chargeForRecord" resource="https://example.com/chargeForRecord" method="get" serialization="none" replace="none"/>
The default instance data is submitted as the search criteria for a desired record. Only upon successful completion of the submission is a second submission performed to charge the user's account for the record.
11.5 The xforms-submit-error Event
Dispatched as an indication of: failure of a submission process
Target: submission
Bubbles: Yes
Cancelable: No
Context Info:
| Property | Type | Value |
|---|---|---|
| error-type | string | One of the following: submission-in-progress, no-data, validation-error, parse-error, resource-error, target-error. |
| resource-uri | string | The submission resource URI that failed (xsd:anyURI) |
| response-status-code | number | The protocol return code of the error response, or NaN if the failed submission did not receive an error response. |
| response-headers | node-set | Zero or more elements, each one representing a content header in the error response received by a failed submission. The returned node-set is empty if the failed submission did not receive an error response or if there were no headers. Each element has a local name of header with no namespace URI and two child elements, name and value, whose string contents are the name and value of the header, respectively. |
| response-reason-phrase | string | The protocol response reason phrase of the error response. The string is empty if the failed submission did not receive an error response or if the error response did not contain a reason phrase. |
| response-body | object (string or node-set) |
When the error response specifies an XML media type as defined by [RFC 3023],
the response body is parsed into
an XML document and the root element of the document is returned. If the parse fails, or if the error response
specifies a text media type (starting with text/), then the response body is returned as a
string. Otherwise, an empty string is returned.
|
Default Action: None; notification event only.
Example:
Reporting a Submission Error
<submission resource="https://example.com/getRecord" method="post" replace="instance" instance="record">
<message ev:event="xforms-submit-error">A submission error (<output value="event('error-type')"/>) occurred.</message>
</submission>
The default instance data is submitted as the search criteria for a desired record. Only upon successful completion of the submission is a second submission performed to charge the user's account for the record.
11.6 The Submission Resource
The submission resource is the URI for the submission. It is of type xsd:anyURI.
In XForms 1.0, the URI for submission was provided by the action attribute. For consistency, form authors should now
use the attribute resource of type xsd:anyURI, which deprecates the action attribute.
If both action and resource are present, then the resource attribute takes precedence.
The resource element provides the submission URI, overriding
the resource attribute and the action attribute. If a submission has more than one resource child element, the
first resource element child must be selected for use. Individually, the resource element, the resource attribute and
the action attribute are not required. However, one of the three is mandatory as there is no default submission resource.
11.6.1 The resource Element
The resource element allows the URI used for a submission to be dynamically calculated based on instance data.
Common Attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the URI, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
Content: PCDATA
The URI to be used by the submission can be specified with either the value attribute or
the string content of the resource element. If both are specified, then the value attribute takes precedence.
If the submission does not have a resource child element,
then the submission URI is obtained from the resource attribute or the action attribute.
Example:
Submitting the default instance to a location determined dynamically from an instance
<submission method="post">
<resource value="instance('params')/anyURI"/>
</submission>11.7 The Submission Method
The submission method indicates the submission protocol operation to be performed.
The submission method may be specified by the method attribute. The submission element can
have a child element named method, which overrides the submission method setting obtained from the method attribute
if both are specified. If more than one method element is given, the first
occurrence in document order must be selected for use.
Individually, the method element and the method attribute are not required. However, one of the
two is mandatory as there is no default submission method.
11.7.1 The method Element
The method element allows the submission method to be dynamically calculated based on instance data.
Common Attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the method, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
Content: PCDATA
The method to be used by the submission can be specified with either the value attribute or
the string content of the method element. If both are specified, then the value attribute takes precedence.
If the submission does not have a method child element, then the submission method is obtained from
the method attribute.
11.8 The header Element
The header element can be used to contribute information to the preamble of a submission in a
manner appropriate to the protocol. The submission element can contain zero or more header child elements.
Each produces zero or more header entries containing a name, a value, and a combination. The entries
are provided to the submission protocol in the specified order. It is the responsibility of the submission protocol implementation
to combine the entries and to serialize the result into submission protocol headers. Accordingly, entries may be re-ordered,
combined, or otherwise altered in accordance with the specific protocol implementation requirements.
Common Attributes: None
Special Attributes:
- nodeset
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. One or more header entries are generated for each node selected by this attribute.
- combine
Author-optional attribute defaulting to "append" and with legal values of "append", "prepend", and "replace". This attribute controls the method of combination for entries produced by this element
headerwith other entries produced by otherheaderelements. This attribute and its default also provide information for the protocol implementation, which may use some or all of the information to combine XForms submission headers with headers provided by the user agent.
Content: (name, value+) |
(value+, name)
If the header element does not contain a nodeset attribute, then one header
entry is created for each value element.
If the header element contains a nodeset attribute, then for each
selected node, one header entry is created for each value element.
The name and value of the header entry are obtained from the required child elements
name (11.8.1 The name Element) and value (11.8.2 The value Element).
If the name obtained from the name element is the empty string, then the header entry is
omitted.
The header entry order is determined as follows:
document order of
headerelementsnode order of nodes in
nodesetattributedocument order of
valueelements
The application of this order information to header serialization is determined by the submission protocol.
If a header element defines the Content-type header, then this setting overrides a
Content-type set by the mediatype attribute.
In the case of a multipart submission, the header entries are combined with those for the first part of the submission.
Example:
Setting the Accept header
In the example below, the submission request uses the header element to replace the user agent's existing value of the HTTP Accept header with application/sparql-results+xml.
<submission id="loadConcepts"
resource="http://example.com/taxonomy/concepts" method="get"
ref="instance('conceptsList')" replace="instance">
<header combine="replace">
<name>Accept</name>
<value>application/sparql-results+xml</value>
</header>
</submission>11.8.1 The name Element
When the name element appears as a child of element header, it is used to specify the name of a header
entry to be provided to the submission protocol.
Common Attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the header name, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
The header entry name may be given by the string content of the name element,
or by the result of the value attribute. If both are given, the result from the value attribute takes
precedence. If the resulting name is the empty string, then the
entry is considered to be void, and it is not
supplied to the submission protocol.
11.8.2 The value Element
When the value element appears as a child of element header, it is used to specify the value component
of a header entry to be supplied to the submission protocol
to be added to the preamble of a submission. The value element may be used more than once
in a given element header, in which case each value produces a new header entry.
Common Attributes: None
Special Attributes:
- value
Author-optional attribute containing an XPath expression to evaluate using the in-scope evaluation context. To obtain the header entry value, the result of the expression is processed as if by call to the XPath
stringfunction. An empty string is used if the XPath evaluation fails.
The header entry value may be given by the string content of the value element,
or by the result of the value attribute. If both are given, the result from the value attribute
takes precedence.
Note:
The XPath string function combines multiple nodes by concatenating them into a string separated with spaces.
As a result, a header value specified by a value element nodeset containing multiple nodes may not be
properly serialized in a submission protocol preamble. To assure proper delivery of individual header items
to the submission protocol, restrict use of XPath expressions producing nodesets for element header
with attribute nodeset, where each node will produce its own separate header entry, and use expressions
resulting in only a single node in element value.
11.9 Submission Options
The XForms Model specifies a submission element containing the following attributes and child elements
that affect serialization and submission.
This section summarizes the behaviors for the allowable values of these attributes and child elements,
and presents subsections that define the behavior for submission and serialization.
For the submission protocol obtained from the URI scheme in the submission resource, XForms normatively defines a binding to HTTP/1.1 [RFC 2616].
Note:
Other bindings, in particular to the URI scheme "mailto:" may, and the schemes "https:" and "file:" should, be supported. Bindings to these schemes are not normatively defined in XForms. Implementations that choose to provide a binding to these schemes should pay particular attention to privacy and security concerns. Within the "http:" and "https:" schemes, form creators are encouraged to follow the finding of the W3C Technical Architecture Group on when to use the GET method: [TAG Finding 7]
The submission method determines the default data serialization format, and both the submission method and the URI scheme in the submission resource determine the submission protocol operation, according to the following table:
| URI scheme | Submission Method | Default Serialization | Submission Protocol Operation |
|---|---|---|---|
| http https mailto | "post" | application/xml | HTTP POST or equivalent |
| http https file | "get" | application/x-www-form-urlencoded | HTTP GET or equivalent |
| http https file | "delete" | application/x-www-form-urlencoded | HTTP DELETE or equivalent |
| http https file | "put" | application/xml | HTTP PUT or equivalent |
| http https mailto | "multipart-post" | multipart/related | HTTP POST or equivalent |
| http https mailto | "form-data-post" | multipart/form-data | HTTP POST or equivalent |
| http https mailto | "urlencoded-post" | application/x-www-form-urlencoded | HTTP POST or equivalent |
| (any) | Any other NCName | application/xml | As given by the Submission Method |
| (any) | QNameButNotNCName | implementation-defined | implementation-defined |
Note:
Foreign-namespaced attribute values are allowed in the Submission Method, but no behavior is defined by XForms.
11.9.1 The get Submission Method
This submit method represents HTTP GET or the equivalent concept. The serialized form data is delivered as part of the URI that is requested during the submit process.
This method is not suitable for submission of forms that are intended to change state or cause other actions to take place at the server. See [RFC 2616] for recommended uses of HTTP GET.
The URI is constructed as follows:
The submit URI is examined. If it does not already contain a
?(question mark) character, one is appended. If it does already contain a question mark character and the serialized form data is non-empty, then a separator character from the attributeseparatoris appended.The serialized form data, if any, is appended to the URI.
No message body is sent with the request.
Examples:
Simple search submission
<submission resource="http://example.com/search" method="get"/>
After doing relevance and validity checking on the data, the leaf nodes
of the default instance are submitted asynchronously, encoded as a URL
(application/x-www-form-urlencoded), to http://example.com/search.
The result replaces the whole page.
Reading from a local file
<submission resource="file:data.xml" method="get" serialization="none" replace="instance" instance="data" />
Replaces the instance 'data' with the content of the file data.xml. Serialization, and its associated validity and relevance processing, is not needed. See the corresponding example for saving a file in Section 11.9.3 The put Submission Method. The user agent may restrict file access to a user-specific and domain-specific security zone in local storage.
11.9.2 The post, multipart-post, form-data-post, and urlencoded-post Submission Methods
These submit methods represent HTTP POST or the equivalent concept (such as a mail message). The serialized form data is delivered as the message body.
Examples:
Posting instance data
<submission resource="https://example.com/jsp/orders" method="post" ref="/purchaseOrder" />
Submits the XML for a purchase order to a secure server order processing system.
Simple posted login
<submission resource="http://example.com/login" method="urlencoded-post"/>
After doing relevance pruning and validity checking on the login data, the leaf nodes
of the default instance are submitted asynchronously in the posted data, encoded based on the
application/x-www-form-urlencoded serialization, to http://example.com/login.
The result replaces the whole page.
11.9.3 The put Submission Method
This submit method represents HTTP PUT or the equivalent concept (such as writing to a local file). The serialized form data is delivered as the message body.
Example:
Saving to a local file
<submission resource="file:data.xml" ref="instance('data')" method="put" validate="false" relevant="false" replace="none" />Saves the instance 'data' to the file data.xml without validation checking and relevance pruning. See the corresponding example for reading from a local file in Section 11.9.1 The get Submission Method. The user agent may restrict file access to a user-specific and domain-specific security zone in local storage.
11.9.4 The delete Submission Method
This submit method represents HTTP DELETE or the equivalent concept (such as deleting a local file). The serialized form data is delivered in the same manner as the get submission method (see 11.9.1 The get Submission Method).
11.9.5 Serialization as application/xml
This format permits the expression of the instance data as XML that is straightforward to process with off-the-shelf XML processing tools. In addition, this format is capable of submission of binary content.
The steps for serialization are as follows:
An XML document is produced following the rules of the XML output method defined in [XSLT 1.0] section 16 and 16.1, using the values supplied as attributes of the
submissionelement.Handling of namespace nodes: The default behavior is that every namespace node is serialized according to the rules of the XML output method, so that at least one namespace declaration appears in the serialized XML for each in-scope namespace. Additional inherited namespaces are declared on the root element of the serialized XML. If, however, attribute
includenamespaceprefixeson elementsubmissionis present, then all namespace declarations not visibly utilized in the instance data (as defined in [Exc-C14N]) and the default namespace if it is empty are excluded from the root element serialization, unless the corresponding namespace prefix is listed in theincludenamespaceprefixesattribute. The special value#defaultrepresents the default namespace.Mediatype: By default, the mediatype of the serialized XML instance is
application/xml, but can be changed to a compatible type using elementsubmissionattributemediatype. Authors should ensure that the type specified is compatible withapplication/xml.
11.9.6 Serialization as multipart/related
This format is intended for integration of XForms into environments that involve large amounts of binary data where the inclusion of the data as xsd:base64Binary or xsd:hexBinary is undesirable.
In this format, XML instance data is serialized as one part of the [RFC 2387] multipart/related message, using the rules as described in 11.9.5 Serialization as application/xml. Binary content from xsd:anyURI instance nodes populated by the upload (see 8.1.6 The upload Element) control is serialized in separate parts of the [RFC 2387] multipart/related message.
This format follows the rules of multipart/related MIME data streams for in [RFC 2387], with specific requirements of this serialization listed below:
multipart/relatedmessage header requirements:First body part (root) requirements:
Subsequent part requirements:
multipart/related
<submission method="multipart-post" resource="http://example.com/photo" />
Submits the instance data in multipart/related, along with the selected file as an attachment.
POST /photo HTTP/1.0 Host: example.com Content-Type: multipart/related; boundary=f93dcbA3; type=application/xml; start="<980119.X53GGT@example.com>" Content-Length: xxx --f93dcbA3 Content-Type: application/xml; charset=UTF-8 Content-ID: <980119.X53GGT@example.com> <?xml version="1.0"?> <uploadDocument> <title>My Proposal</title> <author>E. X. Ample</author> <summary>A proposal for a new project.</summary> <notes image="cid:980119.X17AXM@example.com">(see handwritten region)</notes> <keywords>project proposal funding</keywords> <readonly>false</readonly> <filename>image.png</filename> <content>cid:980119.X25MNC@example.com</content> </uploadDocument> --f93dcbA3 Content-Type: image/png Content-Transfer-Encoding: binary Content-ID: <980119.X25MNC@example.com> ...Binary data here... --f93dcbA3 Content-Type: image/png Content-Transfer-Encoding: binary Content-ID: <980119.X17AXM@example.com> ...Binary data here... --f93dcbA3--
11.9.7 Serialization as multipart/form-data
This format is for legacy compatibility to permit the use of XForms clients with [RFC 2388] servers. This method is suitable for the persistence of binary content. Contextual path information, attribute values, namespaces and namespace prefixes are not preserved. As a result, different elements might serialize to the same name.
Note:
Existing HTML user agents fail to encode special characters (such as double quotes) and non-ASCII characters in the Content-Disposition: form-data name and filename parameters. Since this serialization method is supported for legacy applications only, new applications should use application/xml or multipart/related.
This format follows the rules for multipart/form-data MIME data streams in [RFC 2388], with specific requirements of this serialization listed below:
Each element node is visited in document order, except non-relevant elements are skipped if the
relevantsetting of thesubmissionistrue.Each visited element that has no child element nodes (i.e., each leaf element node) is selected for inclusion, including those that have no value (no text node).
Element nodes selected for inclusion are encoded as
Content-Disposition: form-dataMIME parts as defined in [RFC 2388], with thenameparameter being the element local name.Element nodes of any datatype populated by
uploadalso have aContent-Dispositionfilenameparameter, if the filename is available.Element nodes of any datatype populated by
uploadare serialized as the specified binary content. In the case ofxsd:anyURIand derived types, the serialization content is obtained from the URI. Forxsd:base64Binary,xsd:hexBinary, and derived types, the serialization content is obtained by decoding the element string value.Element nodes of any datatype not populated by
uploadare serialized as the string value of the element (the concatenation of all text node children, or empty string if the element has no text node children).The
Content-Typemust betext/plainexcept forxsd:anyURI,xsd:base64Binary,xsd:hexBinary, and derived types, in which case the header represents the media type of the attachment if known, otherwiseapplication/octet-stream. If a character set is applicable, theContent-Typemay have acharsetparameter.
Example:
multipart/form-data
<submission method="form-data-post" resource="http://example.com/photo" />
Submits the instance data in multipart/form-data, along with the selected file as a part.
POST /photo HTTP/1.0 Host: example.com Content-Type: multipart/form-data; boundary=AaB03x Content-Length: xxx --AaB03x Content-Disposition: form-data; name="document"; filename="b.txt" Content-Type: text/plain; charset=iso-8859-1 This is a file. It has two lines. --AaB03x Content-Disposition: form-data; name="title" A File --AaB03x Content-Disposition: form-data; name="summary" This is my file file test --AaB03x--
11.9.8 Serialization as application/x-www-form-urlencoded
This format represents an extension of the [XHTML 1.0] form content type application/x-www-form-urlencoded with specific rules for encoding non-ASCII and reserved characters.
This format is not suitable for the persistence of binary content. Therefore, it is recommended that forms capable of containing binary content use another serialization method.
The steps for serialization are as follows:
Each element node is visited in document order, except non-relevant elements are skipped if the
relevantsetting of thesubmissionistrue. Each visited element that has no child element nodes (i.e., each leaf element node) is selected for inclusion, including those that have no value (no text node). Note that attribute information is not preserved.Element nodes selected for inclusion are encoded as
EltName=value, where=is a literal character,EltNamerepresents the element local name, andvaluerepresents the string value of the element (the concatenation of all text node children, or empty string if the element has no text node children). The separator character {sep} from theseparatorattribute onsubmissionis used between pairs of encoded name/value pairs, e.g.EltName1=value1{sep}EltName2=value2{sep}EltName3=value3. Note that contextual path information is not preserved, nor are namespaces or namespace prefixes. As a result, different elements might serialize to the same name.The encoding of
EltNameandvalueare as follows: space characters are replaced by+, and then non-ASCII and reserved characters (as defined by [RFC 2396] as amended by subsequent documents in the IETF track) are escaped by replacing the character with one or more octets of the UTF-8 representation of the character, with each octet in turn replaced by%HH, whereHHrepresents the uppercase hexadecimal notation for the octet value and%is a literal character. Line breaks are represented as "CR LF" pairs (i.e.,%0D%0A).
All such encodings are concatenated, maintaining document order.
Example:
application/x-www-form-urlencoded
This format consists of simple name-value pairs.
<PersonName title="Mr"> <GivenName>René</GivenName> </PersonName>
Here is the instance data for the above example. Note that very little of the data is preserved. Authors desiring greater data integrity should select a different serialization format.
11.10 Replacing Data with the Submission Response
The submission element allows an author-optional attribute named targetref. The attribute value is interpreted as
a binding expression to which the first node rule is applied to obtain a replacement target node for the submission response.
This attribute is ignored unless the value of the replace attribute is "instance" or "text".
For backwards compatibility with documents created for earlier versions of the specification, the processor of the submission element
may allow the author-optional attribute named target to be used. The target attribute provides exactly the
same behaviors as the targetref attribute except that the target attribute is ignored if the submission element also bears a
targetref attribute.
The default replacement target node is the document element node of the instance identified by the instance attribute, which
is equal to the default instance of the model if not specified. The evaluation context for this attribute is the in-scope evaluation context
for the submission element, except the context node is modified to be the document element of the instance identified by the
instance attribute if it is specified.
This attribute is evaluated only once a successful submission response has been received and if the replace attribute
value is "instance" or "text". The first node rule is applied to the result.
The processing of the targetref attribute (and its default) is considered to have failed if the result is any of the following:
an empty nodeset
a readonly node, if
replace="text"a non-element, if
replace="instance"a node whose parent is readonly, if
replace="instance"
If the processing of the targetref attribute fails, then submission processing ends after dispatching the
event xforms-submit-error with an error-type of target-error.
If the replace attribute contains the value "text" and the
submission response conforms to an XML mediatype (as defined by the content type specifiers in [RFC 3023]) or
a text media type (as defined by a content type specifier of text/*), then the response data is encoded as text and replaces the
content of the replacement target node.
If the replace attribute contains the value "instance" and the submission response conforms to an XML mediatype
(as defined by the content type specifiers in [RFC 3023]) and the XML parse of the submission response succeeds, then
the XML obtained from the submission response is used to replace the target node. The XML in the response may have comment
and processing instruction nodes before and after the document element. These nodes are discarded if the replacement target node
is not the document element of an instance. Otherwise, those processing instructions and comments replace any processing instructions
and comments that previously appeared outside of the document element of the instance being replaced.
In the case of text replacement of the content of the replacement target node, the replacement is performed by the XForms Action setvalue (10.2 The setvalue Element).
In the case of instance node replacement, the replacement is performed by an XForms action that performs some combination of node insertion and deletion operations that
are performed by the insert action (10.3 The insert Element) and the delete action (10.4 The delete Element).
If the submission has a mode of "asynchronous", then the text replacement action or the instance node replacement action is an outermost action handler, so the
deferred update behavior occurs at the end of the action. If the mode is "synchronous", then
the text replacement action or the instance node replacement action is not outermost since occurs during the default processing of xforms-submit, so the
appropriate deferred update flags are set based on whether the action was a setvalue or whether it performed
a series of insert and delete actions.
Note:
In an asynchronous submission, the deferred update behavior ensures that the user interface is up to date with the latest calculated values before the xforms-submit-done
event is dispatched. In a synchronous submission, the calculated values dependent on replaced text or data nodes can be made available to actions in the xforms-submit-done handler
by first invoking the recalculate action. A sequence of synchronous submissions performed with successive send actions can avoid refreshing the user interface until after the
completion of the last send action.
Examples:
Replacing a subtree of instance data
<submission resource="http://example.com/jsp/prefill" method="post" ref="name" replace="instance" targetref="address"/>
This submission would be invoked after the user enters a value for name. Based on the name given, a simple server-side database
lookup is performed to get a last known address. The address element is replaced with the result, prefilling part of the form for the user.
Replacing text in an instance
<submission resource="http://example.com/postalCodeSearch" method="get" ref="address" replace="text" targetref="address/postalCode"/>
The address information is past to a postal code search service that returns a textual result, which is placed into the postalCode element.
Submission and Read-Only Content
<model xmlns:my="http://example.org">
<instance>
<my:data>
<my:name>
<my:first-name>John</my:first-name>
<my:last-name>Doe</my:last-name>
</my:name>
<my:address>
<my:street>123 Main St.</my:street>
<my:city>Smallville</my:city>
</my:address>
</my:data>
</instance>
<bind nodeset="/my:data/my:name/" readonly="true()"/>
<bind nodeset="/my:data/my:address/my:street" readonly="true()"/>
<submission id="S1" targetref="my:name" replace="instance" method="post" resource="..."/>
<submission id="S2" targetref="my:name/my:first-name" replace="instance" method="post" resource="..."/>
<submission id="S3" targetref="my:name/my:first-name" replace="text" method="post" resource="..."/>
<submission id="S4" targetref="my:address/my:street" replace="text" method="post" resource="..."/>
</model>
Submission S1 succeeds because a readonly node (my:name) can be replaced if its parent is not readonly.
Submission S2 fails because a node (my:first-name) cannot be replaced if its parent is readonly.
Submission S3 fails because the content of a readonly node cannot be replaced, even if it is readonly due to inheritance.
Submission S4 failse because the content of a readonly node cannot be replaced, even if the node's parent is not readonly.
11.11 Integration with SOAP
This section describes the integration of XForms submission with [SOAP 1.1] and [SOAP 1.2]
11.11.1 Representation of SOAP Envelope
The single-node binding of the submission element refers to the XML data to be submitted. In the case of a SOAP submission, the instance data includes the SOAP envelope and related SOAP tags.
Note:
The form author may choose to store the data payload in one instance and copy the data to the submission instance containing the SOAP envelope as part of an xforms-submit event handler. The form author is responsible for declaring the appropriate model item properties on both instances (e.g. the relevant declarations).
11.11.2 Indicating a SOAP submission
For a SOAP submission, the mediatype attribute of the submission
must be set to the MIME type of application/soap+xml. The form author may append charset and action MIME parameters.
Note:
The action MIME parameter has no effect unless the submission method is "post" because the GET method implies no SOAP processing by the receiving SOAP node.
Note:
SOAP 1.1 does not support the HTTP GET operation.
11.11.3 SOAP HTTP Binding
The method attribute of the submission
must be set to get or post in order to access the SOAP HTTP binding.
If method="get", then the SOAP response message exchange pattern is used. The HTTP headers must contain the Accept parameter with a value conforming to the following properties:
must begin with
application/soap+xmlIf the submission
mediatypecontains acharsetMIME parameter, then it is appended to theapplication/soap+xmlMIME type. Otherwise, acharsetMIME parameter with same value as theencodingattribute (or its default) is appended to theapplication/soap+xmlMIME type.No other MIME parameters from the
mediatypeare copied to theapplication/soap+xmlMIME typeThe
qMIME parameter must not be specified in theapplication/soap+xmlMIME type so that the default quality of 1 is used.
If method="post", then the SOAP request-response message exchange pattern is used. For SOAP 1.2, the current submission behavior of using the mediatype attribute value as the value of the Content-type parameter in the HTTP headers is sufficient. If the instance data being submitted has as its root element node a SOAP envelope in the SOAP 1.1 namespace (http://schemas.xmlsoap.org/soap/envelope/), then:
the
Content-typeHTTP header is changed totext/xmlthe
charsetMIME parameter is appended . The charset parameter value from themediatypeattribute is used if it is specified. Otherwise, the value of theencodingattribute (or its default) is used.if the
actionMIME parameter appears in themediatypethen a SOAPAction HTTP header is added and given a value equal to the content of theactionMIME parameter
Note:
XForms 1.1 does not support the SOAP email binding, so method="post" with a mailto: scheme results in an xforms-submit-error event before any submit processing message is dispatched.
Note:
XForms 1.1 does not support the SOAP 1.1 binding to the HTTP Extension Framework.
Example:
Consuming a SOAP 1.1 Request-Response Web Service
<xforms:model xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/" xmlns:tns="http://www.webservice.net">
<xforms:instance id="data">
<data xmlns="">
<city>Victoria</city>
<country>Canada</country>
<weather>Mostly sunny and cool. High 12C. Low 3C.</weather>
</data>
</xforms:instance>
<xforms:instance id="GetWeatherSoapIn">
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetWeather xmlns="http://www.webservice.net">
<CityName>Victoria</CityName>
<CountryName>Canada</CountryName>
</GetWeather>
</soap:Body>
</soap:Envelope>
</xforms:instance>
<xforms:instance id="GetWeatherSoapOut">
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetWeatherResponse xmlns="http://www.webservice.net">
<GetWeatherResult>Mostly sunny and cool. High 12C. Low 3C.</GetWeatherResult>
</GetWeatherResponse>
</soap:Body>
</soap:Envelope>
</xforms:instance>
<xforms:submission id="GetWeather" resource="http://www.webservice.net/getweather.asmx" method="post"
ref="instance('GetWeatherSoapIn')" mediatype="application/soap+xml; action=http://www.webservice.net/GetWeather"
replace="instance" instance="GetWeatherSoapOut">
<xforms:action ev:event="xforms-submit">
<xforms:setvalue ref="instance('GetWeatherSoapOut')/soap:Body/tns:GetWeather/tns:CityName"
value="instance('data')/city"/>
<xforms:setvalue ref="instance('GetWeatherSoapOut')/soap:Body/tns:GetWeather/tns:CountryName"
value="instance('data')/country"/>
</xforms:action>
<xforms:action ev:event="xforms-submit-done">
<xforms:setvalue ref="instance('data')/weather"
value="instance('GetWeatherSoapOut')/soap:Body/tns:GetWeatherResponse/tns:GetWeatherResult"/>
</xforms:action>
</xforms:submission>
</xforms:model>
<xforms:input ref="city">
<xforms:label>City </xforms:label>
<xforms:send ev:event="xforms-value-changed" submission="GetWeather"/>
</xforms:input>
<xforms:input ref="country">
<xforms:label>Country </xforms:label>
<xforms:send ev:event="xforms-value-changed" submission="GetWeather"/>
</xforms:input>
<xforms:output ref="weather">
<xforms:label>The weather forecast is </xforms:label>
</xforms:output>
This form accepts input of a city name and country name from the user. When the user changes either value,
the 'GetWeather' web service is initiated. On xforms-submit, the user input is copied into the
request envelope. When the web service submission result is received, the xforms-submit-done
handler copies the weather forecast from the response envelope to the data instance.
The submission and the request and response instances correspond to the web service definition below:
<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
xmlns:tns="http://www.webservice.net" targetNamespace="http://www.webservice.net">
<wsdl:types>
<xs:schema elementFormDefault="qualified" targetNamespace="http://www.webservice.net">
<xs:element name="GetWeather">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="CityName" type="xs:string" />
<xs:element minOccurs="0" maxOccurs="1" name="CountryName" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
<xs:element name="GetWeatherResponse">
<xs:complexType>
<xs:sequence>
<xs:element minOccurs="0" maxOccurs="1" name="GetWeatherResult" type="xs:string" />
</xs:sequence>
</xs:complexType>
</xs:element>
...
</wsdl:types>
<wsdl:message name="GetWeatherSoapIn">
<wsdl:part name="parameters" element="tns:GetWeather" />
</wsdl:message>
<wsdl:message name="GetWeatherSoapOut">
<wsdl:part name="parameters" element="tns:GetWeatherResponse" />
</wsdl:message>
...
<wsdl:portType name="GetWeatherSoap">
<wsdl:operation name="GetWeather">
<wsdl:input message="tns:GetWeatherSoapIn" />
<wsdl:output message="tns:GetWeatherSoapOut" />
</wsdl:operation>
...
</wsdl:portType>
...
<wsdl:binding name="GetWeatherSoap" type="tns:GetWeatherSoap">
<soap:binding transport="http://schemas.xmlsoap.org/soap/http" style="document" />
<wsdl:operation name="GetWeather">
<soap:operation soapAction="http://www.webservice.net/GetWeather" style="document" />
<wsdl:input>
<soap:body use="literal" />
</wsdl:input>
<wsdl:output>
<soap:body use="literal" />
</wsdl:output>
</wsdl:operation>
...
</wsdl:binding>
<wsdl:service name="GetWeatherService">
<wsdl:port name="GetWeatherSoap" binding="tns:GetWeatherSoap">
<soap:address location="http://www.webservice.net/getweather.asmx" />
</wsdl:port>
...
</wsdl:service>
</wsdl:definitions>11.11.4 Handling the SOAP Response
The XForms processor must handle client authorization and redirection.
SOAP faults (400 and 500 level errors) are handled in the same manner as underlying HTTP errors, which is to say that an xforms-submit-error event is dispatched.
On successful completion, the results are consumed according to the XForms submission process, culminating in an xforms-submit-done event. The form author may capture this event and copy data from the target instance that receives the returned SOAP envelope to other instances that are designed to carry only data.