XForms 2.0

From XForms Users Community Group
__NUMBEREDHEADINGS__



Document title:
XForms 2.0
Editors
Erik Bruchez, Orbeon
Alain Couthures, agence XML
Steven Pemberton, CWI
Past Editors
Nick Van den Bleeken, Inventive Designers
John M. Boyer, IBM
Leigh L. Klotz, Jr., Xerox
Abstract
XForms is an XML markup for a new generation of forms and other applications on the Web. XForms is not primarily a free-standing document type, but is intended for integrating into other markup languages, such as [XHTML], [ODF] or [SVG]. An XForms-based application gathers and processes data using an architecture that separates presentation, purpose and content; processing of data occurs using three mechanisms:
  • a declarative model composed of formulae for data calculations and constraints, data type and other property declarations, and data submission parameters
  • a view layer composed of intent-based user interface controls
  • an imperative controller for orchestrating data manipulations, interactions between the model and view layers, and data submissions.

Thus, XForms accommodates component reuse, fosters strong data type validation, eliminates unnecessary round-trips to the server, offers device independence and accessibility, and reduces the need for scripting.

XForms 2.0 moves to using XPath 2.0, which adds new facilities and functions; adds Attribute Value Templates, allowing dynamic data values to be used in attributes; allows labels, hints, help, and alert texts to be expressed as attributes as well as elements; adds custom functions and variables, model-based switch and repeat, and defines consuming and submitting JSON and CSV instance data.

Status of this Document
This is a live wiki document. Although it often reflects the best understanding of the editors and members of the Working Group, it may be inaccurate and has not necessarily been reviewed. If you need a stable copy, use the most recent official version: http://www.w3.org/TR/xforms.

Please send any comments for this version to public-xformsusers@w3.org.

Copyright © 2010 W3C® (MIT, ERCIM, Keio), All Rights Reserved. W3C liability, trademark and document use rules apply.

About XForms

Forms are an important part of the Web, and continue to be a major mode of Web interaction. Web applications and ecommerce have sparked the demand for richer interactions and XForms is a response to this, providing a declarative platform-independent language for online interaction.

The original version of XForms was purely about forms, and followed HTML fairly closely in what it could do. However, thanks to XForms' generality, it was quickly realised that it was capable of far more than only forms if certain parts were further generalised. And so was born XForms 1.1, that allowed not only forms to be created, but certain types of applications as well, that you would not normally consider as being a form. XForms 2.0 continues this process of generalization.

For a list of the differences between XForms 2.0 and 1.1, see the appendix.

Reading the Specification

This specification has been written with various types of readers in mind, in particular XForms authors and implementors; however, it is not intended as a tutorial. The specification is organized as follows:

Sections 1 and 2
An introduction outlining the design principles and giving a brief tutorial.
Sections 3 and up
XForms definition.
Appendixes
An XML Schema description of XForms, references, examples, and other useful information.

Documentation Conventions

With regard to implementing behaviors defined for XForms, this document uses the terms must, must not, required, shall, shall not, recommended, should, should not, and may in accord with [RFC 2119]; however the meaning of optional as defined in that document is represented in this specification with the term implementation-optional. Generally, the elements, attributes, functions and behaviors of XForms defined in this specification are required to be implemented unless explicitly specified otherwise. The term optional when applied to a content item such as an element, attribute, or function parameter, indicates to authors that they may omit the content item and obtain the default behavior if any; the term is orthogonal to the conformance status (required, recommended, or implementation-optional) of the content item.

Throughout this document, the following namespace prefixes and corresponding namespace identifiers are used:

xforms: The XForms namespace, http://www.w3.org/2002/xforms (see Namespace for XForms)
html: The XHTML namespace, http://www.w3.org/1999/xhtml (see [XHTML 1.0])
xs: The XML Schema namespace, http://www.w3.org/2001/XMLSchema (see [XML Schema part 1])
xsi: The XML Schema for instances namespace, http://www.w3.org/2001/XMLSchema-instance (see [XML Schema part 1])
ev: The XML Events namespace, http://www.w3.org/2001/xml-events (see [XML Events])
my: Any user defined namespace.

This is only a convention; any namespace prefix may be used in practice.

The following typographical conventions are used to present technical material in this document.

Official terms are defined in the following manner: [Definition: You can find most terms in chapter Glossary Of Terms]. Links to terms may be specially highlighted where necessary.

The XML representations of various elements within XForms are presented using the syntax for Abstract Modules in XHTML Modularization [XHTML Modularization].

Examples are set off typographically:

Example Item

References to external documents appear as follows: [Sample Reference] with links to the references section of this document.

Sample Reference
Reference - linked to from above.

The following typesetting convention is used for additional commentary:

Note:

A gentle explanation to readers.

Editorial note: Editorial Note Name 2011-08-31
Editorial commentary, not intended for final publication.

Issue (sample-implementation-issue):

Issue-Name

A specific issue for which input from implementors is requested, for example as part of the Candidate Recommendation phase.

Resolution:

None recorded.

Introduction to XForms

XForms was originally designed for handling forms on the web. Forms helped to kick off the web as an interactive medium and for e-commerce, with tasks such as searching, shopping, reading and writing email, editing documents online, configuring hardware, and banking.

XForms has been designed to improve such interactivity. Issues addressed included authoring, reuse, internationalization, accessibility, usability, data structuring, client-side checking, device independence, support of common use cases and reduced reliance on scripting.

Properties of XForms include:

  • Data is separated from the markup of the controls. This not only makes XForms more tractable by making it clear what is being submitted where, it also eases reuse, since the essential part is no longer irretrievably bound to the page it is used in.
  • Controls say what they do, not how they look. This gives the designer more control, makes it easier to deploy to multiple devices, and aids accessibility.
  • Data can be checked client-side. This speeds up interaction since it reduces the need for round trips to the server for validation, and reduces server-side processing.
  • Structured, typed data is supported. This allows integration in existing data pipelines without the data having to be transformed first. Although XML is the principal format for this, formats like JSON and CSV are also supported.
  • Declarative specification is used. The details of the data, including calculation, are defined using declarative markup, rather than scripting, making forms smaller, more tractable (through static analysis), and easier to produce. Experience has shown that this significantly reduces production times and costs.
  • Calculations are done spreadsheet-style. This means that calculations are always up to date, and the user doesn't have to press a 'recalculate' button having changed a value.
  • Data and markup are fully integrated. For instance, as the user enters an address it can be displayed in its final form on the page itself; data imported from an external source can be easily displayed; and as the data changes it is updated on the page. It also means that it is easy to produce an internationalized version of a form, by importing labels in different languages.

An Example

An application in XForms has a section that describes the data being manipulated, called the Model, which includes the data, types, constraints, and relationships with other data values, and another section that describes how the data is manipulated. Consider a simple case like this:

screen shot of an example form

It is clear that we are asking for the method of payment being used, and if a credit card, its number and expiration date.

This can be represented in a model element, which in XHTML would be contained within the head element:

<model>
   <instance>
      <payment xmlns="">
         <amount/>
         <method/>
         <number/
         <expiry/>
      </payment>
   </instance>
   <submission resource="https://example.com/submit" method="post"/>
</model>

This simply says that we are collecting four 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 resource attribute. XForms defines a device-neutral set of controls suitable for general-purpose use. The controls are bound to the data in the model using the ref attribute on the controls. This markup would appear within the <body> of an XHTML document:

Please pay: <output ref="amount"/>
<select1 ref="method" label="Payment Method">
   <item label="Cash">cash</item>
   <item label="Credit">cc</item>
</select1>
<input ref="number" label="Card Number"/>
<input ref="expiry" label="Expiration Date"/>
<submit label="Submit"/>

There are some things worth noting here:

  • The user interface is not hard-coded to use radio buttons, or any other style of input. Different devices (such as voice browsers) can render the concept of "select one" as appropriate, small-screen devices can use drop-down menus, while larger-screen devices can use radio buttons.
  • Controls always have labels directly associated with them — a feature designed to enhance accessibility.

The fact that you can bind controls to the model like this simplifies integration with other host languages, since any control markup may be used to bind to the model.

Submitted Data

The data collected can directly be submitted as XML data. In the example, the submitted data might look like this:

<payment>
   <amount>99.00</amount>
   <method>cc</method>
   <number>1235467789012345</number>
   <expiry>2025-12</expiry>
</payment>

but it is also possible to submit data in URL-encoded style, such as

https://example.com/submit?amount=99.00&method=cc&number=1235467789012345&expiry=2025-12

This is done by changing the method attribute on the submission element to

<submission resource="https://example.com/submit" method="get"/>

Instance Data

Processing keeps track of the state of the values entered through the instance data; this data can be initially empty as in the example above, or may be (partially) initialized with values, for instance:

<instance>
  <payment xmlns="">
    <amount>99.99</amount>
    <method>cc</method>
    <number/>
    <expiry/>
  </payment>
</instance>

Data may be also initialised from external sources. For instance, for a control to fill in a country, the data for the countries of the world can be obtained from an external resource:

<instance id="c" src="countries.xml"/>

If the countries data looks like this:

<countries xml:lang="en">
  <country code="AF">Afghanistan</country>
  <country code="AX">Åland Islands</country>
  <country code="AL">Albania</country>
  <country code="DZ">Algeria</country>
  <country code="AS">American Samoa</country>
  ...

then a suitable select1 control could use this as follows:

<select1 ref="land" label="Country">
  <itemset ref="instance('c')/country" label="{.}" value="@code"/>
</select1>

This means that the country data is no longer hard-wired, but can be sourced from a single file for the whole site, and is easily updated when necessary.

Binding expressions in XForms use [XPath], including the use of the @ character to refer to attributes, as seen here.

Calculating Values

Values can be calculated dynamically from other values as they change.

For instance, if we add to the example above two values for the unit price of an item, and how many are being ordered:

<payment xmlns="">
  <unitprice>99.99</unitprice>
  <howmany/>
  <amount/>
  <method/>
  <number/>
  <expiry/>
</payment>

then we can add a calculation to calculate the total amount from these two:

<bind ref="amount" calculate="../unitprice * ../howmany" />

Whenever either of those two values is changed, the total amount is automatically updated.

Constraining Values

Data can be checked for validity as the values are entered.

In the absence of specific information, all values are considered strings, but values can be assigned other types. For instance in the example, datatypes representing an integer, and a decimal type for representing monetary values can be used:

<bind ref="howmany" type="integer"/>
<bind ref="amount" type="decimal"/>

but there is also a data type that represents a credit card, accepting between 14 and 18 digits:

<bind ref="number" type="card-number"/>

It is possible to add dynamic constraints to a value. For instance, if you want to restrict how many items are bought:

<bind ref="howmany" constraint=". lt 10" />

which would prevent more than 9 items being ordered. There is also a function for checking that a credit card number is valid:

<bind ref="number" constraint="is-card-number(.)"/>

Values can also be checked that they match a particular pattern:

<bind ref="expiry" constraint="matches(., '^[0-9][0-9]/(0[1-9]|1[012])$'"/>

The data cannot be submitted until all constraints are met, and input controls bound to data not matching their constraints are typically marked specially (how they are marked is controllable by stylesheets). You can also include a message to be displayed should the constraints not be met:

<input ref="howmany" label="Number" alert="Must be a whole number less than 10"/>
<input ref="expiry" label="Expiry date" alert="Format YY/MM"/>

Relevance and Required Values

In the example, the values for number and expiry are only relevant if the credit card option is chosen for method, but are required in that case. This is expressed as follows:

<bind ref="number"
      type="card-number"
      relevant="../method='cc'"
      required="true()"/>
<bind ref="expiry"
      relevant="../method='cc'"
      required="true()"/>

Processors have the option of graying out controls bound to non-relevant values, or of making them non-visible, and this is controllable using style sheets.

Putting it all together, the model would look like this:

<model>
   <instance>
     <payment xmlns="">
       <unitprice>99.99</unitprice>
       <howmany/>
       <amount/>
       <method/>
       <number/>
       <expiry/>
     </payment>
   </instance>
   <bind ref="howmany" type="integer" constraint=". lt 10"/>
   <bind ref="amount" type="decimal" calculate="../unitprice * ../howmany" />
   <bind ref="number"
         type="card-number"
         relevant="../method='cc'"
         required="true()"
         constraint="is-card-number(.)"/>
   <bind ref="expiry" relevant="../method='cc'" required="true()"
         constraint="matches(., '^[0-9][0-9]/(0[1-9]|1[012])$'"/>
   <submission resource="https://example.com/submit" method="post"/>
 </model>

Attribute Values

Values can be displayed using the output element, but they can also be injected into attributes, using attribute value templates (AVTs). These are marked with braces "{" and "}". Any part of an attribute may be replaced.

For instance, with

<output ref="total" class="{if (. ge 0) then 'positive' else 'negative'}" />

a style sheet can then have two rules, one for class positive, and one for negative, for instance coloring the output red if it is negative:

.positive {color: black}
.negative {color: red}

or putting brackets around negative values:

.negative::before {content: "("}
.negative::after {content: ")"}

All attributes support AVTs with the exception of attributes that are already expressions, and a small number of structural attributes. These are marked in the descriptions of the attributes.

Multiple Models per Document

A single document may contain multiple data models. In that case controls need to identify which model element contains the data they use by using an id attribute on the model element, and a model attribute on the control alongside the ref attribute. If no model attribute is used, the first model in the document is referred to.

For instance, adding an opinion poll to the example:

<model>
   <instance>
     ...payment instance data...
   </instance>
   <submission resource="https://example.com/submit" method="post"/>
 </model>
 
 <model id="poll">
   <instance>
     <data xmlns="">
       <helpful/>
     </data>
   </instance>
   <submission resource="..."/>
 </model>

Then the controls can identify which model they use:

<select1 ref="helpful" model="poll" label="How useful is this page to you?">
  <item value="0" label="Not at all helpful"/>
  <item value="1" label="Barely helpful"/>
  <item value="2" label="Somewhat helpful"/>
  <item value="3" label="Very helpful"/>
</select1>

<submit model="poll" label="Submit"/>

More examples can be found in Complete XForms Examples.

Document Structure

XForms documents consist of two parts: one or more models that contain data, data properties, and relationships, and a user interface that contains controls bound to the data in the models. How these two parts are contained in a document depends on the host language.

Host languages

XForms is an application of XML [XML 1.0] and has been designed for use within other XML vocabularies, in particular within versions of XHTML [XHTML 1.0]. As such, it is the integration of XForms with the host language that defines exactly where in a document the XForms constructs may go; however, XForms may also be used standalone with the form element.

The definition of XForms is done as a small number of modules. Each module represents a separable part of the functionality of XForms that could if needed be used independently in some host integration.

The namespace URI for XForms, used for distinguishing which elements are from XForms and which from the host language, is http://www.w3.org/2002/xforms.

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://www.w3.org/1999/xhtml">
<head>
    <title>Input</title>
    <model xmlns="http://www.w3.org/2002/xforms">
        <instance>
            <data xmlns="">
                <name/>
            </data>
        </instance>
    </model>
</head>
<body>
    <group xmlns="http://www.w3.org/2002/xforms">
        <input ref="name" label="Your name"/><h:br/>
        Hello <output ref="name"/>!
    </group>
</body>
</html>

The form Element

Although XForms can be embedded in host languages such as XHTML, ODF, or SVG, the form element is available to enclose the elements of an XForm, either as a root element or embedded in another language.

Common Attributes: Common, UI Common

Content:Content: (model|Controls|UI Common)*

<form xmlns="http://www.w3.org/2002/xforms">
  <label>Date</label>
  <model>
     <instance>
        <date xmlns=""><today/></date>
     </instance>
  </model>
  <bind ref="today" calculate="local-date()"/>
  <output ref="today"/>
</form>

The XForms Extension Module

There are many different ways a host language might include XForms. One approach uses only well-formed processing, disregarding validation. Another case uses strict validation, for example XHTML 1.0, in which only predefined elements are allowed. Another common approach is to allow unregulated content in a few select places. A host language that chooses this option can use the Extension module.

Element Attributes and Their Content (after AVT evaluation) Minimal Content Model

extension

Common, Evaluation

ANY

The extension Element

The optional extension element is a container for application-specific extension elements from any namespace other than the XForms namespace. This specification does not define the processing of this element.

Common Attributes: Common, Evaluation

Content: ANY

<input ref="dataset/user/email" id="email-input" label="Your email address">
  <extension>
    <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about="#email-input">
        <my:addressBook>personal</my:addressBook>
      </rdf:Description>
    </rdf:RDF>
  </extension>
</input>

Core Attribute Collections

Common Attributes

The Common Attribute Collection applies to every element.

anyAttribute
Foreign attributes are allowed on all elements; their meaning is defined by the namespace that they come from. For instance, a web-based XForms implementation might allow html:autocomplete attributes on input controls. Processors must ignore unrecognized foreign-namespaced attributes.
Note: The XML Events attributes are foreign attributes and therefore allowed on any element that includes the Common attributes. This specification lists both Common and Events attributes on Actions for reading convenience, since authors are most likely to place Events attributes on the actual event handler elements.
class
An optional list of names that can be matched by CSS class selectors.
dir
Allows the author to specify the direction of the element's text content. This direction affects the display of characters as defined in Unicode Standard Annex #9: The Bidirectional Algorithm [UAX9], and defines directional properties of text as defined by CSS [CSS]. The default value of this attribute is auto. Possible values are:
  • auto: The directionality is determined by the directionality of the first character in the text that has directionality.
  • ltr: Left-to-right text. The effect of this attribute is defined by the CSS2 rule:
*[dir="ltr"] { unicode-bidi: embed; direction: ltr}
  • rtl: Right-to-left text. The effect of this attribute is defined by the CSS2 rule:
*[dir="rtl"] { unicode-bidi: embed; direction: rtl}
  • lro: Left-to-right override. The effect of this attribute is defined by the CSS2 rule:
*[dir="lro"] { unicode-bidi: bidi-override; direction: ltr}
  • rlo: Right-to-left override. The effect of this attribute is defined by the CSS2 rule:
*[dir="rlo"] { unicode-bidi: bidi-override; direction: rtl}

Example

The Hebrew word for "Hebrew" is <span xml:lang="he">עברית</span>,
but since Hebrew letters have intrinsic right-to-left directionality,
I had to type the word starting from the letter "ע",
i.e. <span xml:lang="he" dir="lro">עברית</span>.
id [not AVT]
An optional attribute of type xs:ID. Assigns an identity to the containing element; see the section on resolving IDs in XForms.
Note: Elements can be identified using any attribute of type ID (such as xml:id), not just the id attribute.
xml:lang
An optional specification of the natural language of the element content as defined in [Language Identification in XML].

Evaluation Attributes

The Evaluation Attribute Collection specifies the evaluation context for bindings. See Evaluation Context for details.

model [not AVT]
An optional Model selector. Specifies the ID of a Model to be associated with this element. This attribute is ignored if a bind attribute is also present. If a model attribute refers to something other than a model element, an xforms-binding-error is dispatched to the element with the attribute. Rules for determining the context Model are described in the section on Evaluation Context.
context
An optional expression used to override the default in-scope evaluation context for a binding or expression. This attribute has no meaning when a bind attribute is present. If the model attribute is present, then it is processed first. Processing is described in Evaluation Context.

Binding Attributes

These attributes bind an element such as a control to data, using a binding expression; such data values are referred to as bound values. Typically controls will bind to instance data nodes, but they can bind to any sort of item (such as atomic values like integer, date, or string atomic values). Atomic values always have the readonly property.

bind [not AVT]
Reference to the ID of a bind element. If there is no matching bind element, an xforms-binding-error is dispatched to the element that the bind attribute is on.
ref
Binding expression: ignored if a bind attribute is present.
nodeset (deprecated)
Synonym for the ref attribute: ignored if a ref attribute is present. In this specification, at any time the ref attribute is mentioned, it should be read to include nodeset where applicable.

In this specification, when an element is declared to have a (item or sequence) binding, then it is required unless the description for the element explicitly states that it is optional.

When a binding is required, one of ref or bind is required:

When a binding is defined as a Single Item Binding then the First-item rule is applied: if a binding selects a sequence of size greater than 1, the first item in the sequence is used.

When a binding is defined as being to simpleContent then this excludes binding to element nodes that have element children. See Implementation Requirements Common to All Controls for user interface processing rules common to all controls.

The binding attributes may be used in other XML vocabularies to bind custom user interface controls to instance data. As an example, the bind attribute might be used with XHTML 1.x user interface controls:

<html:input type="text" name="..." xforms:bind="fn"/>

The value and mediatype Attributes

The value attribute is used by elements to evaluate an expression; some elements that carry it also carry the mediatype attribute that indicates how to interpret the resulting value.

value
An expression. If the result is to be used as a string, then the result of the expression is processed as if by a call to the string conversion function as described in the expression module; an empty string is used if the evaluation fails. If the element has PCDATA content, then the result of the expression overrides that content.
mediatype
Optional string specifying the mediatype to use for interpreting the value, according to the format specified for the HTTP Accept: header in [RFC 2616]. It is the author's responsibility to ensure that the type specified is compatible with the value. The default is to treat the value as text.

Linking Attributes

The host language may permit a Linking Attributes Collection to be applied to XForms elements as an alternate means of obtaining content related to the element. An example is the src attribute from [XHTML 1.0]. The schedule by which link traversal occurs is defined by the host language. If the link traversal fails, the host language may dispatch xforms-link-error to the model associated with the element that bears the Linking Attributes Collection for the failed link.

Attribute Value Templates

All attributes except those that are already expressions and those that explicitly disallow AVTs can contain Attribute Value Templates.

An attribute value template consists of an alternating sequence of fixed parts and variable parts. A variable part consists of an expression enclosed in braces ({}). A fixed part may contain any characters, except that a left brace must be written as {{ and a right brace must be written as }}. An expression within a variable part may contain an unescaped brace within a StringLiteral or within a comment.

Adding attribute value template support to host language attributes is recommended, but should be defined in the host language integration specification.

AVT Evaluation

An attribute value template is evaluated by concatenating the evaluations of the fixed and variable parts:

  • a fixed part: any double brace ({{ or }}) is replaced by the corresponding single brace.
  • a variable part: the enclosed expression is evaluated as a string, using the element evaluation context.

An xforms-expression-error is dispatched to the element containing the expression in the following cases:

  • an unescaped left curly bracket appears in a fixed part, without a matching right curly bracket;
  • an unescaped right curly bracket occurs in a fixed part;
  • the expression contained between matching curly brackets is not syntactically correct;
  • a dynamic error occurs during the concatenation of the parts, for example if the sequence contains an element with a complex content type (which cannot be atomized).

Braces are not treated specially in attributes that cannot contain an attribute value template.

Attribute value templates are evaluated when necessary: on a control, they are evaluated on refresh; on an action, when it is executed.

Note:

The following non-normative list of attributes do not support AVTs: functions, schema and version on model; signature on function; src and resource on instance; type and p3ptype on bind; id.

<output ref="total" class="{if (. ge 0) then 'positive' else 'negative'}"/>
<load resource="/forms/detail/{instance('document-instance')/document/id}"/>

When <load> is executed, the resource attribute is evaluated. The result is the concatenation of /forms/detail/ and of the result of the expression within braces. If the id element pointed to contains the string C72E5, the resource attribute would take the value:

/forms/detail/C72E5

The Model

This module defines storing and describing the data to be used.

The elements and attributes included in this module are:

Element Attributes and Their Content (after AVT evaluation) Minimal Content Model

model

Common, functions (QNameList)[not AVT], schema (list of xs:anyURI)[not AVT], version (xforms:versionList)[not AVT]

(function | instance | xs:schema | submission | bind | Action)*

instance

Common, src (xs:anyURI)[not AVT], resource (xs:anyURI) [not AVT], response-mediatype (xs:string) [not AVT]

ANY

bind

Common, Evaluation, ref (model-binding-expression), nodeset (model-binding-expression [deprecated]), type (Type), constraint (Boolean expression), relevant (Boolean expression), required (Boolean expression), readonly (Boolean expression), calculate (Expression), whitespace ("preserve"* | "remove" | "trim" | "collapse" | "normalize"), p3ptype (String)

bind*

shared

Common, Single Item Binding?

Action*
function Common, Evaluation, signature[not AVT], override? (var*, result)?
result Common, Evaluation, value (expression) PCDATA
var Common, Evaluation, name (QName), value (expression) PCDATA

Elements defined in the Actions module are also allowed in the content model of model and submission, as shown above.

Within the containing document, these structural elements are typically not rendered.

Note that the presence of foreign namespaced elements is subject to the definition of the containing or compound document profile.

The model Element

This element is a container for the data to be used. There is no restriction on the number of model elements in a document.

Common Attributes: Common

Special Attributes:

functions [not AVT]
Optional space-separated list of extension functions (represented by QNames) required by this Model. Guidance on the use of this attribute is in the Extension Functions section.
schema [not AVT]
Optional list of xs:anyURI links to XML Schema documents outside this model element. The XForms Processor must process all XML Schemas listed in this attribute. Within each XForms Model, there is a limit of one XML Schema per namespace declaration, including inline and linked XML Schemas.
The XML Schema definitions for a namespace are determined to be applicable to instance nodes based on an instance XML Schema validation episode initialized to lax processing. When an element lacks an XML Schema declaration, the XML Schema specification defines as implementation-optional the recursive checking of children and attributes. For XForms, this recursive checking is required. XML Schema processing for a node with matching XML Schema declarations is governed by its content processing definition, which is strict by default.
Note: The schema list may include URI fragments referring to elements located outside the current model elsewhere in the containing document; e.g. "#myschema". xs:schema elements located inside the current model need not be listed.
version [not AVT]
Optional list of versions with a default value of empty string and legal values defined by the datatype xforms:versionList. Examples are "1.0", "1.1" and "1.1 2.0". On the default model, if one or more versions are indicated by this attribute then an XForms Processor must support at least one of the listed language versions of XForms; otherwise, the Processor dispatches the event xforms-version-error to the model. If the Processor supports more than one of the language versions indicated or if the version setting is empty, then the Processor must execute the XForms content using the highest conformance level available to it. If any non-default model has a version setting that is incompatible with the language version selected by the Processor, then the Processor dispatches the event xforms-version-error to the default model.

Content: (function | instance | xs:schema | submission | bind | Action)*

<model>
    <instance>
        <data xmlns="">
            <name/>
        </data>
    </instance>
</model>
<model id="Person" schema="MySchema.xsd">
  <instance resource="https://example.com/cgi-bin/get-instance"/>
</model>
<model>
  <message level="modal" ev:event="xforms-version-error">
    <output value="event('error-message')"/>
  </message>
  ...
</model>
...
<model id="m2" version="2.0">
  ...
</model>

Since the version attribute is not specified on the model, the XForms Processor may choose any language conformance level, which may be incompatible with the version setting of the second model. Therefore, the message action occurs during initialization of the second model due to its version incompatibility with the default model.

<model version="1.0 2.0">
  ...
</model>
...
<model id="m2">
  ...
</model>

Since the version attribute is not specified on the second model, it is compatible with any choice made based on the version setting on the default model.

The instance Element

This element contains instance data, which can be updated during processing.

Common Attributes: Common

Special Attributes:

src [not AVT]
Optional link to externally defined initial instance data.
resource [not AVT]
Optional link to externally defined initial instance data.
response-mediatype [not AVT]
Optional mediatype, used to override the mediatype reported by the external resource.

Content: ANY

The data for the instance is obtained from the link in the src attribute, if present and successful, otherwise from the inline content of the instance element if present, and otherwise from the link in the resource attribute.

The resulting document is converted to an XPath Data Model and associated with the instance element.

Processors must at all times keep the data consistent with the constraints imposed by the XPath Data Model. For instance, since consecutive text nodes are not permitted, if a text node is inserted as a sibling to another text node, or a comment node between two text nodes is deleted, the two text nodes must be concatenated into a single text node; similarly, since empty text nodes are not permitted, they must be removed.

Processors must preserve all data relevant to the XPath data model during processing and serialization, including processing instructions, comment nodes and whitespace.

Note: The difference between the src and resource attributes is the precedence over inline content, and that src uses the inline content as a fallback if the link fails.
<instance>
  <screen xmlns="">
    <height>1024</height>
    <width>1920</width>
  </screen>
</instance>
<instance resource="https://example.org/templates/a1.xml"/>
<instance resource="https://example.org/docs/letter.abw"
          response-mediatype="application/xml"/>
<instance resource="https://example.org/site/index.html
          response-mediatype="application/xhtml+xml"/>
<instance src="saveddata.xml">
  <game xmlns="">
     <score>0</score>
     <attempts>0</attempts>
  </game>
</instance>

Creating instance data from inline content

Instance data is obtained from inline content as follows:

  1. A detached copy of the single child element of the instance element is created and placed within a new document node. The copied element becomes the root element of a new XML document.
  2. Ancestor namespace nodes that are referenced by prefixes of elements and attributes in the instance data are copied to the detached root element. (Note that this is a change from previous versions of XForms, where all ancestor namespaces were copied.)

If creation of the XPath data model from inline content fails (for example because the instance element has more than one child element or none):

  1. The instance data is formed by creating an XPath data model consisting of a single document node without a root element.
  2. An xforms-link-error is dispatched to the relevant model element with a resource-uri indicating a fragment identifier URI reference (including the leading # mark) for an identified internal instance, or empty string for an unidentified internal instance. If the event is not canceled, processing halts (this is the default action for xforms-link-error). If the event is canceled, processing continues.
<xh:html
  xmlns:xh="http://www.w3.org/1999/xhtml"
  xmlns:xf="http://www.w3.org/2002/xforms"
  xmlns:foo="http://example.org/foo"
  xmlns:bar="http://example.org/bar">
  <xh:head>
    <xf:model>
      <xf:instance>
        <form>
          <first-name/>
        </form>
      </xf:instance>
    </xf:model>
  </xh:head>
</xh:html>

Resulting data model

<form>
  <first-name/>
</form>
<xh:html
  xmlns:xh="http://www.w3.org/1999/xhtml"
  xmlns:xf="http://www.w3.org/2002/xforms"
  xmlns:foo="http://example.org/foo"
  xmlns:bar="http://example.org/bar">
  <xh:head>
    <xf:model>
      <xf:instance>
        <form>
          <foo:first-name/>
          <last-name bar:baz=""/>
        </form>
      </xf:instance>
    </xf:model>
  </xh:head>
</xh:html>

Resulting data model

<form xmlns:foo="http://example.org/foo"
      xmlns:bar="http://example.org/bar">
  <foo:first-name/>
  <last-name bar:baz=""/>
</form>
<xh:html
  xmlns:xh="http://www.w3.org/1999/xhtml"
  xmlns:xf="http://www.w3.org/2002/xforms"
  xmlns:foo="http://example.org/foo"
  xmlns:bar="http://example.org/bar">
  <xh:head>
    <xf:model>
      <xf:instance>
        <form>
          <foo:bar xmlns:foo="http://dummy.org/foo"/>
        </form>
      </xf:instance>
    </xf:model>
  </xh:head>
</xh:html>

Resulting data model

<form>
  <foo:bar xmlns:foo="http://dummy.org/foo"/>
</form>
<xh:html
   xmlns:xh="http://www.w3.org/1999/xhtml"
   xmlns:xf="http://www.w3.org/2002/xforms"
   xmlns:foo="http://example.org/foo"
   xmlns:bar="http://example.org/bar">
  <xh:head>
    <xf:model>
      <xf:instance>
        <form xmlns:baz="http://example.org/baz">
          <expression value="foo:a/bar:b/baz:c"/>
        </form>
      </xf:instance>
    </xf:model>
  </xh:head>
</xh:html>

Resulting data model

<form xmlns:baz="http://example.org/baz">
  <expression value="foo:a/bar:b/baz:c"/>
</form>

In this case, if the namespace declarations are needed, they should be placed in the instance data:

<xh:html
   xmlns:xh="http://www.w3.org/1999/xhtml"
   xmlns:xf="http://www.w3.org/2002/xforms"
   xmlns:foo="http://example.org/foo"
   xmlns:bar="http://example.org/bar">
  <xh:head>
    <xf:model>
      <xf:instance>
        <form
           xmlns:foo="http://example.org/foo"
           xmlns:bar="http://example.org/bar"
           xmlns:baz="http://example.org/baz">
          <expression value="foo:a/bar:b/baz:c"/>
        </form>
      </xf:instance>
    </xf:model>
  </xh:head>
</xh:html>

Resulting data model

<form
   xmlns:foo="http://example.org/foo"
   xmlns:bar="http://example.org/bar"
   xmlns:baz="http://example.org/baz">
  <expression value="foo:a/bar:b/baz:c"/>
</form>

Creating instance data from external resources

Although inline instance values are created from XML markup, there is no requirement that external sources be XML, just that they be converted to an XPath Data Model internally.

If the external resource is not an XML format, it should be parsed as if a one-to-one mapping had been applied to the original to produce an equivalent XML document which is then used to produce the XPath Data Model. The one-to-one mapping is defined per format. Two format mappings are given below, but implementors are encouraged to add others, and report on their experiences.

A requirement on such a mapping is that it should only require simple and obvious XPath expressions to access the data. It is not necessary to be able to map all possible XML onto the external data type, but it is required to be able to map all possible values of the external data to XML, and then back again.

For every mediatype accepted for external sources by the processor, the processor must provide an equivalent serialization using the serialization attribute of the submission element.

If the link to the external data cannot be traversed, or it can be traversed, but an XPath data model cannot be created from the resource:

  • If the link is specified by the src attribute, and the instance has inline content, that inline content is used to create the instance data, and an xforms-submit-error with a resource-uri of the link that failed is dispatched to the containing model;
  • otherwise, the instance data is formed by creating an XPath data model consisting of a single document node without a root element, and an xforms-link-error with a resource-uri of the link that failed is dispatched to the containing model. If the event is not canceled, processing halts (this is the default action for xforms-link-error); if it is canceled, processing continues.

Otherwise the instance data is formed by creating an XPath data model of the linked resource as described below, and an xforms-submit-done with a resource-uri of the link is dispatched to the containing model.

The conversion of external data to an XPath data model is used both for initializing instances, and for processing the data returned by submissions.

External XML values

If the external resource is an XML format (i.e. with a content type matching any of the specifiers in [RFC 3023]), then an XPath data model is created as defined in [XDM].

External JSON values

If the external resource is a JSON value [JSON][Media Types], a root element <json/> is created whose content is the transformation of the JSON value. Each JSON value is treated as follows:

  • A number is copied across, and an attribute type="number" is added to its containing element.
  • true and false are copied across, and an attribute type="boolean" is added to its containing element.
  • null produces empty content, and an attribute type="null" is added to its containing element.
  • The content of a string is copied across. Escaped characters are transformed as necessary; characters and escapes that have no equivalent XML character (\b, \f, and characters of the form \uxxxx less than \u0020, except for \u0009, \u000A, and \u000D) are transformed by adding \uE000 to them.
  • An object is transformed by adding an attribute type="object" to its containing element, and transforming each of the object's members, if any.
    • Each name/value member is encoded as an XML element whose name is the name of the member, and whose content is the transformation of the value part of the member. If any character of the element name is not an allowable XML name character, or is ":", the character is replaced with an underscore "_"; if the first character of the element name is not an allowable XML name start character, or is ":", then an underscore "_" is prepended to the name. In either case, an attribute name is added to the element, with the value of the original name of the element, with characters treated as with strings.
  • A (non-anonymous) array is transformed by adding an attribute type="array" to its containing element, and transforming each of the array's elements, if any, each contained in an element called "_".
  • An anonymous array (either at the top level, or itself an element of an array), is transformed by creating an element with the name "_", and an attribute type="array", and then transforming each of the array's elements, if any, each contained in an element called "_".

This format can be serialized back to JSON with a submission element with a serialization attribute value of "application/json". Elements not in the default namespace and unknown attributes are ignored when serialising to JSON.

JSON Transformation Example selector
{"given": "Mark", "family": "Smith"}
<json type="object">
   <given>Mark</given>
   <family>Smith</family>
</json>
given
{"name": "Mark", "age": 21}
<json type="object">
   <name>Mark</name>
   <age type="number">21</age>
</json>
age
{"selected": true}
<json type="object">
   <selected type="boolean">true</selected>
</json>
selected
{"cities": ["Amsterdam", "Paris", "London"]}
<json type="object">
  <cities type="array">
    <_>Amsterdam</_>
    <_>Paris</_>
    <_>London</_>
  </cities>
</json>
cities/_[1]
{"load": [0.31, 0.33, 0.32]}
<json type="object">
  <load type="array">
    <_ type="number">0.31</_>
    <_ type="number">0.33</_>
    <_ type="number">0.32</_>
  </load>
</json>
load/_[1]
{"father": {"given": "Mark", "family": "Smith"}, "mother": {"given": "Mary", "family": "Smith"}}
<json type="object">
  <father type="object">
     <given>Mark</given>
     <family>Smith</family>
  </father>
  <mother type="object">
     <given>Mary</given>
     <family>Smith</family>
  </mother>
</json>
mother/given
{"p": null} <json type="object">

</json>

p
{"p": ""} <json type="object">

</json>

p
{"p": []} <json type="object">

</json>

p
{"p": {}} <json type="object">

</json>

p
{"$v": 0}
<json type="object">
   <_v name="$v" type="number">0</_v>
</json>
*[@name="$v"]
{"1": "one"}
<json type="object"><_1 name="1">one</_1></json>
*[@name="1"]
3
<json type="number">3</json>
.
"Disconnected"
<json>Disconnected</json>
.
["red", "green", "blue"]
<json type="array">
  <_>red</_>
  <_>green</_>
  <_>blue</_>
</json>
_[1]
{"g": [["a", "b", "c"], ["d", "e"]]}
<json type="object">
 <g type="array">
   <_ type="array">
     <_>a</_>
     <_>b</_>
     <_>c</_>
   </_>
   <_ type="array">
     <_>d</_>
     <_>e</_>
   </_>
 </g>
</json>
g/_[1]/_[1]
{}

<json type="object"/>

.
[]

<json type="array"/>

.
""

<json/>

.

Note that the mapping is designed to be round-trippable, to allow as natural as possible selectors, and to easily support structural additions and deletions; the type attributes are only necessary to distinguish ambiguous representations on serialization, and have no further effect on processing.

External CSV values

When an XForms Processor receives a CSV value [CSV], it treats it as follows:

  • A root element <csv/> is created whose content is the transformation of the CSV value.
  • If the first row of the external value contains labels (marked by the header parameter of the mediatype), then that row appears in the transformed content, enclosed by an <h> element. Each value of the headers row is enclosed by an element: if the value consists only XML name characters, that is the name of the element, otherwise non-matching characters are replaced by the underscore character "_"; if the first character may not start an XML name, an underscore is prepended.
  • Each (subsequent) row is enclosed in an <r> element.
  • If the first row of the external value contained labels, then each value of subsequent rows is surrounded by an element consisting of the transformed name from the respective header as defined above.
  • If the first row of the CSV value did not contain headers, then each value is surrounded by a <v> element.

This format can be serialized back to CSV with a submission element with a serialization attribute value of "text/csv", with optional charset and header parameters [CSV]. When no header parameter is supplied, it has the same effect as header=absent.

CSV Transformation
Year, Result
2011, 143
2012, 457
<csv>
  <r><Year>2011</Year><Result>143</Result></r>
  <r><Year>2012</Year><Result>457</Result></r>
</csv>
2011, "Jan, Mar"
2012, "Feb, Apr"
<csv>
  <r><v>2011</v><v>Jan, Mar</v></r>
  <r><v>2012</v><v>Feb, Apr</v></r>
</csv>
Name, Hex value
Red, #f00
Green, #0f0
Blue, #00f
<csv>
  <h><Name>Name</Name><Hex_value>Hex value</Hex_value></h>
  <r><Name>Red</Name><Hex_value>#f00</Hex_value></r>
  <r><Name>Green</Name><Hex_value>#0f0</Hex_value></r>
  <r><Name>Blue</Name><Hex_value>#00f</Hex_value></r>
</csv>
<repeat ref="r"><output ref="Name"/></repeat>
<output ref="r[1]/Year"/>
<input ref="r[1]/v[3]">...
<output ref="r[2]/Hex_value"/>
Other External values

No other types of external values are normatively defined in this specification; however implementors are encouraged to accept other types of values, and report on experiences for possible future inclusion. Transformations should be chosen to make selectors as natural as possible. As an example, a VCARD:

BEGIN:VCALENDAR
 METHOD:PUBLISH
 PRODID:-//Example/ExampleCalendarClient//EN
 VERSION:2.0
 BEGIN:VEVENT
 ORGANIZER:mailto:a@example.com
 DTSTART:19970701T200000Z
 DTSTAMP:19970611T190000Z
 SUMMARY:ST. PAUL SAINTS -VS- DULUTH-SUPERIOR DUKES
 UID:0981234-1234234-23@example.com
 END:VEVENT
 END:VCALENDAR

could be transformed to

<VCALENDAR>
   <METHOD>PUBLISH</METHOD>
   <PRODID>-//Example/ExampleCalendarClient//EN</PRODID>
   <VERSION>2.0</VERSION>
   <VEVENT>
     <ORGANIZER>mailto:a@example.com</ORGANIZER>
     <DTSTART>19970701T200000Z</DTSTART>
     <DTSTAMP>19970611T190000Z</DTSTAMP>
     <SUMMARY>ST. PAUL SAINTS -VS- DULUTH-SUPERIOR DUKES</SUMMARY>
     <UID>0981234-1234234-23@example.com</UID>
   </VEVENT>
 </VCALENDAR>

The bind Element

The bind element associates properties with values in instance data.

Common Attributes: Common, Evaluation

Special Attributes:

ref
Optional model binding expression that selects the items on which to operate. If the attribute is omitted, the default is the in-scope evaluation context.
nodeset [deprecated]
A synonym for ref. Ignored if attribute ref is present.
type [not AVT]
Optional type. Default is xf:string.
constraint
Optional boolean expression. Default is true.
relevant
Optional boolean expression. Default is true.
required
Optional boolean expression. Default is false.
readonly
Optional boolean expression. Default is false.
calculate
Optional expression. Default is no calculated expression.
whitespace
Optional string with allowable values "preserve", "remove", "trim", "collapse", and "normalize". Default is "preserve".
label
Optional text with no default.
hint
Optional text with no default.
help
Optional text with no default.
alert
Optional text with no default.
p3ptype [deprecated] [not AVT]
Optional string. Default is empty string.

Content: bind*

If the model attribute is used, and doesn't reference the parent model, an xforms-binding-error is dispatched to the bind element.

If the bind has a ref attribute, it is evaluated in the in-scope evaluation context to give a sequence of items; otherwise the in-scope evaluation context gives the sequence.

For each item in the sequence, model item properties are applied according to the remaining attributes on the bind element (see Model Item Properties for details).

When bind has an attribute of type xs:ID, that ID is associated with the selected sequence.

See Evaluation Context for details on how the evaluation context is determined for each attribute of the bind element.

<bind ref="today" type="date"/>
<bind ref="color" readonly="../variant='basic'"/>
<bind ref="state" required="../country='USA'"/>
<bind ref="state" relevant="../country='USA'"/>
<bind ref="total" calculate="../number * ../unitprice"/>
<bind ref="height" constraint=". > 0"/>
<bind ref="creditcard" whitespace="remove"/>
<bind ref="a" label="Age"/>
<bind ref="username" help="If you can't remember your username, call the help desk on extension 3000"/>
<bind ref="h" hint="height in centimeters"/>
<bind ref="i" type="integer" alert="must be a whole number"/>
<bind ref="c">
      <bind calculate="../a + ../b"/>
</bind>
<bind ref="c">
      <bind context=".." calculate="a + b"/>
</bind>
<bind ref="instance('admin')">
      <bind ref="submitted" type="boolean"/>
      <bind ref="finished" relevant="../submitted=true()"/>
</bind>
<bind ref="count">
      <bind type="integer" alert="must be a whole number"/>
      <bind constraint=". > 0" alert="must be greater than zero"/>
</bind>

Model Item Properties

Model item properties are properties bound to instance data nodes with the bind element. The combination of an instance data node and its properties is called a model item.

Some model item properties define inheritance rules, in which case the Processor combines the local value, which is applied from a bind element, with the inherited value, which is the combination of values from ancestor nodes in the instance data.

Some model item properties are computed: the processing model describes when and how the calculation is performed.

If Model Item Properties are attached to atomic values, or nodes that don't belong to an instance, an xforms-binding-error is dispatched to the element with the binding.

Most properties may be assigned multiple times to a node using different bind elements (for instance two binds to the same node, each specifying a constraint). However, an xforms-binding-error is dispatched to any bind that applies a calculate, whitespace or p3ptype property twice to the same node. Multiple bindings are combined so that all have to be true, or that at least one has to be true, according to the following table:

property combination
type all have to be true
constraint all have to be true
relevant all have to be true
required one has to be true
readonly one has to be true
calculate not allowed
whitespace not allowed
label not allowed
help not allowed
hint not allowed
alert one allowed per type and constraint
p3ptype not allowed
<bind ref="action" readonly="../status='accepted'"/>
<bind ref="action" readonly="../status='rejected'"/>

has the same effect as

<bind ref="action" readonly="../status='accepted' or ../status='rejected'"/>

The following sections list the model item properties available.

The type Property

This property associates a datatype with an instance node, contributing to the validity of a node.

Computed Expression: No.

Legal Values: An xs:QName.

Default Value: xf:string.

Inheritance Rules: does not inherit.

The value must reference a datatype (as defined in [XML Schema part 2]) defined in an applicable XML Schema, or an XForms predefined type. The datatype can be obtained from a simpleType definition or a simpleContent definition from a complexType. The namespace context of the bind element is used to resolve the namespace.

The datatype is associated with the node, as defined in XPath Data Model. It can be applied to both elements and attributes, but not to instance nodes that contain child elements.

Note: In XML Schema, an element can be made nillable. Although this means it can have empty content, nillable is defined by [XML Schema part 1] to be a property of an element, not a type. Therefore, it is not applicable to a type model item property.

<bind ref="count" type="integer"/>
<bind ref="today" type="date"/>
<model xmlns="http://www.w3.org/2002/xforms">
    <schema xmlns="http://www.w3.org/2001/XMLSchema">
       <simpleType name="PIN">
          <restriction base="xsd:string">
             <pattern value="[0-9]{4}"/>
          </restriction>
       </simpleType>
    </schema>

    <instance>
       <data xmlns="">
          <pin-code/>
       </data>
    </instance>

    <bind ref="pin-code" type="PIN"/>
 </model>
<model xmlns:ex="http://example.org">
 
   <schema targetNamespace="http://example.org" xmlns="http://www.w3.org/2001/XMLSchema">
     <simpleType name="Currency">
       <restriction base="xs:string">
         <enumeration value="USD"/>
         <enumeration value="EUR"/>
       </restriction>
     </simpleType>
 
     <complexType name="Price">
       <simpleContent>
         <extension base="xs:decimal">
           <attribute name="currency" type="ex:Currency" use="optional" default="USD"/>
         </extension>
       </simpleContent>
     </complexType>
   </schema>
 
   <instance>
     <data xmlns="http://example.org">
       <aString>Hello, world!</aString>
       <simpleType>
         <price>100.00</price>
         <price>abc</price>
         <price currency="EUR">100.00</price>
         <price currency="EUR">abc</price>
       </simpleType>
       <complexType>
         <price>100.00</price>
         <price>abc</price>
         <price currency="abc">100.00</price>
         <price currency="EUR">abc</price>
       </complexType>
     </data>
   </instance>
 
   <bind ref="ex:simpleType/ex:price" type="decimal"/>
   <bind ref="ex:complexType/ex:price" type="ex:Price"/>
   <bind ref="ex:complexType/ex:price[3]/@currency" type="ex:Currency"/>
 
 </model>

The readonly Property

This property describes whether the node content is restricted from changing.

Computed Expression: Yes.

Legal Values: Any boolean expression.

Default Value: false, unless a calculate property is specified for the content, then true.

Inheritance Rules: If any ancestor node of the bound node is readonly, this value is also readonly. Otherwise, the local value is used.

If the expression fails to evaluate, the property is set to true.

This property indicates whether changes are allowed to the content of the bound instance data node from constructs other than the model item property system (i.e. other than a calculate). Instance mutations performed by submission, controls, DOM interface access, and XForms actions must not insert or copy a new node into a parent node that is readonly, delete or replace a node whose parent is readonly, nor change the value or content of a readonly node. A node that is readonly but whose parent is not readonly can be entirely deleted or replaced by a submission even though doing so indirectly results in deletion or replacement of readonly descendant nodes.

Controls bound to readonly instance data do not receive input focus, and should indicate that entering or changing the value is not allowed. The readonly model item property does not affect visibility.

<instance>
  <person xmlns="">
    <name>Roland</name>
    <id>2015000123</id>
  </person>
</instance>
<bind ref="id" readonly="true()"/>
<bind ref="color" readonly="../version='basic'"/>

This example illustrates overriding the default readonly setting on calculated nodes.

<model>
  <instance>
    <data xmlns=""></data>
  </instance>
  <bind ref="/data" readonly="false()" calculate="choose(.='', 'default', .)"/>
<model>

The calculate is executed on any recalculate, including initialization, so the value is initially 'default'. If the user makes changes to the value, the calculate is re-evaluated, so that if an empty value is entered, data will be set back to 'default'.

The required Property

This property describes whether a value may be empty or not, contributing to the validity of a node.

Computed Expression: Yes.

Legal Values: Any boolean expression.

Default Value: false.

Inheritance Rules: does not inherit.

If the expression fails to evaluate, the property is set to true.

This property indicates whether the instance data node must be non-empty. A value is non-empty if it would have a length greater than zero if converted to string.

Controls bound to a required node should indicate that they are required. This property does not prevent controls and Actions from setting empty strings into data nodes, and has no defined effect on visibility, focus, or navigation order. Authors should ensure that controls bound to required data are visible.

<instance>
   <address xmlns="">
      <street/>
      <street2/>
      <city/>
      <state/>
      <country/>
   </address>
</instance>
<bind ref="street" required="true()"/>
<bind ref="city" required="true()"/>
<bind ref="state" required="../country='USA'"/>

Here, street2 and country are optional, and state is only required if country has the value 'USA'.

Note: XML Schema has a similarly named concept with use="required|optional|prohibited". This is different than the XForms Model item property, in two ways: 1) use applies only to attributes, while XForms required applies to any node, 2) use is concerned with whether the entire attribute must be specified (without regard to value), while required determines whether a value is required of the node before submission.

The XML Schema feature represented by nillable and xsi:nil is unrelated to the XForms required model item property. An element may have the xsi:nil attribute set to true to indicate that its empty content is schema valid, but if the required model item property for that element node is true, the element still has to be non-empty.

The relevant Property

This property indicates whether an instance node is available to the user interface and to submission.

Computed Expression: Yes.

Legal Values: Any boolean expression.

Default Value: true.

Inheritance Rules: If any ancestor node of the bound node is non-relevant, this value is also non-relevant. Otherwise, the local value is used.

If the expression fails to evaluate, the property is set to false.

This property indicates whether the instance data node is available for use by controls in the user interface and for submission. For instance, when paying by cash, a credit card number is not relevant.

Relevance affects visibility, focus, and navigation order of controls bound to a node: see the section on Availability for details.

Note: A control must have a Single Item Binding in order to be associated with an instance node. Due to the definition of repeat object, the relevant model item property of the node in the associated repeat item affects the availability of the repeat object.

<instance>
  <order xmlns="">
    <item>
      <amount/>
      <discount>10</discount>
    </item>
  </order>
</instance>
<bind ref="item/discount" readonly="true()" relevant="../amount > 1000"/>

This indicates that the discount is relevant only when the order amount is greater than 1000.

The calculate Property

Instance values may be computed from other values, for example, the sum of a series of values, or the amount of tax to be paid on an order. This property calculates a value for the associated node.

Computed Expression: Yes.

Legal Values: Any expression.

Default Value: none.

Inheritance Rules: does not inherit.

If the evaluation succeeds, the result is converted to string and stored as the value content of the associated data node. If the evaluation fails, the value content is set to the empty sequence.

<instance>
  <order xmlns="">
    <item>
      <amount/>
      <discount/>
    </item>
  </order>
</instance>
<bind
  ref="item/discount"
  calculate="../amount * 0.1"
  relevant="../amount > 1000"/>

Here, a discount of 10% is calculated when the order amount is greater than 1000.

The constraint Property

This property specifies extra validity conditions for instance data.

Computed Expression: Yes.

Legal Values: Any boolean expression.

Default Value: true.

Inheritance Rules: does not inherit.

If the expression fails to evaluate or evaluates to false, the associated data node is not valid (the converse is not necessarily true).

This property contributes to the validity of a node; the effect of validity on controls is described in the section on Implementation Requirements Common to All Controls. This property does not prevent controls and Actions from setting invalid values into data nodes.

<instance>
  <range xmlns="">
    <from/>
    <to/>
  </range>
</instance>
<bind ref="to" constraint=". > ../from"/>

This indicates that the value of to must be greater than that of from.

<bind ref="pin-code" constraint="matches(., '^\d{4}$')"/>

This checks if the value of pin-code matches 4 digits. This could also be done by writing a schema that defines a type that has the same effect (see The Type Property for the equivalent example).

<instance>
    <wishes xmlns="">
        <blank><wish/></blank>
    </wishes>
</instance>
<bind ref="wish" constraint="count(../wish) &lt; 4"/>
<repeat ref="wish">
    <input ref="." label="What is your wish?">
        <alert>You can't have more than 3 wishes!</alert>
    </input>
</repeat>
<trigger label="Make a wish">
    <insert ev:event="DOMActivate" ref="wish" origin="/wishes/blank/wish"/>
</trigger>

This makes all wishes invalid if there are more than 3. To make only the excess wishes invalid, you can use

<bind ref="wish" constraint="position() &lt; 4"/>

The whitespace Property

This property specifies how whitespace is treated when a node receives a new value.

Computed Expression: No.

Legal Values: preserve, remove, trim, collapse, normalize.

Default Value: preserve.

Inheritance Rules: does not inherit.

When a node receives a new value, this property controls how whitespace is treated:

preserve
all whitespace is preserved,
remove
all whitespace is removed,
trim
all whitespace from the beginning and end of the string is removed,
collapse
each occurrence of multiple whitespace is replaced with a single space character (0x20),
normalize
a combination of 'trim' and 'collapse'.

Whitespace is any character defined as whitespace ("WSpace=Y", "WS") in the Unicode Character Database [Unicode Character Database].

The whitespace property is processed during a recalculate.

<instance>
   <payment xmlns="">
      <amount/>
      <name/>
      <cardnumber/>
   </payment>
</instance>
<bind ref="amount" type="decimal"/>
<bind ref="name" whitespace="normalize"/>
<bind ref="cardnumber" type="card-number" constraint="is-card-number(.)"
      whitespace="remove"/>

Here, the whitespace properties indicate that when a value is input for name, the leading and trailing whitespace will be removed, and all other consecutive sequences of whitespace will be collapsed to a single space, and that if a credit card number is input with embedded whitespace, that whitespace will be removed. For the amount value, by default whitespace is preserved — however XML rules specify that leading and trailing whitespace does not affect validity of numbers: see the section on whitespace normalization during validation in [XML Schema Part 1].

The label Property

This property associates a label text with an instance data node. It may be expressed either with an attribute on bind or with a label element as a child of bind.

Computed Expression: No.

Legal Values: Any string.

Default Value: None.

Inheritance Rules: does not inherit.

Controls without a label element or attribute must make the label property text available to the user as part of the control. If a control has its own label element or attribute, that text is used instead.

<bind ref="p" label="Percentage"/>
<bind ref="co2">
    <label>CO<h:sub>2</h:sub></label>
</bind>

The help Property

This property associates a help text with an instance data node. It may be expressed either with an attribute on bind or with a help element as child of bind.

Computed Expression: No.

Legal Values: Any string.

Default Value: None.

Inheritance Rules: does not inherit.

Controls without a help element or attribute must make the help property text available to the user when requested. If a control has its own help element or attribute, that text is used instead.

<bind ref="cvv" label="Security Code" help="The 3-digit code on the back of your card is your CVV number/Card Security Code."/>
<bind ref="/login/password" label="Password">
  <help>Have you forgotten your password? Simply call 1-900-555-1212 and have
        a major credit card handy.</help>
</bind>

The hint Property

This property associates a hint text with an instance data node. It may be expressed either with an attribute on bind or with a hint element as child of bind.

Computed Expression: No.

Legal Values: Any string.

Default Value: None.

Inheritance Rules: does not inherit.

Controls without a hint element or attribute must make the hint property text available to the user when requested. If a control has its own hint element or attribute, that text is used instead.

<bind ref="creditcard" type="card-number" label="Credit card" constraint="is-card-number(.)"
      alert="Incorrect card number" hint="16 digits, spaces allowed" whitespace="remove"/>

<bind ref="expires" label="Expires" constraint="matches(., '^dd/0d|dd/1[12]$')" alert="Format must be YY/MM">
   <hint appearance="minimal">YY/MM</hint>
</bind>

The alert Property

This property associates an alert text with type and constraint properties of a binding. It may be expressed either with an attribute on bind or as an alert element as child of bind.

Computed Expression: No.

Legal Values: Any string.

Default Value: None.

Inheritance Rules: does not inherit.

This property associates an alert text with a type property or constraint property of a binding, or both.

A control bound to a node that fails to match its type and constraint properties must make an alert text available to the user: If the control has an alert element or attribute, that text is used; otherwise, if the type property or constraint that has failed has an alert property associated with it, that text is used; otherwise an implementation-dependent text may be used.

<bind ref="a" type="integer" alert="Must be an integer"/>
<bind ref="a" type="integer">
      <alert><h:strong>Must</h:strong> be an integer"</alert>
</bind> 
<bind ref="b" constraint=". ne 0" alert="May not be zero"/>

<bind ref="c" type="integer" constraint=". ge 0 and . le 100" alert="Must be an integer between 0 and 100"/>
<bind ref="c" label="Percentage" type="integer" alert="Must be integer">
     <bind constraint=". ge 0 and . le 100" alert="Must be between 0 and 100"/>
</bind>

<bind ref="c" label="Percentage" type="integer" alert="Must be integer">
     <bind constraint=". ge 0 and . le 100">
          <alert><h:strong>Must</h:strong> be between 0 and 100</alert>
     </bind>
</bind>
<bind ref="d" label="{instance('messages')/divisor}">
     <bind type="integer"      alert="{instance('messages')/integer}"/>
     <bind constraint=". ne 0" alert="{instance('messages')/zero}"/>
</bind>

<bind ref="birth" label="Year of birth" type="integer">
     <bind constraint=". ge 1900" alert="Year must be after 1900"/>
     <bind constraint=". le ../thisyear" alert="Year can be at most {../thisyear}"/>
</bind>

<bind ref="death" label="Year of death" type="integer">
     <bind constraint=". ge 1900"        alert="Year must be after 1900"/>
     <bind constraint=". le ../thisyear" alert="Year can be at most {../thisyear}"/>
     <bind constraint=". ge ../birth"    alert="Year of death must be after year of birth ({../birth})"/>
</bind>

<bind id="age" ref="age" label="Age at death" type="integer" calculate="../death-../birth">
     <bind constraint=". ge 0"   alert="Age must be greater than or equal to zero"/>
     <bind constraint=". lt 130" alert="No one has ever lived to be that age!"/>
</bind>

The p3ptype Property (Deprecated)

This property attaches a P3P data element, giving details on the specific kind of data collected.

Computed Expression: No.

Legal Values: xs:string.

Default Value: none

Inheritance Rules: does not inherit.

This property describes the kind of data collected in the associated instance data node, according to the P3P specification [P3P 1.0]. This information may be used to enhance interaction, for example by supplying previously-known data.

<instance>
  <name xmlns="">
    <first/>
    <second/>
  </name>
</instance>
<bind ref="first" p3ptype="user.name.given"/>
<bind ref="second" p3ptype="user.name.family"/>

The shared Element

Specifies the data to be shared by this form when embedded with a control element in another form, and allows communication with events between the two.

Common Attributes: Common, Single Item Binding (optional)

Special Attributes:

initial [not AVT]
Optional attribute specifying how the shared data must be initialized. Allowable values are "local" and "external". The default is "local".

Content: Action*

Data Binding Restrictions: This element can only be bound to a single element, of any type.

If this form is not embedded in another, this element has no effect.

If it is embedded, this element specifies which data element if any is to be shared and synchronised with the embedding form, and provides a communication point for use with the signal action.

If the element has a binding:

  • It is evaluated, and must evaluate to a single element, and the control element that caused the current form to be embedded must also have a binding that similarly evaluates to a single element, otherwise an xforms-binding-error is dispatched to the shared element.
  • If the element has an initial attribute that evaluates to external, the attributes and content including all children of the referenced element in the embedding form replace those of the referenced element in the embedded form,
  • otherwise, the attributes and content including all children of the referenced element in the embedded form replace those of the referenced element in the embedding form.
  • After initialisation, the referenced elements are kept synchronised: a change in one is reflected in a change in the other.

If the shared element does not have a binding, the control element used to embed the current form must not have a binding and no data is shared.

<shared ref="data"/>
<shared bind="sharing"/>
<shared ref="collection/a" initial="external"/>
<shared/>
<shared>
  <action ev:event="restart">
     <setvalue ref="score">0</setvalue>
  </action>
</shared>

Validity

An instance node is valid if

  • the value is empty and not required,

or

  • the value satisfies all applicable types, and all applicable constraint model item properties evaluate to true().

Applicable types include those associated by the type model item property, by an external or an inline XML Schema, and by xsi:type.

Validity affects the rendering of values, and submission; the effect of validity on controls is described in the section on Implementation Requirements Common to All Controls. It does not prevent controls and Actions from setting data nodes to values that do not match their types.

Model Processing

Model Initialization

The XML Schemas, if any, are loaded. If an error occurs while attempting to access or process a remote document, an xforms-link-error is dispatched to the model: if the event is canceled, processing continues as if the XML Schema had not been linked in the first place; otherwise processing halts (which is the default action for xforms-link-error).

If there are no instance elements, the data model is not constructed in this phase, but during user interface initialization (following the xforms-model-construct-done event); otherwise for each instance element an XPath data model is constructed as described in The instance Element section.

If applicable, P3P initialization occurs. [P3P 1.0]

An update is then done for this model. (A refresh is not performed since the user interface has not yet been initialized.)

User Interface Initialization

After all models have been initialized, the controls in the user interface are connected to the data in the models.

For very simple cases, no explicit instance is needed: an instance is created from the bindings on the controls.

For each control:

  • The user interface for the control is created.
  • If necessary, an instance data node is created for the control.
  • If the control has a binding, it is evaluated; if the result is an empty sequence then the control is initially disabled; if the result is an atomic value, the control is initially readonly.
  • The control is initialized with its value and model item properties (valid, required, readonly and relevant).
  • For a repeat, it is initialized as described in repeat initialization.

An instance data node is created if the binding on the control is just a name and either no instance exists for that binding, or the instance that exists is an automatically created one from this rule, but has no matching instance data node:

  • If no instance exists, one is created with a root element called instanceData with no namespace.
  • An instance data element node is created using the binding expression from the control as the name.
 <model>
    <submission resource="http://example.com/search"/>
 </model>
 ...
 <input ref="q" label="Find"/>
 <input ref="n" label="Number of results"/>
 <submit label="Go"/>

This will create an instance

<instance><instanceData xmlns=""><q/><n/>/instanceData></instance>

Dependencies

As a result of bindings within a model, instance values can depend on each other in various ways; for instance, a value may by calculated from other values with a calculate property, or may be constrained by other values using a constraint property.

At fixed points during processing, if the structure of an instance has changed (due to insert or delete actions, or being replaced after a submit), or values within an instance have changed, the model is updated.

An update may involve as necessary a rebuild of dependencies if the structure has changed, a recalculate of new values of dependent items, and a revalidate, to check the validity of the new values.

An update is followed by a refresh of the user interface with the new values.

Note that updates are triggered by a change to a value or structure within an instance; this means that values that only depend on values external to the model are not automatically updated when the external values change. In particular functions without parameters such as index(), case(), and now() do not trigger a recalculate when their values change. For index it is preferable to use the indexref attribute on repeat and for case the ref attribute on select.

Although some processes in this specification are described as if all expressions in a model or the user interface are re-evaluated every time there is a change, implementations are of course at liberty to optimize this, as long as the result is the same.

Although rebuild, recalculate, revalidate, and refresh are described as separate steps, since they always occur in sequence, implementations are at liberty to combine them into a lesser number of steps.

An expression references a node of instance data if the node is selected during the evaluation of the expression, even if it is subsequently excluded from further participation in the expression evaluation (for example by a filter expression). (The selection mechanism is defined in the expression module.)

A computed expression is dependent on an instance node if it references it and uses its character content (rather than just referencing for navigation); any other expression is dependent on an instance node if it just references it.

Consider the following expression:

continent[@name='Europe']/country[@name='France']/capital

applied to the following instance:

<instance>
   <data xmlns="">
      <continent name="Europe">
         <country name="UK">
            <capital>London</capital>
         </country>
         <area>10</area>
      </continent>
      <continent name="Asia">
         <country name="Japan">
            <capital>Tokyo</capital>
         </country>
         <area>45</area>
      </continent>
   </data>
</instance>

Both continent elements are referenced since both are matched, and the name attribute on each is referenced during the evaluation of the filter. The filter rejects the second continent element, but the element and its attribute have still been referenced.

The country element in the first continent is referenced, but not the one in the second continent since expression evaluation did not proceed beyond the filter expression that rejected the second continent element.

While performing the test for element country, observe that the expression evaluator may visit all the children of the first continent element. However, an element is not referenced if it is only visited but fails the test. In this case, the test is for country, which the area element fails. Therefore, area is not referenced.

The filter expression test on country rejects the only country element that has been selected so far because the attribute value of name does not match. Still, country and its attribute name have been referenced by this expression.

Element capital is not considered to be referenced by this expression. Although a test for capital appears in the expression, the evaluation of the expression did not proceed due to the rejection of country by the filter expression.

Finally, note that an expression can reference many nodes even if its final result is the empty sequence (as in this case).

Consider the following example:

<model>
  <instance>
    <data xmlns="">
      <continent name="Europe">
        <country name="UK">
          <capital>London</capital>
        </country>
        <area>10</area>
      </continent>
      <continent name="Asia">
        <country name="Japan">
          <capital>Tokyo</capital>
        </country>
        <area>45</area>
      </continent>
      <selected-country>UK</selected-country>
    </data>
  </instance>

  <bind
    ref="selected-country"
    id="selected-country"/>

  <bind
    ref="continent/country"
    id="all-countries"/>

  <bind
    ref="continent/country[@name = ../../selected-country]"
    id="current-country"/>

</model>

 <select1 bind="selected-country" label="Select country">
  <itemset bind="all-countries" label="{@name}" value="@name"/>
  <rebuild ev:event="xforms-value-changed"/>
</select1>

<group bind="current-country" label="Country details">
  <output ref="@name" label="Country name"/>
  <output ref="capital" label="Country capital"/>
</group>

When the user changes the value of the selection control, the expectation is that the information relative to the selected country shows below.

However, the current-country bind does not refresh upon the selection control's change of value. This means that the form doesn't behave as intuitively expected. In order to fix this, an explicit rebuild action runs when the value of the control changes. Subsequently, all model binds are up to date, and when the user interface refreshes the correct country details show.

Updates

Updates of a model are done after a user or action handler has caused a change to an instance.

Updates are not done while an action handler is being processed, but only after the termination of the outermost action handler.

An outermost action handler is an action that is activated when the Processor is not executing any other action handlers.

An inner action handler is an action that is activated while the Processor is already executing an 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 by an action handler.

Note:

Since the Processor is not executing an outermost action handler at the time that it performs an update, event handlers for events dispatched during the resulting refresh are new outermost action handlers.

Since some XForms actions require the model to be in a consistent state either before or after their processing, they ensure that the model is up-to-date at the appropriate moment. These points are described in the relevant descriptions of the actions.

Rebuild

A rebuild considers each bind element in the model, re-computes the model item properties, rebuilds the implicit computational dependency structures, and prepares for a full recalculate.

Recalculate

All computed expressions in the model are identified:

  • An expression is bound either to the value or to a model item property of one or more instance nodes; each combination of an expression with a single instance node's value or model item property is considered as a single computational unit, a compute, for the purposes of recalculation.
  • A compute may reference (or refer to) an instance node, in which case the value of the instance node is referenced.
  • All computes that directly reference an instance node are its dependants; excluded are references to the current node's value in calculate expressions (such an instance node does not take itself as a dependent).
  • A compute is computationally dependent on an instance node if there is a path of dependants leading from the instance node through zero or more other instance nodes to the compute.
  • A compute is part of a circular dependency if it is computationally dependent on itself through a series of calculate expressions.

At the start of a recalculate, there is a, possibly empty, list L of instance nodes whose values may have been changed, e.g., by user input or by a setvalue action.

  • All nodes in L, if any, and nodes that are computationally dependent on nodes in L must be recalculated.
  • Only a single recalculation of each compute that is computationally dependent on elements in L may be performed.
  • A compute must be recalculated before any computes that are computationally dependent on the instance node associated with it.
  • If a compute is computationally dependent on an element in L and part of a circular dependency, then an xforms-compute-error must be dispatched to the model element.

When a compute is recalculated, the expression is evaluated using the evaluation context of the model binding expression that the compute comes from, as defined for computed expressions in Evaluation Context.

If any node value changes as a result of a calculate constraint, and if the resulting node has a whitespace property, that property must be immediately applied to the value.

Note: The Recalculation Sequence Algorithm describes one possible method for achieving the recalculation behavior.

Note: Referring to a node's value in a calculate on the node, as in the following example, may have effects that vary by implementation: <bind ref="x" calculate=".+1"/>. Model item properties other than calculate, such as required or readonly are well-defined in the presence of self-references.

Note: An example of a calculate formula that contains a self-reference (i.e. that refers to the node it calculates) appears in Section The readonly Property. The example enforces a default value for a node and, as mentioned above, does not create a circular dependency. An example of a circular dependency is <bind ref="A|B" calculate="../A + ../B"/>. In this example, node A depends in part on B, and node B depends in part on A.

Revalidate

All instance data nodes in all instance elements in the model are checked for validity.

Update

All instance data nodes in all instance elements in the model are updated by doing a rebuild, recalculate, and revalidate as necessary.

Refresh

All UI Expressions are re-evaluated as necessary, and the user interface is updated to reflect the state of the model, including:

  • current values,
  • model item properties: validity, relevance, read-write, and requiredness,
  • the proper number of, and content for, repeat objects and itemset items.

Notification events are dispatched, in no defined order:

  • If a bound value has become non-relevant since the last refresh, the xforms-disabled event is dispatched to the value's bound controls; if a bound value has become relevant, the xforms-enabled event is dispatched.
  • If a bound value has changed since the last refresh, then the xforms-value-changed event is dispatched to the value's enabled bound controls.
  • If any other model item properties of a bound value have changed since the last refresh, the appropriate notification events (xforms-optional/xforms-required, xforms-readwrite/xforms-readonly, xforms-valid/xforms-invalid) are dispatched to the value's enabled bound controls.
  • The events xforms-out-of-range and xforms-in-range must also be dispatched as appropriate to enabled controls.

Finally an xforms-refresh-done event is dispatched to the default model.

Expressions

Expressions appear in attributes throughout XForms. They can be split into two kinds:

  • bindings, that identify locations whose content may or may not be changed by the attached element; and
  • value expressions, that supply values for use by the attached element.

They can further be classified according to when they are evaluated:

  • on bind elements (where bindings are called model item bindings, and other expressions are called computed expressions): evaluated during model initialization and recalculate;
  • on controls and their contained elements excluding Actions (where bindings are called UI bindings, and all expressions including bindings are called UI expressions): evaluated during user interface initialization and refresh;
  • on Actions and the submission element: evaluated on activation by an event;
  • in Attribute Value Templates (AVTs): evaluated whenever the containing element is processed.

At the time of evaluation, an expression must be syntactically correct, the namespaces it uses must be in scope, and the functions and variables it uses must be defined; otherwise one of the following events is dispatched:

If the evaluation of an expression fails, for whatever reason, including type errors:

  • for a calculate expression, the result is the empty sequence;
  • for other bind computed expressions (which are all boolean valued), the result is the opposite of the default for that property;
  • for all other expressions, an xforms-expression-error is dispatched to the element containing the expression.
Note: To allow for forward compatibility, this specification is written to permit the use of different expression languages. However only one is used in XForms 2.0, XPath 2.0 as defined in XForms 2.0: XPath Expressions Module.

Typed Values

Types in XForms are principally used to check the validity of strings provided as values to nodes; however, the types can also be used when evaluating expressions using nodes.

The XForms processor should therefore provide the typed values of nodes to the expression evaluator, and not just the strings. This includes expressions evaluated during a recalculate, even though a revalidate has not yet occurred.

When the result of evaluating an expression is described as being converted to some type, this is done as described in the expression module.

This example illustrates the difference between evaluating with and without types. If the typed values are passed, then the two times 00:00:00 and 24:00:00 are recognized as being equal. However, if the two values are just passed as strings, they are not found to be equal.

<model>
    <instance>
       <data xmlns="">
          <t>00:00:00</t>
          <t>24:00:00</t>
       </data>
    </instance>
    <bind ref="t" type="time"/>
 </model>
 
 <output value="choose(t[1] = t[2], 'typed', 'untyped')"/>

Evaluation Context

All expressions are evaluated in an evaluation context, which consists of a context item, a size, and a position. In general, the context item is some element of a sequence, the size is the size of that sequence, and the position is the position of the context item within the sequence.

Initial evaluation context

An element inherits an initial evaluation context from its ancestor elements; if the element has a model attribute, and the inherited context item is not from that model, then the initial evaluation context is the default context from the referenced model.

For elements with no ancestor, the initial evaluation context is the default context item of the element's default model, with a size and position of one:

  • the default model for an element is its containing model, if any, and otherwise the textually first model in the document;
  • the default context item of a model is the top-level document element node of the textually first instance of the model.

In-scope evaluation context

If the element has a context attribute, that attribute is evaluated in the initial evaluation context, giving the in-scope evaluation context; otherwise the initial evaluation context is used for the in-scope evaluation context.

Element evaluation context

Unless otherwise stated, all expressions (including those in AVTs) in an element are evaluated in the element evaluation context:

  • if the element has no binding, the in-scope evaluation context is used for the element evaluation context;
  • if the element has a ref attribute, the attribute is evaluated in the in-scope context to give the element evaluation context;
  • if it has a bind attribute, the element evaluation context of the referenced bind element is used.

If a binding is declared as a Single Item Binding, the size of the context and its position are both set to 1; otherwise it is a Sequence Binding, and uses the evaluated size and position.

For sequence bindings, an occurrence of the original binding element is also generated for each of the items in the sequence, with a dynamic evaluation context that has a context item of the item of the sequence for which the occurrence was generated, a size of the size of the sequence, and a position of the position of the generated item in the sequence.

The element evaluation context is then inherited by any contained elements as their initial evaluation context.

Note: the context() function returns the context item of an element's in-scope evaluation context, while the position() and last() functions return the context position and size respectively of the element evaluation context, and the dot selector "." returns its context item.

So the following would output 2 1 2 3:

<instance>
    <data xmlns="">
       <a><b>1</b</a>
       <b>2</b>
       <b>3</b>
    </data>
</instance>
 ...
<output         value="b"/> ⇒ 2
<output ref="a" value="b"/> ⇒ 1
<output ref="a" value="context()/b"/> ⇒ 2
<output         value="b[last()]"/> ⇒ 3
<model id="m">
    <instance>
       <data xmlns="">
          <a>1</a>
       </data>
    </instance>
 </model>
 <model id="n">
    <instance>
       <data xmlns="">
          <a>2</a>
          <a>3</a>
          <b>4</b>
       </data>
    </instance>
 </model>
 <model id="p">
    <instance>
       <data xmlns="">
          <a><b>5</b></a>
          <b>6</b>
       </data>
    </instance>
</model>
<output ref="a"/> ⇒ 1
<output model="n" ref="a"/> ⇒ 2
<output model="p" ref="a" value="b"/> ⇒ 5
<output model="p"         value="b"/> ⇒ 6
<group model="p" ref="a">
   <output ref="b"/> ⇒ 5
</group>
<group model="p" ref="a">
   <output context=".." ref="b"/> ⇒ 6
</group>
<group model="p">
   <output ref="b"/> ⇒ 6
</group>
<group model="p">
   <output model="n" ref="b"/> ⇒ 4
</group>

Functions

The extra functions available in expressions above those available from XPath are described in the XPath Expressions Module. The list here gives an overview.

Math functions

double avg(node()*)
The arithmetic average of the nodes.

double min(node()*)
Minimum (numeric) value.

double max(node()*)
Maximum (numeric) value.

double power($base as double, $exponent as double)
The first argument raised to the power of the second.

double random(boolean?)
A uniformly distributed pseudorandom number ≥ 0.0 and < 1.0.

String functions

integer compare(string, string)
Lexicographic comparison of the two Unicode strings, returning -1 (less than), 0 (equal) or +1 (greater than).

Card Number functions

boolean is-card-number(string?)
Whether the string (or context item if absent) is a valid (credit-card) number.

Date and time functions

date local-date()
The current date in the user agent time zone.

dateTime local-dateTime()
The current date and time in the user agent time zone.

string now()
The current date and time in UTC.

numeric days-from-date(string)
Number of days since 1970 of the given date.

string days-to-date(double)
The date of those number of days since 1970.

double seconds-from-epoch(string)
double seconds-from-dateTime(string)
The number of seconds since 1970 of the given date and time. The seconds-from-dateTime function is only for backwards compatibility: use seconds-from-epoch for preference.

string seconds-to-dateTime(double)
The date and time of that many seconds since 1970.

string adjust-dateTime-to-timezone(string)
Takes a date and time (possibly in a different timezone) and returns it adjusted to the local timezone.

numeric seconds(string)
Returns a duration of days, hours, minutes and seconds as the number of seconds.

numeric months(string)
Returns a duration of years and months as the number of months.

URI functions

anyURI location-uri()
The URI from which the current document has been loaded.

string* location-param(string)
The current location URL's parameter values for the given name.

string? uri-scheme(string)
string? uri-scheme-specific-part(string, boolean)
string? uri-authority(string, boolean)
string? uri-user-info(string, boolean)
string? uri-host(string)
integer? uri-port(string)
string? uri-path(string, boolean)
string? uri-query(string, boolean)
string? uri-fragment(string, boolean)
Returns the respective sub-part of the given URI.

string* uri-param-names(string)
The names of the parameters used in the given URI.

string* uri-param-values(string, string)
The value(s) in the given URI of the given parameter name.

Utility functions

item() current()
The current context item.

item() context(string?)
The current in-scope evaluation context item.

boolean boolean-from-string(string)
"true" and "1" return true, all other strings return false.

integer count-non-empty(node()*)
The number of non-empty nodes.

item()* eval(string)
Evaluates the string as an expression in the current context.

item()* eval-in-context(string, node()*)
Evaluates the string as an expression in the given context.

item()* choose(boolean, item()*, item()*)
If the first parameter is true, returns the second parameter, and otherwise the third. [Deprecated]

Cryptographic functions

string digest($data as string, $algo as string, $encoding as string?)
The hash value of the data string.

string hmac($secret as string, $data as string, $algo as string, $encoding as string?)
A cryptographic encoding of the data string.

Model functions

element()? instance(string?)
The identified instance data.

node()* bind(string)
The nodes associated with the identified bind element.

boolean valid(item*?)
boolean valid(item*, boolean, boolean?)
Whether the selected items are valid. By default recurses through the elements, and non-relevant items are ignored. The boolenas control this default.

boolean relevant(item*?)
boolean readonly(item*?)
boolean required(item*?)
Whether the selected items are, respectively, relevant, read-only, or required.

Controls functions

numeric index(string)
The value of the repeat index for the identified repeat.

string? case(string)
Returns the ID of the selected case for the identified switch.

Event functions

item()* event(string)
Returns the specified context information of the current event.

string? property(string)
Returns details of the implementation.

XML manipulation functions

element() element($qname as anyAtomicType, $content as item()*)
Constructs an element from string values.

attribute() attribute($qname as anyAtomicType, $value as anyAtomicType?)
Constructs an attribute.

element()? parse(string, string?)
Parses a string, and returns the resulting node.

string serialize(item*, $params?)
String serialization of the items. [NOTE: same as XPath 3.0]

element()* id(string*, node()*?)
element()* id(node()*, node()*?)
The elements in the given data identified by the given IDs. [Deprecated]

Extension Functions

XForms documents may use additional functions beyond those defined in the document and by the expression language. A number of useful community extensions are defined at [EXSLT].

The names of any extension functions used in a document should be declared in the functions attribute on the model element. When the document is loaded the processor must check that those functions are available. If any are not, an xforms-compute-error must be dispatched to the model element. If that event is not canceled, processing halts (this is the default action for xforms-compute-error). If the event is canceled, processing continues.

If an expression uses an extension function for which the processor does not have an implementation, on evaluation an appropriate event (xforms-expression-error, xforms-binding-error, or xforms-action-error) must be dispatched to the containing element.

<model functions="math:sin">
   <instance>
      <data xmlns="">
         <length/>
         <angle/>
         <height/>
      </data>
   </instance>
   <bind ref="length | angle | height" type="double"/>
   <bind ref="height" calculate="../length * math:sin(../angle)"/>
</model>

The var element

The var element declares a local variable. A variable is a mapping between a name and a value. The value of a variable is any sequence of nodes and/or atomic values, as defined in the XPath Data Model [XDM].

Common Attributes: Common, Evaluation, value

Special Attributes:

name
Required attribute containing the name of the variable. The value of the name attribute is a QName. The scope of the variable is defined in the Variable Scope section below.

Content: PCDATA

A value is obtained by evaluating the value attribute if present, and otherwise from the inline text. The result is made available as a variable to expressions for which the variable is in scope.

A variable can occur either as a child of an action element or anywhere a control can appear.

Note:

Variables under the model element are not supported except within nested action elements. Behavior for such variables may be specified in the future based on implementation experience.

Variable Evaluation

If a variable is a child of an action element, its value is updated after the previous child action or variable has been invoked or evaluated, and before the following child action or variable is invoked or evaluated. Such a variable is evaluated exactly once for each execution of the content of the action element.

Note:

This means that if the action is repeated with the iterate or while attribute, the variable is re-evaluated as well during each execution.

Variables outside of actions behave as if they are updated by refresh in the order they are defined.

Note:

A variable holds references to all the nodes the value expression returns (if any). Deleting nodes from an instance with a delete action does not remove those nodes from the value of the variable until the variable is re-evaluated. Similarly, changes to predicates of the value expression by actions don't update the value of the variable.

Variable Scope

For any variable, there is a region (more specifically, a set of element nodes) of the form within which the variable is visible. The set of variables in scope for an expression consists of those variables that are visible at the point in the form where the expression occurs.

Variable scoping is lexical: a variable defined by a var element is visible for all following sibling nodes and their descendants. The variable is not visible for the var element itself.

Variable shadowing is not allowed: if a variable is declared with a name that is already in scope at the point of the new variable declaration, an xforms-binding-error is dispatched to the var element.

Note:

This is unlike XSLT, which discourages but allows shadowing.

<trigger label="Show">
  <action ev:event="DOMActivate">
    
    <message ref="$message"/>
  </action>
</trigger>

<trigger label="Show">
  <message ev:event="DOMActivate" ref="$message"/>
</trigger>
<action iterate="items/item">
  
  <insert context="$current-item" origin="xforms:element('label'), xforms:element('value')"/>
</action>

<input ref="$binding" label="Quantity"/>

<select ref="my-item" label="Item">
  <itemset ref="$items" label="{name}" value="value"/>
</select>
<var name="message">Your document has been saved.</var>


<group>
  
  
  
  <output value="$page-count" label="Number of pages"/>
</group>

The function Element

Defines a function that can be called from any expression within the document that is associated with the model in which the function is defined.

Common Attributes: Common, Evaluation

Special Attributes:

signature [not AVT]
The signature (name, parameters and return type) of the function.
override
Optional string specifying if this function overrides previously declared functions. Allowable values are true and false, with a default of true.
type
Optional MIME type specifying the implementation language of the function. The default is the default expression language of the form. Other supported languages are implementation-dependent. The function definition is ignored if the language is not supported or if the function element contains mixed content.

Content: (var*, result)?

A function element can only appear as a top-level element in a model.

Note: The Working Group is considering allowing the definition of custom functions outside of the model in a future version of the specification, but is waiting for implementation experience first.

A custom function is included in the in-scope functions of the static context for all expressions associated with the model that contains the function definition, unless

  • the override attribute has the value "no" and there is already a function with the same name and arity in the in-scope functions.
  • the custom function tries to override a built-in function.

The value of the signature attribute defines the name, parameters and return type of the function. See Function signature syntax for more information about the function signature.

The function that is executed as the result of a function call is identified by searching the in-scope functions of the static context for a function whose name and arity match those of the function call.

Note: Functions are not polymorphic. Although the function call mechanism allows two functions to have the same name and different arity, it does not allow them to be distinguished by the types of their arguments.

The result of a function is a sequence of atomic values and/or nodes. If the result type of the function is specified with the as attribute, the result value of the function as specified by the function body is converted to the required type (specified using a SequenceType, as defined in XPath 2.0), using the function conversion rules. It is a type error if this conversion fails. If the as attribute is omitted, the calculated result is used as supplied, and no conversion takes place.

<function signature="my:sumproduct($p as xs:decimal*, $q as xs:decimal*) as xs:decimal">
  sum(for $i in 1 to count($p) return $p[$i]*$q[$i])
</function>
<function signature="my:fibonacci($n as xs:integer) as xs:integer">
  <var name="sqrt5" value="math:sqrt(5)"
  <result value="(math:power(1+$sqrt5, $n) - math:power(1-$sqrt5, $n)) div (math:power(2, $n) * $sqrt5)"/>
</function>
<function signature="my:summation($p as xs:decimal*) as xs:decimal" override="no" type="text/javascript">
  ...
</function>
<function signature="my:summation($p as xs:decimal*) as xs:decimal" override="no">
  sum($p)
</function>

The second definition of the my:summation function doesn't override the first definition because the override attribute is set to no (even though the expanded QName and the arity of the functions are the same).

Function signature syntax

The signature attribute of the function element has the following syntax:

CustomFunctionSignature ::= FunctionName "(" ParamList? ")" ("as" SequenceType)?
FunctionName ::= PrefixedName
ParamList ::= Param ("," Param)*
Param ::= "$" QName TypeDeclaration?
TypeDeclaration ::= "as" SequenceType

The function name is a QName but not an NCName. This means that a form author cannot add functions to the default function namespace.

The parameter list defines the formal arguments to the function. When the function is called using a function call in an expression, the first argument supplied is assigned to the first parameter, the second argument supplied is assigned to the second parameter, and so on.

The type declaration defines the required type of the parameter. The rules for converting the values of the actual arguments supplied in the function call to the types required by each parameter are defined in [XPath 2.0]. The rules that apply are those for the case where XPath 1.0 compatibility mode is set to false.

If the value of a parameter to a custom function cannot be converted to the required type, a type error is signaled.

If the type declaration is omitted, no conversion takes place and any value is accepted.

[ERR] It is a static error if two parameters of a custom function have the same name.

Note:

Optional parameters are not allowed.

my:foo() as xs:integer
my:sumproduct($p as xs:decimal*, $q as xs:decimal*) as xs:decimal

Function body

The function body contains the implementation of the function as text content, following the syntax of the function's implementation language.

Alternatively, when the function's implementation language is the same as the expression language of the form, the function body can be specified with an optional sequence of var elements followed by a single result element specifying the function's result.

Note: This in particular allows writing more readable custom functions with XPath 1.0 and XPath 2.0, which do not natively support variables.

The implementation of the function should be stable (calling the same function twice within an execution scope with the same arguments returns the same result) and should not change any instance data, nor should it change the internal state of the form (e.g.: should not change the repeat index) or processor.

Function body evaluation context

Within the body of a custom function, the evaluation focus is initially undefined; this means that any attempt to reference the context item, context position, or context size is a non-recoverable dynamic error ([err:XPDY0002] as defined in XPath 2.0)

The variables in scope for the function body include all variables representing the function parameters, as well as all variables that are in scope where the custom function is defined.

Note: Function parameter names can shadow variables that would otherwise be in scope for the function body.

Expressions within the function body may refer to instance data by using the instance() function.

Any static or dynamic error occurring while evaluating the value of a var element within the body element propagates to the expression calling the function.

The result element

The optional result element is used inside a function element to produce the result of the function.

Common Attributes: Common, Evaluation, value

Content: PCDATA

If any var element is present under the function element, this element is required. Otherwise, it is optional.

A value is obtained by evaluating the value attribute if present, and otherwise from the inline text; this is used as the result of the function.

Any static or dynamic error occurring while evaluating the value attribute propagates to the expression calling the function.

Datatypes

This section defines the standard datatypes available. They are in-scope without the inclusion of an XML Schema.

XML Schema Built-in Types

All XML Schema 1.0 datatypes are supported except for xs:ENTITY, xs:ENTITIES, and xs:NOTATION. The concepts of value space, lexical space and constraining facets are as specified in [XML Schema part 2].

XForms Datatypes

The following types are defined in the XForms namespace. They can be used without a namespace prefix when the XForms namespace is the default.

Built-in primitive and derived types

For ease of authoring, the following XForms types are defined as having a lexical space identical to the corresponding XML Schema datatype.

Built-in primitive types:

string, boolean, decimal, double, float, date, time, dateTime, duration, dayTimeDuration, yearMonthDuration, QName, anyURI, gDay, gMonthDay, gMonth, gYearMonth, gYear, base64Binary, hexBinary

Built-in derived types:

integer, nonPositiveInteger, negativeInteger, long, int, short, byte, nonNegativeInteger, unsignedLong, unsignedInt, unsignedShort, unsignedByte, positiveInteger, normalizedString, token, language, Name, NCName, ID, IDREF, IDREFS, NMTOKEN, NMTOKENS

Note:

Type duration does not support a total ordering. Using dayTimeDuration or yearMonthDuration is preferable.

Absolute IRI type

This type represents an absolute IRI, a subset of IRI as defined in [RFC 3987]

The type is defined as the following lexical space (the pattern has been split over lines for slightly improved readability, but should be a single line):

<xs:simpleType name="absoluteIRI">
  <xs:restriction base="xs:string">
    <pattern value="[a-zA-Z][a-zA-Z0-9\+\.\-]*://
                    ((%[0-9A-F][0-9A-F]|[a-zA-Z0-9&#xA0;-&#xEFFFD;\.!$&amp;'()\*\+,;=:_~\-])*@)?
                    ([a-zA-Z0-9&#xA1;-&#x2FA1F;]([a-zA-Z0-9&#xA1;-&#x2FA1F;-]*[a-zA-Z0-9&#xA1;-&#x2FA1F;])*
                  (\.[a-zA-Z0-9&#xA1;-&#x2FA1F;]([a-zA-Z0-9&#xA1;-&#x2FA1F;-]*[a-zA-Z0-9&#xA1;-&#x2FA1F;])*)*
                    |(\[([0-9a-fA-F]{0,4}:){0,6}(([0-9a-fA-F]{0,4}:[0-9a-fA-F]{0,4})|([0-9]{1,3}\.){3}[0-9]{1,3})\]))
                    (:[0-9]*)?
                    (/(%[0-9A-F][0-9A-F]|[a-zA-Z0-9&#xA0;-&#xEFFFD;\.!$&amp;'()\*\+,;=:@_~\-])*)*
                   (\?(%[0-9A-F][0-9A-F]|[a-zA-Z0-9&#xA0;-&#xEFFFD;\.!$&amp;'()\*\+,;=:@_~\-/\?])*)?
                    (#(%[0-9A-F][0-9A-F]|[a-zA-Z0-9&#xA0;-&#xEFFFD;\.!$&amp;'()\*\+,;=:@_~\-/\?])*)?"/>
   </xs:restriction>
</xs:simpleType>

To help understand the above rather complex pattern, here is a more informal description:

absoluteIRI: scheme :// user? host port? path? query? fragment?
scheme: letter letgit*
letter: [a-zA-Z]
letgit: [a-zA-Z0-9+.-]
                         Example: http
user:   uch* @
uch:    enc | iletter | punct
                         Example: user05:pw12345@
host:   domain (.domain)* | ipv6
domain: iletter (iletterm* iletter)*
iletterm: iletter | "-"
                         Example: www.w3.org
IPv6:   [ (h4:){0,6} ((h4:h4)|ipv4) ]
h4:     h{0,4}
h:      [0-9a-fA-F]
                         Example: [2001:db8:1::8a2e:370:7334]
ipv4:   d3.d3.d3.d3
d3:     [0-9]{1,3}
                         Example: 192.168.0.1
port:   : digit*
digit:  [0-9]
                         Example: :80
path:   segment+
segment: / pch*
pch:    enc | iletter | punct | @
                         Example: /2002/xforms/index.xhtml
query:  ? qfch*
qfch:   enc | iletter | punct | [/?@]
                         Example: ?q=test
fragment: # qfch*
                         Example: #toc
iletter: [a-zA-Z0-9&#xA0;-&#xEFFFD;]
enc:    %[0-9A-F][0-9A-F]
punct:  [.!$&'()*+,;=:_~-]
http://www.w3.org/
http://www.w3.org/2002/xforms
https://école.fr.example.org/élève.xhtml
irc://irc.w3.org:6665/#forms
http://search.example.org?q=☺
https://zh.wikipedia.org/wiki/Wikipedia:关于中文维基百科/en
https://www.石川.日本/雅康#mimasa
ssh://user@host.example.com:2222
ftp://anonymous@example.net:4916/;type=d

HTTP IRI type

This type represents an internationalised absolute http: or https: web address, a further subset of absoluteIRI.

The type is defined as the following lexical space (the pattern has been split over lines for readability, but should be a single line), which is the same as that defined for absoluteIRI, with the scheme restricted to http and https.

<xs:simpleType name="httpIRI">
  <xs:restriction base="xs:string">
    <pattern value="(http|https)://
                    ((%[0-9A-F][0-9A-F]|[a-zA-Z0-9&#xA0;-&#xEFFFD;\.!$&amp;'()\*\+,;=:_~\-])*@)?
                    ([a-zA-Z0-9&#xA1;-&#x2FA1F;]([a-zA-Z0-9&#xA1;-&#x2FA1F;-]*[a-zA-Z0-9&#xA1;-&#x2FA1F;])*
                  (\.[a-zA-Z0-9&#xA1;-&#x2FA1F;]([a-zA-Z0-9&#xA1;-&#x2FA1F;-]*[a-zA-Z0-9&#xA1;-&#x2FA1F;])*)*
                    |(\[([0-9a-fA-F]{0,4}:){0,6}(([0-9a-fA-F]{0,4}:[0-9a-fA-F]{0,4})|([0-9]{1,3}\.){3}[0-9]{1,3})\]))
                    (:[0-9]*)?
                    (/(%[0-9A-F][0-9A-F]|[a-zA-Z0-9&#xA0;-&#xEFFFD;\.!$&amp;'()\*\+,;=:@_~\-])*)*
                   (\?(%[0-9A-F][0-9A-F]|[a-zA-Z0-9&#xA0;-&#xEFFFD;\.!$&amp;'()\*\+,;=:@_~\-/\?])*)?
                    (#(%[0-9A-F][0-9A-F]|[a-zA-Z0-9&#xA0;-&#xEFFFD;\.!$&amp;'()\*\+,;=:@_~\-/\?])*)?"/>
  </xs:restriction>
</xs:simpleType>
http://www.w3.org/
http://www.w3.org/2002/xforms
https://www.石川.日本/雅康#mimasa


Legacy email type

This type represents an email address, as defined by the production Mailbox in [RFC 5321]. Two uncommon features of the syntax are excluded, namely address literals, such as person@[198.162.0.1], and quoted-strings, such as "unusual.@.unusual"@example.com. Additionally, the domain part must contain at least one dot, as recommended by ICANN [ICANN].

The type is defined as the following lexical space (the pattern has been split over lines for readability, but should be a single line):

<xs:simpleType name="email">
  <xs:restriction base="xs:string">
    <xs:pattern value="([A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+)
                     (\.[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]+)*
                      @([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)
                     (\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)+"/>
  </xs:restriction>
</xs:simpleType>

To help understand the above pattern, it can be split up as follows:

email:   atoms@host
atoms:   atom(.atom)*
atom:    char+
char:    [A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~]

host:    domain(.domain)+
domain:  letgit(letgitm*letgit)?
letgit:  [A-Za-z0-9]
letgitm: [A-Za-z0-9-]
editors@example.com
~my_mail+{nospam}$?@sub-domain.example.info

Note:

Whilst the string mailto:editors@example.com is a valid xs:anyURI, it is not a valid xforms:email because the colon separator for the URI scheme is not allowed before the '@' symbol. A valid email address does not include a mailto: URI scheme.

International email type

This type represents an 'international' email address, as defined in [RFC 6531]. This is in essence the same syntax as above, but with more characters permitted where letters are permitted.

The type is defined as the following lexical space (the pattern has been split over lines for readability, but should be a single line):

<xs:simpleType name="iemail">
   <xs:restriction base="xs:string">
      <xs:pattern value="([A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~&#x00A1;-&#x2FA1F;]+)
                       (\.[A-Za-z0-9!#-'\*\+\-/=\?\^_`\{-~&#x00A1;-&#x2FA1F;]+)*
                        @([A-Za-z0-9&#x00A1;-&#x2FA1F;]([A-Za-z0-9&#x00A1;-&#x2FA1F;-]*[A-Za-z0-9&#x00A1;-&#x2FA1F;])?)
                       (\.[A-Za-z0-9&#x00A1;-&#x2FA1F;]([A-Za-z0-9&#x00A1;-&#x2FA1F;-]*[A-Za-z0-9&#x00A1;-&#x2FA1F;])?)+"/>
   </xs:restriction>
</xs:simpleType>
editors@example.com
~my_mail+{nospam}$?@sub-domain.example.info
élève@école.fr
δοκιμή@παράδειγμα.δοκιμή
我買@屋企.香港
甲斐@黒川.日本
чебурашка@ящик-с-апельсинами.рф
संपर्क@डाटामेल.भारत

Telephone number type

This type represents a telephone number, based on [ITU E.123], but adapted according to observed usage. The type allows an optional leading international code (such as +33), an optional bracketed area code (such as (020)), and a string of digits. Digits may be separated by spaces and hyphens.

The type is defined as the following lexical space (the pattern has been split over lines for readability, but should be a single line):

<simpleType name="telephone">
   <restriction base="xsd:string">
      <pattern value="^(\(\ *\+?\ *([0-9]\ *(\-\ *[0-9]\ *)*)+\)\ *
                                   ([0-9]\ *(\-\ *[0-9]\ *)*)+)
                           |(\+?\ *([0-9]\ *(\-\ *[0-9]\ *)*)+
                             (\(\ *([0-9]\ *(\-\ *[0-9]\ *)*)+\)\ *
                                   ([0-9]\ *(\-\ *[0-9]\ *)*)+)?)[0-9]$"/>
   </restriction>
</simpleType>
06123456
(020)6123456
+31206123456
+31 20 6123456
+31-20-6123456
+1(234)1234567
+1 (234) 1234567
+1 (234) 123-4567
+1 (234) 123 - 4567

card-number type

This type represents identity, debit and credit card numbers; it is a pattern restriction on xs:string to one or more digits (0 - 9).

<xs:simpleType name="card-number">
  <xs:restriction base="xs:string">
    <xs:pattern value="[0-9]+"/>
  </xs:restriction>
</xs:simpleType>

To properly check a credit card number, you must not only check that it is a string of digits, but also that it is a valid card number. The function is-card-number() does this, as in this example:

<model xmlns="http://www.w3.org/2002/xforms">
   <instance>
     <payment xmlns="">
       <amount/>
       <number/>
       <expiry/>
     </payment>
   </instance>
   <bind ref="number" type="card-number" 
         constraint="is-card-number(.)" whitespace="remove"/>
 </model>

HTMLFragment type

This type is for a value intended to be interpreted as a serialized HTML fragment. The lexical space is a string with no extra restrictions:

<xs:simpleType name="HTMLFragment">
  <xs:restriction base="xs:string"/>
</xs:simpleType>
Note:

HTMLFragment is a tagging datatype that can be used by the UI to provide a convenient means for entry and displaying of HTML fragments ('rich text content').

This is <b>rich</b> text content.

listItem type

This datatype serves as a base for the listItems datatype. The lexical space for listItem permits one or more characters valid for xs:string, except white space characters.

listItems type

Controls that produce simpleType list content use a derived-by-list datatype. The lexical space for listItems is defined by list-derivation from listItem, that is to say, it consists of zero or more values of type listItem, separated by whitespace.

Note:

In most cases, it is better to use markup to distinguish items in a list. See The itemset Element.

Applying Datatypes

Datatypes can be applied to instance data nodes in three ways:

  1. Through applicable XML Schema definitions (via external or an inline XML Schemas);
  2. By xsi:type attributes directly applied to instance values;
  3. Through a type model item property applied by a bind element.

When multiple datatype restrictions apply to a node, the combination of all given restrictions apply. (Note that it is possible to produce a combination of restrictions that is impossible to satisfy.)

If no type constraint is provided, an instance data node defaults to type xs:string.

If a type name is used that does not identify an in-scope type, an xforms-binding-error is dispatched to the relevant bind or instance element.

Note: Attributes xsi:schemaLocation and xsi:noNamespaceSchemaLocation are ignored for purposes for locating an XML Schema.

This declares a datatype based on xs:string with an additional constraining facet:

<xs:simpleType name="password">
  <xs:restriction base="xs:string">
    <xs:minLength value="8"/>
  </xs:restriction>
</xs:simpleType>

This datatype can then be associated with model items using xsi:type:

<instance>
  <password xmlns="" xsi:type="my:password"/>
</instance>

or bind:

<instance>
  <password xmlns=""/>
</instance>
<bind ref="/password" type="my:password"/>

Controls

Controls allow interaction with instance data:

  • They encapsulate high-level semantics by expressing the intent of the control without prescribing presentation.
  • They are declared using elements and their attributes.
  • They are bound to data using binding attributes.
  • Thanks to the high-level semantics, controls are suitable for styling as aural or visual media.
  • Accessibility is further aided by taking a uniform approach to features such as labels, help text, navigation, and keyboard shortcuts.
  • Internationalization issues are addressed by following the same design principles as in XHTML.

A core control is an element that acts as a direct point of user interaction for read, write, or read/write access to instance data.

A container control combines other controls into full user interfaces.

Each control has its own syntax and functionality; however, all share some features, which are described in this section.

Common attribute and content sets

The following attributes and attribute sets are common to many elements.

Control Common
Element Attributes and their Content (after AVT evaluation)
(various)

Common, Evaluation, Appearance, Navigation, UI Common, Single Item Binding

appearance
Element Attributes and Their Content (after AVT evaluation)
(various)

appearance ("full"|"compact"|"minimal" | PrefixedName)

Optional appearance hint. If absent, any suitable rendering may be used. The effect of this attribute is defined by each control that uses it. Note that a control may have up to four standard appearances: without the attribute, and with the three possible values. See for instance the output element.
inputmode
Optional hint about the sort of text that is expected by the control. See Input Modes for details.
incremental
Optional boolean that determines when a bound control updates instance data. Normally, controls that only require a single interaction update the instance immediately after a change; controls that require more interaction, like text-oriented controls such as textarea, only update the instance once focus is moved away. When false, this attribute indicates that the instance data should be updated when the control loses focus; when true, the instance data should be updated more often, thereby generating more xforms-value-changed events – however, an implementation may buffer sequences of changes happening in quick succession, and apply them all at once. The default value for this attribute varies per control and modality, but for textual controls the default is normally false.
UI Common
Element Attributes and their Content (after AVT evaluation)
(various)

label (xs:string) | help (xs:string) | hint (xs:string) | alert (xs:string)

Controls may have label, help, hint, and alert texts associated with them, either via attributes or child elements of the control itself, or via texts associated with the bound value through the bind element in the model. If a text is associated in more than one way, the attribute on the control takes precedence, followed by the child element of the control, and finally the bound text in the model. The effect of these texts are described in the respective element descriptions.
Navigation
A host language must provide a way to indicate overall navigation order among controls and other elements included in the host language, as well as keyboard or direct access navigation to specific elements. One possibility is to use a pair of attributes named navindex and accesskey, defined as follows:
navindex
Optional non-negative integer in the range of 0-32767 used to define the navigation sequence. This gives the author control over the sequence in which controls are traversed. The default navigation order is specified in the section on control navigation.
accesskey
Optional shortcut for moving the input focus directly to a particular control. The value of this is a single character which when pressed together with a platform specific modifier key (e.g., the alt key) results in the focus being set to this control. The user agent must provide a means of identifying the accesskeys that can be used.

This module also defines the following content sets:

Content Set Minimal Content Model
UI Common

label|help|hint|alert|Action

List UI Common choices|item|itemset
Core Controls input|secret|textarea|output|upload|range|trigger|submit|select|select1|control
Controls Core Controls|group|switch|repeat|dialog
UI Content output

The Actions module adds the Actions content set into the UI Common content set. A host language may add markup to the UI Content set. When the XForms Extension module is present, it too should be included in the UI Common content set.

Common Support Elements

These are used to attach information to many controls and other elements; the information may be specified either as a child element, or as an attribute of the same name (see the UI Common attribute set). If both an attribute and an element of the same name are present, the attribute is used.

If specified as an attribute, the content of the attribute is the information to be used; if as a child element, the information is obtained by evaluating the value attribute if present, otherwise from the Single Item Binding if present, and otherwise from the inline text.

The information is rendered in the same way as by the output element, and then displayed as described below; as a consequence they may also generate an xforms-output-error.

The following table summarizes the common child elements for controls.

Support Element Attributes and Their Content (after AVT evaluation) Minimal Content Model

label

Common, Evaluation, Appearance, Single Item Binding (optional), value, mediatype

(PCDATA|(UI Content))*

help

Common, Evaluation, Appearance, Single Item Binding (optional), value, mediatype

(PCDATA|(UI Content))*

hint

Common, Evaluation, Appearance, Single Item Binding (optional), value, mediatype

(PCDATA|(UI Content))*

alert

Common, Evaluation, Appearance, Single Item Binding (optional), value, mediatype

(PCDATA|(UI Content))*

The label Element

Optional descriptive label for the attached control.

Common Attributes: Common, Evaluation, Appearance, Single Item Binding (optional), value, mediatype

Content: (PCDATA|(UI Content))*

The label is made available to the user.

<input ref="price" label="Unit Price"/>
<input ref="price">
   <label>Unit Price</label>
</input>
<input ref="price" label="{instance('msg')/price}"/>
<group>
   <label ref="intro" mediatype="text/html"/>
   ...
</group>

The help Element

Optional help information for a control.

Common Attributes: Common, Evaluation, Appearance, Single Item Binding (optional), value, mediatype

Content: (PCDATA|(UI Content))*

If the user requests it, the help content is made available to the user.

Processors should choose an appropriate presentation, and should allow styling if the host language integration supports it. By default a graphical browser should present help as an ephemeral message.

<secret ref="/login/password" label="Password">
  <help>Have you forgotten your password? Simply call 1-900-555-1212 and have
        a major credit card handy.</help>
</secret>

A password entry form control, with a popup window below, displaying instructions for retrieving a forgotten password

The hint Element

Optional hint information for a control.

Common Attributes: Common, Evaluation, Appearance, Single Item Binding (optional), value, mediatype

Content: (PCDATA|(UI Content))*

If the user requests it, the hint content is made available to the user.

Processors should choose an appropriate presentation for the hint, and should allow styling if the host-language integration supports it. By default, a presentation should be the same as an ephemeral message associated with the label.

<input ref="po/address/street1" label="Street">
  <hint>Please enter the number and street name</hint>
</input>

A graphical browser might render this as follows:

An average-looking text entry form control, with a mouse pointer visible and a tooltip below, reading 'Please enter the number and street name'

With appearance="minimal", a hint should be associated with the value yet distinguished from actual values.

<group ref="registration">
  <input ref="name" label="Name:">
    <hint appearance="minimal">Last, First</hint>
  </input>
  <input ref="website" label="Website:">
    <hint appearance="minimal">http://</hint>
  </input>
</group>

A graphical browser might render this as follows:

Two text entry form controls, one for name and another for website, with grayed-out hints 'Last, First' and 'http://' appearing in the input value text boxes.

The alert Element

Optional alert or error text for a control when its associated data is non-valid.

Common Attributes: Common, Evaluation, Appearance, Single Item Binding (optional), value, mediatype

Content: (PCDATA|(UI Content))*

When a control's associated data is invalid, the alert text is made available to the user. Processors should choose an appropriate presentation for the alert.

<instance>
   <data xmlns="">
      <number/>
   
<instance>
<bind ref="number" type="integer" />
... 
<input ref="number" label="Number" alert="Must be a whole number/>

This might be displayed with a symbol showing that the value is invalid, that if you hover over, displays the alert text:

An average-looking text entry form control, with the value 1.5 entered and a mouse pointer hovering over an icon representing invalidity, and a tooltip below, reading 'Must be a whole number'

Implementation Requirements Common to All Controls

All controls must meet the implementation requirements listed in the following sections.

Data Binding

  • If a control violates its data binding restriction, an xforms-binding-error must be dispatched to the control.
    Note: Controls that read or write simpleContent produce this error whenever and as soon as they are bound to an element node that has an element child node.
  • Controls that write simpleContent to instance data must do so as defined by the setvalue action.
    Note: If a control binds to an element node, then regardless of how many child nodes the element has, the result of the control writing to it is that it has either a single non-empty text node child, or no children if the value written is the empty string.
  • A control that reads simpleContent instance data must do so according to the type of node it is bound to:
    • The root node: an xforms-binding-error is dispatched to the control.
    • Element nodes: If element child nodes are present, then an xforms-binding-error is dispatched to the control. Otherwise, the string-value of the node is used.
    • Attribute nodes: the string-value of the node is used.
    • Text nodes: the string-value of the node is used.
    • Namespace, processing instruction, and comment nodes: behavior is undefined and implementation-dependent.
Note: The simpleContent binding restriction is intended to allow controls to bind to attribute and element nodes. This specification does not prevent binding controls directly to text nodes, however doing so can yield undesirable behavior, such as a control becoming disabled if a user enters empty data. This specification also does not prevent implementers supporting binding controls directly to comment or processing instruction nodes, however the resulting behavior is implementation-dependent and may also yield undesirable behavior.

Interaction

  • At any time, at most one core control has the focus, so that user interaction goes to that control. The focus can be changed by user interaction, by the effects of processing, or by the focus-setting events and actions xforms-focus, xforms-previous, xforms-next, setfocus, previousfocus, nextfocus.
  • If a container control is given focus, focus goes to the first enclosed core control in navigation order that can accept focus. If there is no such control, no control has focus.
  • Controls bound to a readonly value or an atomic value, must not allow the user to modify the value.
  • The host language may define navigation order between controls; in the absence of a host-language-defined ordering, the next/previous control (including container controls) in document order that is capable of receiving the focus defines the navigation order.
  • Controls that are disabled, hidden, or read-only do not participate as navigable controls, and may not receive the focus.
  • The navigation order past the last control, or before the first, is undefined. Processors may cycle back to the first/last control, remove focus altogether, or do something else.

Availability

Controls are disabled if any of the following apply and enabled otherwise:

  • the Single Item Binding resolves to the empty sequence,
  • the Single Item Binding resolves to a non-relevant instance node,
  • the control is contained by a non-relevant switch, group, or repeat item,
  • the control is contained by a non-selected case element of a switch.

When a control becomes disabled, the xforms-disabled event must be dispatched to it, and the control and any children must be made unavailable, removed from the navigation order, and not allowed focus. Disabled content should not be presented, or should be styled differently.

When a control becomes enabled, the control must be updated to represent the current value(s) and model item properties of its bound instance data, and made available for user interaction. The xforms-enabled event must be dispatched to the control, as well as the following events as appropriate: xforms-value-changed, one of xforms-valid or xforms-invalid, one of xforms-readonly or xforms-readwrite, one of xforms-required or xforms-optional, and one of xforms-in-range or xforms-out-of-range.

This processing is done during a refresh.

Note: Some elements other than controls, such as actions like setvalue and message, and the submission element also use a Single Item Binding; however, since the binding is not a UI binding expression they are not disabled when bound to a non-relevant node. Their operation may however be affected in other ways; for example, non-relevant nodes are by default excluded from the data of a submission.

Rendering

  • Layout: unless otherwise specified, controls have an inline layout by default (e.g. for a host language that supports CSS, the default styling should be display:inline). Repeat items and groups have a block layout by default (e.g. a CSS styling of display:block).
  • Representation: controls that render bound data must produce a rendering that directly corresponds to the data; it is not required to match the lexical space value of the data, but should take into account the datatype of the value, appearance hints, and localization and internationalization issues such as representation of numbers and dates.
  • Required values: enabled controls that display a representation of the bound data must distinguish rendering between being bound to a required node versus a non-required node. Exceptions include trigger and the container controls. This rendering should be user-stylable.
  • Validity: enabled controls must distinguish rendering between valid and invalid states. This rendering should be user-stylable.
  • Read-only: controls bound to a readonly value or an atomic value should indicate that entering or changing the value is not allowed. This rendering should be user-stylable.
  • Out-of-range: enabled controls bound to a value that the control is unable to represent must indicate that the control is out-of-range. This rendering should be user-stylable. Whenever a control switches to or from being out-of-range, an xforms-out-of-range or xforms-in-range event must be dispatched to the control.

Core Controls

A core control is an element that acts as a direct point of user interaction and often provides read, write, or read/write access to instance data.

Element Attributes and Their Content (after AVT evaluation) Minimal Content Model

input

Control Common, inputmode (xs:string), incremental (xs:boolean)

UI Common*

secret

Control Common, inputmode (xs:string), incremental (xs:boolean)

UI Common*

textarea

Control Common, inputmode (xs:string), incremental (xs:boolean)

UI Common*

output

Control Common, value (Expression), mediatype (xs:string)

PCDATA | (mediatype? [deprecated], UI Common*)

upload

Control Common, accept (xs:string), mediatype (xs:string) [deprecated], incremental (xs:boolean)

filename?, mediatype?, UI Common*

range

Control Common, start (xs:string), end (xs:string), step (xs:string), incremental (xs:boolean)

UI Common*

trigger

Control Common

UI Common*

submit

Control Common, submission (xs:IDREF)

UI Common*

select

Control Common, selection ("open" | "closed"), incremental (xs:boolean)

UI Common*, List UI Common+, UI Common*

select1

Control Common, selection ("open" | "closed"), incremental (xs:boolean)

UI Common*, List UI Common+, UI Common*

control

Control Common, resource (xs:anyURI)

UI Common*

The following table summarizes the support elements for these controls.

Support Element Attributes and Their Content (after AVT evaluation) Minimal Content Model

filename (for upload)

Common, Evaluation, Single Item Binding

EMPTY

mediatype (for upload)

Common, Evaluation, Single Item Binding

EMPTY

mediatype (for output) (deprecated)

Common, Evaluation, Single Item Binding, value (string Expression)

EMPTY

choices (for selection controls)

Common, Evaluation, label (xs:string)

label?, (List UI Common)+

item (for selection controls)

Common, Evaluation, UI Common, value (Expression), copy (Expression)

(value|copy), (UI Common)*

value (for selection controls)

Common, Evaluation, Single Item Binding (optional), value (Expression)

PCDATA

itemset (for selection controls)

Common, Evaluation, UI Common, Sequence Binding, value (Expression), copy (Expression)

(value|copy), (UI Common)*

copy (for selection controls)

Common, Evaluation, Single Item Binding

EMPTY

The input Element

This control enables data entry in a way appropriate to the datatype of the bound node.

Common Attributes: Control Common, inputmode, incremental

Content: UI Common*

Data Binding Restrictions: Binds to any simpleContent (except xs:base64Binary, xs:hexBinary or any datatype derived from these) or an atomic value.

An input element produces some suitable rendering of the instance data it is bound to. If the control has an appearance attribute with a value of minimal, it should be displayed in a manner similar to the output control, otherwise, it should be displayed in a way that suggests that the value is editable.

When the element has the input focus, interaction can change that rendering; changes to the rendering cause consequent changes to the instance data it is bound to.

This control must allow entry of a lexical value for the bound datatype. Implementations should provide a convenient means for entry of value according to their datatype and take into account localization and internationalization issues such as representation of numbers and dates. For example, an input bound to an instance data node of type date might provide a calendar control to enter dates; similarly, an input control bound to type boolean might be rendered as a checkbox.

<input ref="order/shipTo/street" label="Street"/>

A graphical browser might render this as:

An average-looking text entry control. The label, 'Street' has been aligned to the left

<input ref="order/shipDate" label="Ship By"/>

A graphical browser might render this as:

A text box for a date control, with a button to open into a calendar.

The user can type a date into the text edit box, or press the button to open a calendar:

A calendar picker graphical widget.

<input ref="/search/expr" label="Search term(s):">
  <send ev:event="DOMActivate" submission="doSearch"/>
</input>

<submit submission="doSearch" label="Search"/>

This example shows input and submit controls working together to provide the common user experience of a simple search. The input collects the search term(s) and then automatically initiates the submission identified by doSearch if the user activates the input control. Alternatively, the user initiate the doSearch submission by activating the submit control.

Note:

A graphical browser on a desktop device might activate controls such as input in response to a special user action such as pressing the Enter key or either clicking or double-clicking with the mouse (depending on the type of control).

The secret Element

This control allows input of data in a manner that hinders third parties discerning the data being input. A common use is for password entry.

Common Attributes: Control Common, inputmode, incremental

Content: UI Common*

Data Binding Restrictions: Binds to any simpleContent (except xs:base64Binary, xs:hexBinary or any datatype derived from these) or an atomic value.

Implementation Requirements: Implementations, including accessibility aids, must obscure the value being entered into this control. One approach is to render a "*" or similar character instead of the actual characters entered.

Except for the rendering aspects, the secret control behaves further as an input control.

<secret ref="/login/password" label="Password" 
        hint="The password you enter will not be displayed"/>

A graphical browser might render this control as follows:

A password entry control, with '*' characters where the text would be expected and a hint box displaying hint text.

The textarea Element

This control enables free-form data entry and is intended for use in entering multiline content, such as the body of an email message.

Common Attributes: Control Common, inputmode, incremental

Content: UI Common*

Data Binding Restrictions: Binds to any simpleContent (except xs:base64Binary, xs:hexBinary or any datatype derived from these) or an atomic value.

Implementation Requirements: Must allow entry of a lexical value for the bound datatype, including multiple lines of text. Implementations should provide a convenient means for entry of datatypes, for example, a textarea bound to an instance data node of type xforms:HTMLFragment might provide a WYSIWYG rich text editor with common word processor features.

<textarea ref="message/body" label="Message Body:"/>

Note that the constraints on how much text can be input are obtained from the underlying XForms Model definition and not from any display properties.

A graphical browser might render the above example as follows:

A larger-than-average text entry form control. The title, 'Message Body:' provides an additional hint that large amounts of text are allowed here.

The output Element

This control renders content based on instance data.

Common Attributes: Control Common, value, mediatype

Content: PCDATA | (mediatype? [deprecated], UI Common*)

Most controls are required to have an item binding: output does not.

Data Binding Restrictions: Binds to any simpleContent or an atomic value.

The data to be rendered is obtained by evaluating the value attribute if present, or otherwise from the Single Item Binding if present, and otherwise from the inline data.

The mediatype is obtained from the mediatype attribute if present, or otherwise from the mediatype child element if any.

If a mediatype has been specified, and the data to be output is non-empty, the data is decoded or dereferenced depending on the base type of the data: an xs:base64Binary value is base-64 decoded, an xs:hexBinary value is hex-binary decoded, and an xs:anyURI value is treated as a URI and dereferenced. For any other type, the data is used without modification. Implementations should accept at least image/* and, if the host language is some version of HTML, text/html as possible values of mediatype.

The data is rendered in a suitable way taking into account the datatype of the value, the mediatype if any, the appearance attribute, and localization and internationalization issues such as representation of numbers and dates.

The data is rendered on XForms initialization, and re-rendered whenever there is a change in any node to which the binding or expression refers, or if the mediatype changes.

Failure to render the content should result in a (non-fatal) xforms-output-error. Failure can occur for many reasons, such as:

  • Data to be decoded does not conform to the format of xs:base64Binary or xs:hexBinary;
  • An error dereferencing the URI in a item of or derived from type xs:anyURI;
  • A data format error (e.g. incorrect or unsupported image format);
  • An unrecognized mediatype identifier string.

Note:

The content model for the output element includes UI Common in order to allow action handlers for the xforms-output-error as well as to allow more comprehensive behavior and information to be provided for the output, e.g. via the hint element.

<output ref="age" label="Age:"/>
<output ref="age"><label>Age:</label></output>
<output value="amount*taxrate" label="Tax:"/>
<output class="note">Deleted</output>
I charged you <output ref="order/totalPrice"/>
- and here is why:

A graphical browser might render this control as follows:

Average-looking text, reading 'I charged you 100.0 - and here is why:'

<output value="'http://tile.openstreetmap.org/10/511/340.png'" mediatype="image/*" />
<output value="'http://{site}/{zoom}/{x}/{y}.{type}'" mediatype="image/*" />

The second example above can use an instance such as:

<instance xmlns="">
   <map>
      <site>tile.openstreetmap.org</site>
      <zoom>10</zoom>
      <x>511</x>
      <y>340</y>
      <type>png</type>
   </map>
</instance>
<model>
  <instance>
    <data xmlns="">
      <picture/>
    </data>
  </instance>
  <bind ref="picture" type="xs:base64Binary"/>
</model>

Given the model above, the following controls can upload an image to instance data and display it:

<upload ref="picture" accept="image/*" label="Press me to attach a picture"/>
<output ref="picture" mediatype="image/*" hint="This is the image you attached to the form.">
  <message ev:event="xforms-output-error">Error attaching image data.</message>
</output>
<bind ref="birthdate" type="date"/>
...
<output ref="birthdate" label="Lexical:"/>
<output ref="birthdate" appearance="full" label="Full:"/>
<output ref="birthdate" appearance="compact" label="Compact:"/>
<output ref="birthdate" appearance="minimal" label="Minimal:"/>

A graphical browser taking into account the appearance and the localization information from the host language, might present the above output controls as follows:

Lexical: 1998-01-19 Full: 19 janvier 1998 Compact: 19 jan 98 Minimal: 19/01/1998

or as

Lexical: 1998-01-19 Full: 19 January 1998 Compact: 19 Jan 98 Minimal: 19/01/1998
<instance id="messages">
   <messages xmlns="">
      ...
      <warning>Do &lt;em>not&lt;/em> pass go!</warning>
      ...
   </messages>
</instance>
<output ref="instance('messages')/warning" mediatype="text/html"/> 

The mediatype Element (for output) (Deprecated)

Element mediatype (deprecated in favor of using an AVT in the mediatype attribute on element output) specifies the required mediatype to be used for output.

Common Attributes: Common, Evaluation, Single Item Binding, value

Content: PCDATA

The mediatype to be used is obtained by evaluating the value attribute, or otherwise from the inline content of the element.

<mediatype value="'image/*'"/>
<mediatype>image/*</mediatype>
<mediatype value="../imagetype"/>

The upload Element

This control allows files to be uploaded from the local file system, as well as accepting input from devices such as microphones, pens, scanners, and digital cameras.

Common Attributes: Control Common, incremental

Special Attributes:

accept
Optional comma-separated list of suggested mediatypes and file extensions (including the leading period), used to determine the possible sources of data to upload. This attribute must work as described in [HTML5].
mediatype [deprecated in favor of accept]
Space-separated list of suggested mediatypes, used to determine the possible sources of data to upload.

Content: filename?, mediatype?, UI Common*

Data Binding Restrictions: This control can only be bound to datatypes xs:anyURI, xs:base64Binary or xs:hexBinary, or types derived by restriction from them.

When activated, this control offers the user a dialog to upload a file, or obtain data from another source, such as a camera, scanner, microphone, etc.

Implementations with a file system should support file upload — selecting a specific file. The types of files presented by default should reflect the mediatype specified by the accept attribute, for example defaulting to only audio file types for "audio/*".

Implementations attached to devices capable of producing data should support those devices. The devices presented by default should reflect the mediatype specified by the accept attribute, for example defaulting to cameras and scanners for "image/*".

Implementations which cannot support upload for the given mediatype must make this apparent to the user.

If child element filename is present and a filename is available, the filename of the data to upload is placed in the instance at the node indicated by the binding attributes on child element filename.

If child element mediatype is present and a mediatype is available, the mediatype of the data to upload is placed in the instance at the node indicated by the binding attributes on child element mediatype.

When bound to an instance data node of type xs:base64binary, xs:hexBinary, or a type derived by restriction thereof, the binary content is placed in the content of the node, encoded as indicated.

When bound to an instance data node of type xs:anyURI (or a type derived by restriction thereof), a URI is placed in the content of the node. For security reasons, the URI bound to this control must not be dereferenced without explicit user permission.
Note: Binary content, mediatype, and filename must be associated with that URI for Serialization as multipart/related and Serialization as multipart/form-data serialization.
<upload ref="mail/attachment" accept="video/*,image/*,.txt,.pdf" label="Select attachment:">
  <filename ref="@filename"/>
  <mediatype ref="@mediatype"/>
</upload>
<upload ref="mail/attachment" accept="image/*" label="Select image:">
  <filename ref="@filename"/>
  <mediatype ref="@mediatype"/>
</upload>

A graphical browser might render this control as follows:

A drop-down box; main display reads 'Select Image:' with a cute icon. The drop-down itself has three items: (icon)-From Scanner or Camera...; (icon)-Scribble...; Browse...

The filename Element (for upload)

This element specifies the location for the filename of the chosen binary resource, if available. For security reasons, upload must not take action due to any existing value of the node.

Common Attributes: Common, Evaluation, Single Item Binding

Content: EMPTY

Data Binding Restrictions: Binds to any simpleContent (except xs:base64Binary, xs:hexBinary or any datatype derived from these).

The user is prompted to select an image. Depending on the type of mail/attachment, either the binary data of the image or a URI for it, is placed in mail/attachment. The corresponding filename, perhaps "me.jpg", is placed in the attribute node mail/attachment/@filename, and the mediatype, perhaps "image/jpeg" in the attribute node mail/attachment/@mediatype.

<upload ref="mail/attachment" accept="image/*" label="Select an image to attach">
  <filename ref="@filename"/>
  <mediatype ref="@mediatype"/>
</upload>

The mediatype Element (for upload)

This element specifies the location to place the mediatype of the chosen binary resource, if available.

Common Attributes: Common, Evaluation, Single Item Binding

Content: EMPTY

Data Binding Restrictions: Binds to any simpleContent (except xs:base64Binary, xs:hexBinary or any datatype derived from these).

The range Element

This control allows input or selection from a sequential range of values.

Common Attributes: Control Common, incremental

Special Attributes:

start
Optional hint for the starting bound for the range — a legal value for the underlying data. If provided, this value further refines the constraints specified by the underlying model.
end
Optional hint for the ending bound for the range — a legal value for the underlying data. If provided, this value further refines the constraints specified by the underlying model.
step
Optional delta-value to use for incrementing or decrementing the value. It must be of a type capable of expressing the difference between two legal values of the underlying data.

Content: UI Common*

Data Binding Restrictions: Binds to simpleContent from the following list of datatypes, or datatypes derived by restriction from them: xs:duration, xs:date, xs:time, xs:dateTime, xs:gYearMonth, xs:gYear, xs:gMonthDay, xs:gDay, xs:gMonth, xs:float, xs:double, and xs:decimal.

Note: These datatypes include by derivation all of the integer datatypes (which are derived by restriction from xs:decimal), and all of the XForms datatypes defined in Section XForms Datatypes that correspond to the allowed XML Schema datatypes.

This control allows the input of a value within the restrictions specified by the control. In the event of overlapping restrictions between the underlying datatype and the start and end hints, the most restrictive range should be used. The upper and lower bounds and the step size should be available to the user.

If the instance data value is outside the upper or lower bounds, the control is out-of-range.

In graphical environments, this control could be rendered as a "slider" or "rotary control".

Note:

The attributes of this element encapsulate sufficient metadata that in conjunction with the type information available from the XForms Model proves sufficient to produce meaningful prompts when using modalities such as speech, e.g., when using an accessibility aid. Thus, in the example below, an aural user agent might speak a prompt of the form Please pick a date in the range January 1, 2020 through December 31, 2020.

<range ref="/stats/balance" start="-2.0" end="2.0" step="0.5" label="Balance"/>

A graphical browser might render this as follows:

a slider control, from -2 to +2

<range ref="/order/shipDate" start="2021-01-01" end="2021-12-31" label="Ship Date"/>

The trigger Element

This control allows user-initiated actions and can be used to construct custom controls. It is similar in effect to the HTML button element.

Common Attributes: Control Common

Content: UI Common*

Most controls must have a single item binding; on trigger it is optional.

Data Binding Restrictions: Binds to any node or an atomic value; the data is not used, only the data's model item properties:

  • the relevant property affects visibility, focus, and navigation order as with other controls, and thus disables the trigger;
  • the readonly property has a similar effect as with input controls: the trigger cannot receive focus, cannot be activated, but remains visible with a presentation that indicates it is not activatable;
  • all other properties have no effect.
Editorial note: trigger enablement 2018-01-17
There is discussion on whether it is preferable to use all MIPS, and only make a trigger activatable when the bound value is valid, relevant, and non-empty if required.

Implementation Requirements: The user agent must provide a means to generate a DOMActivate event on the control.

This control is activated by user interaction, which causes the DOMActivate event to be dispatched to it; event handlers in the body of the trigger can respond to this event to effect further processing.

Graphical implementations might render this control as a push-button with the label on the button face. Style sheets can be used to style this control in other ways, though a means is provided to suggest an appearance through the appearance attribute. Suggested renditions for the pre-defined values of this attribute are as follows:

full: visually rendered as a standard button control with border,
compact: visually rendered as a standard button control without border,
minimal: as underlined text, such as might be used for an XHTML anchor element.
<trigger label="Click here">
  <message ev:event="DOMActivate">Hello!</message>
</trigger>

The submit Element

This control initiates a submission; it is shorthand for a trigger with a send action.

Common Attributes: Control Common

Most controls must have a single item binding; on submit, it is optional.

Special Attributes:

submission
Optional reference to the ID of a submission element. If omitted, then the first submission in document order from the model associated with the in-scope evaluation context is used.

Content: UI Common*

Data Binding Restrictions: Binds to any node or an atomic value. This control does not use the instance data it is bound to, but is affected by the data's model item properties: the relevant property affects if the control can be activated or not; all other properties have no effect.

This control is activated by user interaction or by the DOMActivate event.

A submission element is identified from the submission attribute or its default: if no such element is identified then an xforms-action-error with an error-type of send-submission is dispatched; otherwise an xforms-submit is dispatched to the element. This control then becomes unavailable for further activation until the submit process concludes with either an xforms-submit-done or xforms-submit-error.

Typically, style sheets are used to specify the appearance of controls, however a means is provided to suggest an appearance through attribute appearance. Suggested renditions for the pre-defined values of this attribute are the same as for trigger.

<submit label="OK"/>
<submit submission="timecard" label="Submit Timecard"/>

Selection Controls

There are two selection controls:

  • select which allows the selection of zero or more values from a collection, which are combined into a single value and stored in the bound value;
  • select1 which allows for the selection of zero or one from the collection, which is then stored in the bound value.

The collection of values to be selected from are provided by a combination of item elements, each of which supplies one value, and itemset elements, which provide a sequence of values.

A selection control can be "simple" or "complex":

  • a simple selection only selects simpleContent values (typically strings), in which case the item or itemset elements use a value child or attribute;
  • a complex selection selects more general values (typically with children nodes), and the item and itemset use a copy child or attribute. If one item or itemset element has a copy child or attribute, then all of them must have, and the bound target of the containing selection control must be an element node, otherwise an xforms-binding-error event is dispatched to the containing selection control.

A simple selection can be either "open" or "closed", as indicated by the selection attribute: an open selection allows the selection of values outside the list given. A complex selection is always closed.

The items from the children of the selection control are evaluated, each being a pair of a label and a value.

The label for each pair must be made available to the user, with an indication of whether the item is selected or not.

Interaction with a label toggles the selected state. On selection, items receive the xforms-select event; on deselection, the xforms-deselect event.

A selection control is out-of-range if it is bound to data whose value for any reason is not in the collection of possible values.

Typically, a style sheet is used to control the appearance of controls, though a means is provided to suggest an appearance through the appearance attribute. The value of the attribute consists of one of the following values:

  • "full": all labels should be rendered at all times;
  • "compact": a fixed number of labels should be rendered, with scrolling facilities as needed;
  • "minimal": a minimum number of labels should be rendered, with a facility to temporarily render additional choices.

The select Element

This control allows the selection of multiple values from a list of choices.

Common Attributes: Control Common, incremental

Special Attributes:

selection
Optional value indicating whether the selection is open or closed. Allowable values are "open" and "closed". Default is "closed".

Content: UI Common*, List UI Common+, UI Common*

Data Binding Restrictions: For simple selections, binding must be to any simpleContent capable of holding a sequence or a sequence of atomic values; the datatype may be a non-enumerated value space, e.g., string, or a union of an enumeration and a non-enumerated datatype (called an open enumeration). For complex selections, binding is to an element with no mixed content, or a sequence of atomic values.

All items whose values match a value in the bound instance data are initially selected; if a particular value in the bound data matches more than one item, at least one is selected, but it is not further defined which, nor how many. If there is no match, no items are initially selected. Items with an empty storage data subtree or a storage value that is either empty or contains only white space characters are never selected.

If the bound instance data contains values that do not match any item's value:

  • for open selections, all such non-matching values are retained and made available to the user; since there are no associated labels, the value itself is used as the label;
  • for closed selections, the control is out-of-range.

Any number of the items may be selected, including none.

For open selections, the control must also allow free data entry, as described in The input Element. The control must permit multiple values to be entered through free entry. The label of such an entered value is considered identical to the value itself.

Selected values are represented in the bound instance location:

  • for simple selections as a space-separated list,
  • for complex selections as copies of the subtrees of the selected values.

The content of the bound instance node must only be changed by the addition or deletion of storage data associated with items that have been selected or deselected; content not associated with selection items must be preserved.

For a simple selection, the net effect of newly selected and deselected items is computed into a string, preserving content not associated with selection items. For complex selections, the individual subtrees associated with the newly selected and deselected items are added or removed individually by using insert and delete; after which an update is done, followed by a refresh.

Note that when the list of values is stored as a space separated list, the values to be selected may not themselves contain spaces. For instance, this is incorrect use:

<item>
  <label>USA</label>
  <value>United States of America</value>
</item>
<select ref="flavors" label="Flavors">
  <item label="Vanilla">v</item>
  <item label="Strawberry">s</item>
  <item label="Chocolate">c</item>
</select>

A graphical browser might render this control as any of the following:

appearance="full" appearance="compact" appearance="minimal"

Check boxes for three choices: Vanilla, Strawberry, and Chocolate. Strawberry and Chocolate are selected.

A list box with three choices: Vanilla, Strawberry, and Chocolate visible. Strawberry and Chocolate are selected.

A popup menu with three choices: Strawberry, Vanilla, and Chocolate. Strawberry and Chocolate are selected.

Since a select is essentially a shorthand for inserts and deletes, which can also insert and delete attributes, a selection control can also be used for adding attributes to elements:

<select ref="a">
    <label>Add attributes</label>
    <item label="class"/>
       <copy ref="attribute('class', 'basic')"/>
    </item>
    <item label="id"/>
       <copy ref="attribute('id', 'aaa')"/>
    </item>
    <item label="href"/>
       <copy ref="attribute('href', 'http://www.example.com')"/>
    </item>
 </select>
 <input ref="a/@class" label="class"/>
 <input ref="a/@id" label="id"/>
 <input ref="a/@href" label="href"/>

The select1 Element

This control is similar to the select control except that only a single item may be selected from the list of choices: interaction with a label of a non-selected item first deselects any item already selected, and then selects the new item.

Common Attributes: Control Common, incremental

Special Attributes:

selection
Optional value indicating whether the selection is open or closed. Allowable values are "open" and "closed". Default is "closed".

Content: UI Common*, List UI Common+, UI Common*

Data Binding Restrictions: For simple selections, binds to any simpleContent or an atomic value; for complex selections, binds to an element with no mixed content or an atomic value.

Any item whose value matches the value of the bound instance data is initially selected; if more than one matches, at least one is selected, but it is not further defined which, nor how many of the matching items is selected. If there is no match, no item is initially selected. For both closed and open selections, any item with an empty storage data subtree or a storage value that is either empty or contains only white space characters is treated identically to any other value.

If the bound instance data is non-empty and does not match any item's value:

  • for open selections, the non-matching value is retained and made available to the user; the value is also used as the label;
  • for closed selections, the control is out-of-range;

Interaction with the label of an unselected item deselects any already-selected item and then selects the new item; interaction with the label of a selected item deselects that item.

For open selections, the control must also allow free data entry, as described in The input Element; entering a value selects that value after deselecting any already-selected value. The label of such an entered value is considered identical to the value itself.

The selected value is stored in the bound instance location, for complex selections as a copy of the subtree of the selected value.

<select1 ref="icecream/flavor" label="Flavour">
  <item label="Vanilla">v</item>
  <item label="Strawberry">s</item>
  <item label="Chocolate">c</item>
</select1>

A graphical browser might render this control as any of the following:

appearance="full" appearance="compact" appearance="minimal"

Radio buttons for three choices: Vanilla, Strawberry, Chocolate. Strawberry is selected.

A list box with three choices: Vanilla, Strawberry, and Chocolate visible. Strawberry is selected.

A collapsible pull-down list with the three choices. The list is collapsd, and Vanilla is selected.

With this instance

<instance id="palette">
   <palette xmlns="">
      <hue name="Salmon">#fa8072</hue>
      <hue name="Olive">#808000</hue>
      <hue name="Navy">#000080</hue>
   </palette>
</instance>

This select1 combines item and itemset elements to form the collection of items:

<select1 ref="colour" label="Colour">
   <item label="Black">#000000</item>
   <item label="White">#ffffff</item>
   <itemset ref="instance('palette')/hue" label="{@name}" value="."/>
</select1>

The choices Element

This element is used within selection controls to group available choices. This provides the same functionality as element optgroup in HTML.

Common Attributes: Common, Evaluation

Content: label?, (List UI Common)+

<select1 ref="drink" label="Drink">
  <choices label="Hot">
     <item label="Coffee">coffee</item>
     <item label="Tea">tea</item>
  </choices>
  <choices label="Cold">
     <item label="Water">water</item>
     <item label="Milk">milk</item>
  </choices>
</select1>

The item Element

This element specifies the storage value and label to represent an item in a selection list. It is found within elements select1 and select, or grouped in element choices.

Common Attributes: Common, Evaluation, UI Common, value

Special Attributes:

copy
Optional expression giving a value to be copied. Takes precedence over any copy child element.

Content: (value | copy | UI Common)*

Data Binding Restriction: All lexical values must be valid according to the datatype bound to the selection control. If the Single Item Binding attributes are used and indicate a node in a model other than the bound node of the containing selection control, then an xforms-binding-error must occur.

The storage value is obtained by evaluating the value if present, otherwise from the Single Item Binding if present, otherwise by evaluating the value child element, if present, and otherwise from the string content of the item element.

These four are equivalent:

<item label="Credit">cc</item>
<item label="Credit" value="'cc'"/>
<item label="Credit"><value>cc</value></item>
<item><label>Credit</label><value>cc</value></item>

These two are equivalent:

<item label="{labels/female}">f</item>
<item><label ref="labels/female"></label><value>f</value></item>
<item label="Today" value="substring-before(now(), 'T')"/>
The value Element (for item)

This element provides a storage value to be used when an item is selected.

Common Attributes: Common, Evaluation, Single Item Binding (optional), value

Content: PCDATA

The storage value is obtained by evaluating the value attribute if present, otherwise from the Single Item Binding if present, and otherwise from the inline content of the value element.

<value>3</value>
<value ref="../a"/>
<value value="substring-before(now(), 'T')"/>

The itemset Element

This element generates item elements from instance values, for select and select1 controls.

Common Attributes: Common, Evaluation, UI Common, Sequence Binding, value

Special Attributes:

copy
Optional expression giving a value to be copied. Takes precedence over any copy child element.

Content: (value|copy), (UI Common)*

If there is a copy attribute or child present, this itemset is part of a complex selection: if the bound target of the containing select or select1 element is not an element node, an xforms-binding-error event is dispatched to the containing selection element.

The sequence binding is evaluated to give a sequence. For each item of this sequence, an associated item element is generated:

  • the label is obtained from the label attribute if present, or otherwise the label child element;
  • for a simple selection, the value attribute if present, or otherwise the value child, is evaluated to give a simple value;
  • for a complex selection, the copy attribute if present, or otherwise the copy child, is evaluated to give a complex value.

Actions appearing in the content of an itemset are created within each item element, and their evaluation context is that of the data item for which the item was generated, as described in Evaluation Context.

Note:

As with the repeat element, the itemset template content, including XForms Actions, is made unavailable. Copies of the itemset template content, including XForms Actions, are made available via repeated item objects.

Note:

Whenever a refresh is done, the sequence binding is re-evaluated to update the list of available choices.

Using the following two models:

<model id="cone">
  <instance>
    <icecream xmlns="">
      <order/>
    </icecream>
  </instance>
</model>

<model id="flavors">
  <instance>
    <flavors xmlns="">
      <flavor><description>Vanilla</description></flavor>
      <flavor><description>Strawberry</description></flavor>
      <flavor><description>Chocolate chip</description></flavor>
    </flavors>
  </instance>
</model>

you can then specify the following control:

<select model="cone" ref="order" label="Flavors">
  <itemset model="flavors" ref="flavor" label="{description}" copy="description"/>
</select>

If all three items are then selected, this produces instance data like

<icecream>
   <order>
      <description>Vanilla</description>
      <description>Strawberry</description>
      <description>Chocolate chip</description>
   </order>
</icecream>
<model>
   <instance>
      <transaction xmlns="">
         <addressee/>
      </transaction>
   </instance>
   <instance id="contacts">
      <contacts xmlns="">
         <address>
            <name>John Smith</name>
            <street>11 Main Street</street>
            <city>London</city>
            <postcode>W1 1AA</postcode>
            <land>UK</land>
         </address>
         <address>
            ... etc ...
         </address>
         <address>
            ... etc ...
         </address>
      </contacts>
   </instance>
</model>
 ...
<select1 ref="addressee">
   <label>Choose address</label>
   <itemset ref="instance('contacts')/address">
      <label ref="name"/>
      <copy ref="."/>
  </itemset>
</select1>
The copy Element (for item and itemset)

This element is similar to the value element, except that it works with subtrees of instance data rather than simple values.

Common Attributes: Common, Evaluation, Single Item Binding

Content: EMPTY

The storage value is obtained by evaluating the Single Item Binding.

<copy ref="."/>

The Control Element

This control embeds a form in the current one, optionally sharing data between the two, and optionally allowing communication via events.

Common Attributes: Control Common

Special attributes:

resource
Required URI of a resource containing an XForms Document to be embedded within the invoking form.

Content: UI Common*

The resource attribute is evaluated. It should be an XForms document, though implementations may accept a wider class. If no resource is found, or the implementation cannot process it, an xforms-link-error is dispatched to the control element, and the element has no further effect; otherwise the resource is embedded in the current form at the current textual position.

If the control element has a binding it must evaluate to a single element, and the embedded resource must have a shared element with a binding that also evaluates to a single element, otherwise an xforms-binding-error is dispatched to the control element.

If the control element has no binding, the embedded resource must either contain no shared element, or contain one without a binding, otherwise an xforms-binding-error is dispatched to the control element.

In the absence of the above errors, the embedded resource is further initialised and processed.

If the embedded resource contains a shared element, the embedded form is initialised with additional effect from that element, and data is shared between the two forms, as described in that section.

The shared element also permits communication with events using the signal action.

If the embedded resource contains no shared element, there is no communication between the two; the embedded resource is freestanding and is processed in the normal way.

<control resource="game.xhtml"/>
<control resource="process.xf" ref="data"/>
<control resource="{choice}" bind="values">
   <toggle ev:event="finished" case="closed"/>
</control>
<control resource="histogram.xhtml" ref="before" label="Before"/>
<control resource="histogram.xhtml" ref="after"  label="After"/>


Container Controls

A container control is a control that combines other controls in its content into user interfaces.

The elements and attributes are:

Element Attributes and Their Content (after AVT evaluation) Minimal Content Model

group

Control Common, collapse ("open"|"closed")

(Controls|UI Common)*

switch

Common, Evaluation, Appearance, Single Item Binding (optional)

case+

case

Common, Evaluation, UI Common, selected (xs:boolean), name (xs:string)

(Controls|UI Common)*

toggle

Action Common, case (xs:IDREF)

case?
dialog Common, Evaluation, Appearance, UI Common, level ("modeless"|"modal"|PrefixedName), hide (xs:boolean) (Controls|UI Common)*
show Action Common, dialog (xs:IDREF) EMPTY
hide Action Common, dialog (xs:IDREF) EMPTY

repeat

Common, Evaluation, Appearance, Sequence Binding, indexref (node Expression), startindex (xs:positiveInteger), number (xs:nonNegativeInteger)

(Controls|Action)*

Various (global attributes) [xforms:repeat-ref, xforms:repeat-nodeset (deprecated), xforms:repeat-bind, xforms:repeat-model] (Sequence Binding attributes), xforms:repeat-indexref (node Expression), xforms:repeat-startindex (xs:positiveInteger), xforms:repeat-number (xs:nonNegativeInteger) N/A

The group Element

This control aggregates and sets the context for a group of enclosed controls; groups can be nested. The optional label represents a label for the entire group. The optional collapse attribute makes the group interactively collapsible.

Common Attributes: Control Common

Special Attribute:

collapse
Optional attribute to make the group collapsible. The value of the attribute gives its current state, one of ("open"|"closed"). If absent, the group is not collapsible.

Content: (Controls|UI Common)*

A group should have a block layout by default (e.g. a CSS styling of display:block); if the element has an appearance attribute with the value minimal, then the group should have an inline layout.

If the collapse attribute is present, the group is interactively collapsible, and the presentation of the group should make this apparent to the user. If the value of the attribute is open then the group and its label are made available to the user; if the value is closed, only the label is made available. Activating the group toggles between the two states.

If a group element is bound to a node, which is optional, only the relevant model item property has an effect. See Implementation Requirements Common to All Controls for details of processing for non-relevance. If a group is disabled, then so is the entire content of the group.

<group ref="address" label="Shipping Address"/>
  <input ref="line_1" label="Address line 1"/>
  <input ref="line_2" label="Address line 2"/>
  <input ref="postcode" label="Postcode"/>
</group>
<group collapse="open" ref="address" label="Shipping Address"/>
  <input ref="line_1" label="Address line 1"/>
  <input ref="line_2" label="Address line 2"/>
  <input ref="postcode" label="Postcode"/>
</group>

A graphical browser might display this, toggling between this presentation:

A group with collapse="open", showing a title "Shipping address, with an indication that its state is open, and controls for filling in an address

and this:

A group with collapse="closed", showing a title "Shipping address, with an indication that its state is closed, and nothing else.

The switch Element

This is a container control that allows parts of the user interface to be switched in and out. It defines one or more case elements, one of which is rendered at any given time.

Common Attributes: Common, Evaluation, Appearance, Single Item Binding (optional)

Content: case+

Initially, and, if there are case elements with a name attribute, any time the value of the Single Node Binding (if present) changes:

  • if there is a Single Item Binding, and any of the case elements has a name attribute, the Binding is evaluated as a string, and then compared one-by-one in document order with the name attribute on each case that has one; the first that matches, if any, causes that case to be selected;
  • if there is no Binding, or no name matches, the first case with a selected attribute set to true, if any, is selected;
  • otherwise the first case in document order is selected.

If a switch element is bound to a node via a Single Item Binding, but no case element has a name attribute, only the relevant model item property of the bound value has an effect, and changes to the bound value do not cause a new case to be selected. See Implementation Requirements Common to All Controls for details of processing for non-relevance. If a switch is disabled, then so are all of its cases.

A case can also be selected using toggle, see the toggle action for details.

Note: A case is selected using the name attribute when selecting via the binding, and the id attribute when using toggle.

<select1 ref="/payment/details/@method" label="Select Payment Method">
  <item label="Credit Card"       value="'creditCard'"/>
  <item label="Bank Account Card" value="'cashCard'"/>
  <item label="Cash on delivery"  value="'COD'"/>
</select1>

<switch ref="/payment/details/@method">
  <case/>
  <case name="creditCard" label="Credit Card Details">
    ...
  </case> 
  <case name="cashCard" label="Bank Account Card">
    ...
  </case>
  <case name="COD" label="Cash-on-delivery Account Information">
    ...
  </case>
</switch>

In this example, if the payment method is initially empty, then the first, empty, case will be selected. Once the user chooses a payment method with the select1, then the case is selected whose name matches the selected item value.

<switch>
  <case id="in">
    <input ref="yourname" label="Please tell me your name">
      <toggle ev:event="DOMActivate" case="out"/>
    </input>
  </case>
  <case id="out">
      Hello <output ref="yourname"/>!
      <trigger label="Edit">
        <toggle ev:event="DOMActivate" case="in"/>
      </trigger>
  </case>
</switch>

This results in the portion of the user interface contained in the first case being displayed initially. This prompts for the user's name; filling in a value and activating the control, e.g. by pressing enter, switches to the alternate case, with an output rendering. Activating the trigger labeled "Edit" in turn switches back to the original case.

The case Element

This element contains markup to be conditionally rendered by a switch.

Common Attributes: Common, Evaluation, UI Common

Special Attributes:

selected
Optional initial selection status for the case, either true or false. The default value is false.
name
Optional name for the case, a string.

Content: (Controls|UI Common)*

Before a case is selected, any existing selected case is first deselected.

When a case is selected, it receives the event xforms-select, and its content is rendered. The content elements behave as if they were in a group that has become enabled (see The group Element).

When a case is deselected, it receives the event xforms-deselect and its content is no longer rendered. The content elements behave as if they were in a group element that has become disabled.

The dialog Element

This container control allows the definition of a dialog, which can be shown or hidden at different times.

Common Attributes: Common, Evaluation, Appearance, UI Common

Special Attributes:

level
Optional dialog level identifier, one of ("modeless"|"modal"|PrefixedName). The default is "modal". This specification does not define behavior for PrefixedName values.
hide
Optional boolean, indicating if the processor should provide a way to hide the dialog. The default value is true. On a graphical browser an "x" could be shown in the dialog title bar when hide is set to true. If you specify hide="false", then you should provide a way to hide the dialog, for instance by having you own "Close" button inside the dialog. This is typically useful when you want to force users to enter some data before proceeding and you don't want them to cancel the current operation by closing the dialog.

Content: (Controls|UI Common)*

When a modal dialog is shown the user can't interact with any control on the page outside of that dialog. A graphical browser could visualize this by shielding the document with a partially transparent mask when a modal dialog is shown.

The dialog generates an implicit group that contains the content elements (i.e. controls and host language elements). When the dialog is shown the implicit group is enabled, when the dialog is hidden the implicit group is disabled.

Note: It should be possible to show a new dialog from within a modal dialog.

<dialog id="my-dialog" label="Please enter your information">
  <input ref="first-name" label="First Name:"/>
  <input ref="last-name"  label="Last Name:"/>
  <input ref="e-mail" label="E-mail:"/>
  <trigger label="Submit">
    <hide ev:event="DOMActivate" dialog="my-dialog"/>
  </trigger>
</dialog>

A graphical browser might render the above dialog as follows:

An example dialog

The show Element

This action shows a specified dialog.

Common Attributes: Action Common

Special Attributes:

dialog
Required reference to the ID of a dialog element.

Content: EMPTY

An update is done if necessary.

A dialog element is identified using the dialog attribute. If no such element exists, this action has no effect.

An xforms-dialog-show event is dispatched to the identified element.

The hide Element

This action hides a specified dialog.

Common Attributes: Action Common

Special Attributes:

dialog
Required reference to the ID of a dialog element.

Content: EMPTY

An update is done if necessary.

A dialog element is identified using the dialog attribute. If no such element exists, this action has no effect.

An xforms-dialog-hide event is dispatched to the identified element.

The xforms-dialog-show Event

Dispatched in response to a show action executed with an existing dialog id.

Target:dialog Bubbles: Yes Cancelable: Yes Context Info: none

Default action: Show the dialog if it isn't shown already.

The default action for this event results in the following steps:

  1. Adjusts the shown state of the dialog.
  2. Makes the dialog available to the user.
  3. Dispatches the xforms-dialog-shown event

The xforms-dialog-hide Event

Dispatched in response to a hide action executed with an existing dialog id.

Target: dialog Bubbles: Yes Cancelable: Yes Context Info: none

Default action: Hide the dialog if it isn't hidden already.

The default action for this event results in the following steps:

  1. Adjusts the shown state of the dialog.
  2. Makes the dialog unavailable to the user.
  3. Dispatches the xforms-dialog-hidden event

The xforms-dialog-shown Event

Dispatched in response to a dialog being shown.

Target:dialog Bubbles: Yes Cancelable: No Context Info: none

Default action: none; notification event only.

The xforms-dialog-hidden Event

Dispatched in response to a dialog being hidden.

Target: dialog Bubbles: Yes Cancelable: No Context Info: none

Default action: none; notification event only.

The repeat Element

This container control binds to a sequence of values, allowing a user interface to be generated for each item in the sequence.

Common Attributes: Common, Evaluation, Appearance, Sequence Binding

Special Attributes:

indexref
Optional Single Item Binding to simpleContent, with which the repeat index is synchronized.
startindex
Optional 1-based initial value of the repeat index. The default value is 1. This attribute is ignored if indexref is specified.
number
Optional hint of how many elements of the repeat collection to display.

Content: (Controls|Action)*

A repeat control consists of

  • a sequence of items called the repeat collection;
  • an index into that collection called the repeat index, with a value between 0 and the size of the collection (only ever zero if the sequence is empty), that indicates which repeat item has, or last had, the user focus;
  • an optional index reference which reflects the current value of the index; and
  • the repeat template, which is a copy of the original content of the repeat element.

For each item in the repeat collection, a repeat item is defined, consisting of the item, and a repeat object consisting of an implicitly generated group element that binds to the item, and containing a copy of the template. Unlike an explicit group, the binding to the item does not reset the size and position of its context.

These repeat objects together form the run-time content of the repeat.

That is to say, a repeat like

<repeat ref="/products/product" class="list">
  <output ref="."/><html:br/>
</repeat>

is conceptually similar to

<group class="list">
   <group ref="/products/product[1]"><output ref="."/><html:br/></group>
   <group ref="/products/product[2]"><output ref="."/><html:br/></group>
   <group ref="/products/product[3]"><output ref="."/><html:br/></group>
   <group ref="/products/product[4]"><output ref="."/><html:br/></group>
</group>

Note: the repeat collection can be an arbitrary sequence of items: nodes, atomic values or a mix. They don't have to be in document order, and the same node can occur multiple times.

Repeat Processing

Repeat Initialization

During user interface initialization (see The xforms-model-construct-done Event), the following steps are performed:

  1. The Sequence Binding is evaluated to give the repeat collection;
  2. The repeat index is initialized:
    1. If the collection is empty, 0 is used; otherwise
    2. If the indexref attribute is specified, it is evaluated as a number in the in-scope evaluation context and rounded to the nearest integer. If it is a number it is used, and otherwise 1; otherwise
    3. If the startindex attribute is specified, its value is used;
    4. Otherwise 1 is used.
    If the resulting value is less than 1, and the sequence is not empty, 1 is used, otherwise if it is larger than the size of the collection, the size of the collection is used.
  3. A repeat object is generated for each repeat item using the repeat template.
Updating

Whenever a new item is added to the repeat collection, by whatever means, a new repeat item is created dynamically, and the resulting repeat object is initialized.

Whenever an item is removed from the repeat collection, by whatever means, the corresponding repeat object is eliminated.

These actions must be done before the dispatch of the xforms-insert and xforms-delete events, so that event handlers for them have access to the new value of the repeat index.

Index Processing

If indexref has been specified for a repeat, it is kept up-to-date with the current value of the repeat index: if the repeat index changes, indexref is changed to match, and vice versa. However, this is only possible if indexref references a node that is not readonly. If it is, changes to indexref will change the repeat index, but not vice versa.

If a new value of the repeat index is ever greater than the size of the repeat collection, the repeat index is set to the size of the repeat collection and the xforms-scroll-last event is dispatched to the repeat.

Similarly, if a new value is ever less than 1 (or 0 for an empty sequence), then xforms-scroll-first is dispatched to the repeat element, and the index is set to 1 (or 0 for an empty sequence).

If items are added to the repeat collection, then the repeat index is set to the position of the last item added.

If items are removed from the repeat collection:

  • if, prior to deletion, the repeat index indicated an item still contained in the collection after deletion, then the index is adjusted as necessary to indicate the same item;
  • if the repeat index indicated one of the deleted items and the new size of the collection is smaller than the index, the index is changed to the new size;
  • otherwise the index is not changed.

Whenever a repeat index is changed, focus is given to the corresponding repeat element, as if by a setfocus action.

Note: the value of the repeat index is also available via the index() function, and can be set with the setindex action.

Note: attributes that contain an IDREF must be interpreted based on a combination of repeat indexes and where the IDREF attributes appear relative to the element bearing the matching ID. See Resolving ID References, for details.

Interaction and rendering

Repeat items should have a block layout by default (e.g. a CSS styling of display:block). If the repeat element has an appearance attribute with the value minimal, then the repeat items have an inline layout:

<repeat appearance="minimal" ref="keyword">
   <output value="concat(., if(last(), '', ', '))"/>
</repeat>


This can also be achieved with the CSS pseudo-element repeat-item, for instance:

.list ::repeat-item {display: inline}
<repeat class="list" ref="1 to 10">
  <output ref="."/>
</repeat>

The rendering of the repeat item currently referred to by the repeat index can be displayed specially using the pseudo-element ::repeat-index:

::repeat-index {background-color: yellow}

The number of displayed items might be less than the total number available in the collection; for example, responding to the count attribute hint, a graphical user interface might present a scrolling table. The current item indicated by the repeat index should be made available to the user at all times, and not allowed to scroll out of view.

If the focus is given to a control within a repeat by any means, such as by an XForms action or by user interaction, the repeat index is set to the position of the repeat item that contains the control, and the repeat index of all containing repeats are adjusted appropriately. A repeat index is changed as if by a setindex action.

If focus is given to a repeat element, focus goes to the first enclosed control in navigation order that can accept focus within the repeat item indicated by the repeat index.

If an item of the repeat collection is non-relevant, then the associated repeat object is disabled.

Events and Actions

Since repeat objects are copies of the repeat template, including action handlers, the action handlers for events targeted at a repeat element should be placed outside of the repeat template, for example:

<repeat id="X" ... >
  ...
</repeat>

<action ev:event="xforms-scroll-first" ev:target="X" ev:observer="X">
  ...
</action>
Examples
<instance>
   <countries>
      <country capital="Paris">France</country>
      <country capital="Rome">Italy</country>
      <country capital="Amsterdam">The Netherlands</country>
   </countries>
</instance>
<repeat ref="country">
   <output label="Country" ref="."/>
   <output label="Capital" ref="@capital"/>
</repeat>
<repeat ref="1 to count(table)">
  <output value="table[.]" label="[{.}]:"/>
</repeat>

Given the instance:

<instance>
   <description xmlns="">
       <function>sqrt</function>
       applied to:
       <x>6.25</x>
       <!-- gives two results -->
       <r>2.5</r>
       <r>-2.5</r>
   </description>
</instance>

Using node() and name():

<repeat ref="node()">
   <output ref="." label="{name(.)}"/>
</repeat>

would give

function sqrt
#text    applied to: 
x        6.25
#comment gives two results 
r        2.5
r        -2.5

while using * and name

<repeat ref="*">
   <output ref="." label="name(.)"/>
</repeat>

would give:

function sqrt
x        6.25
r        2.5
r        -2.5
<instance>
   <lines xmlns="">
      <line name="a"><price>3.00</price></line>
      <line name="b"><price>32.25</price></line>
      <line name="c"><price>132.99</price></line>
   </lines>
   <i/>
</instance>
<repeat ref="line" indexref="i">
  <input ref="@name" label="Name"/>
  <input ref="price" label="Price"/>
</repeat>

<trigger label="Insert a new item after the current one">
  <action ev:event="DOMActivate">
    <insert ref="line" at="i" position="after"/>
    <setvalue ref="line[i]/@name"/>
    <setvalue ref="line[i]/price">0.00</setvalue>
  </action>
</trigger>

<trigger label="remove current item">
  <delete ev:event="DOMActivate" ref="line" at="i"/>
</trigger>

Creating Repeating Structures Via Attributes

When using XForms within host languages like XHTML, it can be necessary to create repeating structures within constructs that don't accept the repeat element as content, such as table.

To help integrate repeat behavior into host languages, there is an alternative syntax using the following global attributes that is functionally equivalent to the repeat element:

xforms:repeat-model
xforms:repeat-bind
xforms:repeat-ref
xforms:repeat-nodeset (deprecated)
xforms:repeat-startindex
xforms:repeat-number
xforms:repeat-indexref

These attributes are equivalent to the local repeat attributes of the comparable name. A host language can allow these attributes in the appropriate places to enable repeating constructs.

When using the setindex action, its repeat attribute of type idref can point to any element carrying these global repeat attributes.

Similarly, when using function index for a repeating structure created using the global repeat attributes, the id of that element can be used as the argument to function index.

A version of XHTML might allow the following:

<table xforms:repeat-ref="...">
  <tr>
<td><xforms:output ref="..."/> </tr> </table> Note that what gets repeated is the content of the element with the global repeat- attributes, i.e. in this case, the tr is repeated, not the table.
<table>
   <thead>
Country Capital </thead> <tbody xforms:repeat-ref="countries/country"> <tr> <td><xforms:output ref="."/> <td><xforms:output ref="@capital"/> </tr> </tbody> </table>

Submission

Submitting data happens as a response to a submission element receiving an xforms-submit event. This is typically dispatched by a submit control, or a send action.

In brief: the data to be submitted is selected, checked for validity if necessary, serialized, and sent to the receiving service. When the reply is received, it is checked for success, and any associated data is then processed as required.

Element Attributes and Their Content (after AVT evaluation) Minimal Content Model
submission

Common
Evaluation
Single Item Binding
value (expression)
nonrelevant ("keep" | "remove" | "empty")
relevant (xs:boolean) [deprecated]
validate (xs:boolean)

resource (xs:anyURI)
action (xs:anyURI) [deprecated]
mode ("asynchronous"|"synchronous")
method ("post" | "get" | "put" | "delete" | "multipart-post" | "form-data-post" | "urlencoded-post" | Any other NCName | PrefixedName)
serialization (xs:string)
mediatype (xs:string)
encoding (xs:string)

separator (";" | "&")

version (xs:NMTOKEN)
indent (xs:boolean)
omit-xml-declaration (xs:boolean)
standalone (xs:boolean)
cdata-section-elements (QNameList)
includenamespaceprefixes (xs:NMTOKENS)

response-mediatype (xs:string)
replace ("all" | "instance" | "text" | "none" | PrefixedName)
instance (xs:IDREF)
targetref ( Single Item Binding)
target ("_self" | "_blank" | xs:string)

(resource [deprecated] | method [deprecated] | header)*, Action*

The following table summarizes the child elements of the submission element. Elements defined in the Actions module are also allowed.

Element Attributes and Their Content (after AVT evaluation) Minimal Content Model
resource (deprecated) Common, Evaluation, value (string Expression) PCDATA
method (deprecated) Common, Evaluation, value (string Expression) PCDATA
header Common, Evaluation, Sequence Binding, name (xs:string), value (string Expression) name [deprecated], value+ [deprecated]
name (for header) (deprecated) Common, Evaluation, Sequence Binding, name (xs:string), value (string Expression) PCDATA
value (for header) (deprecated) Common, Evaluation, Sequence Binding, name (xs:string), value (string Expression) PCDATA

Action

various various

The submission Element

The attributes of submission can be divided into three groups, describing what is to be submitted, how it is to be submitted, and what to do with the result.

Common Attributes: Common, Evaluation

Special Attributes:

What to submit:

Single Item Binding
Optional binding that selects the data to be submitted: the node and all its descendants are selected. The default is "/".
value
Optional expression, overriding the single item binding, that calculates a value representing the data to be submitted. If this attribute is present, the relevant, nonrelevant, validate and serialization attributes are ignored.
nonrelevant
Optional string indicating whether non-relevant values are included in the serialized data; it has no effect if serialization is "none". Values are "keep": all values are serialized, "remove": non-relevant values are not serialised, "empty": non-relevant nodes are serialized as empty values. The default is "remove".
relevant [deprecated in favor of attribute nonrelevant]
Optional boolean indicating whether only relevant data is serialized. This attribute has no effect if nonrelevant is specified, or serialization is "none". Values are "true": equivalent to nonrelevant="remove", and "false": equivalent to nonrelevant="keep". The default is "true".
validate
Optional boolean indicating whether data validation is performed. The default is "false" if the value of serialization is "none" and "true" otherwise.

How to submit it:

resource
URI indicating the destination for the submission. This attribute is required unless the destination URI is provided by the (deprecated) resource element, or the (deprecated) action attribute. Behavior of relative URIs in links is determined by the host language, although [XML Base] processing is strongly recommended.
action [deprecated]
Optional URI indicating the destination for the submission. Use resource for preference.
mode
Optional string defaulting to "asynchronous" and with legal values of "synchronous" and "asynchronous". This controls whether or not user interaction can continue while the submission is in progress, or whether the system blocks until the result has been received.
method
Optional string specifying the protocol method to be used to transmit the submission, with a default of "get". See Section Submission Protocols for information on how this attribute affects the default serialization of instance data and the HTTP method [RFC 2616].
serialization
Optional string that controls how to serialize the submission data. The format is type/subtype, or the single word "none". Allowable values are "application/xml", "application/x-www-form-urlencoded", "multipart/related", "multipart/form-data", or any of the values allowed in the section Creating instance data from external resources. The default value of this attribute is based on the submission method as described in Section Submission Protocols. If the attribute value is "none", then instance data is not serialized, which is useful for requests that either require no data or that have the data already in the URI.
mediatype
Optional string specifying the mediatype of the serialization, to be used in the Content-type header of HTTP, or similar, according to the format specified in [RFC 2616]. It is the author's responsibility to ensure that the type specified is compatible with the serialization used, such as application/xhtml+xml for posted XML data. The default is serialization-dependent, but is "application/xml" for XML serialization.
Note: This attribute does not affect serialization nor does it override the serialization attribute. It is only used to provide additional information about the submission data.
encoding
Optional string specifying the character encoding to be used for serialization. The default is "UTF-8".

If the data is serialized as urlencoded, the following attribute applies:

separator
Optional string specifying the separator character between name/value pairs if the serialization used is "application/x-www-form-urlencoded"; otherwise the attribute is ignored. The default is '&'.

If the data is serialized as XML, the following attributes apply:

version
Optional string specifying the version of XML to be serialized. The default is "1.0".
indent
Optional boolean specifying whether the serializer should add extra white space nodes for readability. The default is "false".
omit-xml-declaration
Optional boolean specifying whether to omit the XML declaration on the serialized instance data. The default value is "false".
standalone
Optional string specifying whether to include a standalone declaration in the serialized XML. If omitted, then the XML declaration does not include a standalone document declaration; if the omit-xml-declaration attribute has the value true, this attribute is ignored; otherwise the XML declaration includes a standalone document declaration with the same value as this attribute.
cdata-section-elements
Optional string specifying element names to be serialized with CDATA sections. The default is empty string.
includenamespaceprefixes
Optional string 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 #default specifies the default namespace. When this attribute is present all namespace prefixes not visibly utilized by the submitted instance data are listed.

What to do with the result:

response-mediatype
Optional mediatype overriding the content-type reported for the returned data.
replace
Optional string specifying how the information returned after submit should be applied. The legal values are "all", "instance", "text" and "none", with a default of "all". See Processing the Response from a Submission.
instance
Optional IDREF identifying the instance to replace when the replace attribute value is "instance". The default is the instance that contains the submission data. When the replace value is not "instance", this attribute is ignored.
targetref
Optional Single Item Binding that indicates the target node for data replacement. The in-scope evaluation context of the submission element is used to evaluate the expression. If replace is "instance", then the target node is replaced by the submission result. If replace is "text", then the content of the target node is replaced by the submission result. For other values of the replace attribute, this attribute is ignored. By default, the target node is the document element of the instance indicated by the instance attribute.
target
Optional presentation context name or keyword when the replace attribute value is "all". Behavior is defined for values "_self" and "_blank"; the default is "_self". In addition, an implementation-dependent presentation context name can be specified. The following are the possible values for the target attribute and the corresponding processing behaviors:
_self
The document is loaded into the current presentation context. Form processing is interrupted, exactly as if the user had manually requested navigating to a new document.
_blank
The document is loaded into a new presentation context, e.g., a new window or tab. Form processing in the original window or tab continues.
Any other value
The behavior is implementation-dependent.
Note:

If the host language is HTML, the implementation is encouraged to handle the target attribute as defined in HTML for the form element. In particular, values of "_self", "_blank", "_parent", "_top", as well as browsing context names should be supported.

Content: (resource [deprecated] | method [deprecated] | header)*, Action*

<submission
   resource="http://example.com/search"/>

 <submission
   resource="http://example.com/search"
   method="put"/>

 <submission
   resource="http://example.com/search"
   replace="instance"
   instance="results"/>

 <submission
   ref="instance('reference')"
   resource="http://example.com/locate-address"
   replace="instance"
   instance="address"/>

 <submission
   ref="instance('address')"
   resource="http://example.com/new-address"
   method="post"
   replace="none"/>

 <submission id="s1"
   resource="http://example.org/api.php?action=search&format=json&search={search}"
   mediatype="application/json"
   serialization="none"
   mode="synchronous"
   replace="instance"
   instance="iresults"/>

The header Element (for submission)

This element is used to change headers, or add extra headers to a submission protocol.

Common Attributes: Common, Evaluation, Sequence Binding, value

Special Attributes:

name
Optional string that overrides the name child element if present.
combine
Optional string defaulting to "append" and with legal values of "append", "prepend", and "replace". Controls the method of combination for entries produced by this element header with other entries produced by other header elements. This attribute and its default also provide information for the protocol implementation, which may use some or all of the information to combine submission headers with headers provided by the user agent.

Any value attribute present overrides all value child elements.

Content: PCDATA | (name, value+) | (value+, name)

The submission element can contain zero or more header child elements: each produces zero or more header entries containing a name and a value, and how they are to be combined with existing headers. 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 suitably.

  • If the header element contains a name attribute, it is used for name of the headers being produced; otherwise there must be a name child element, which is used instead. If the name evaluates to the empty string, no header is produced.
  • If the header element has a Sequence Binding, then for each selected item, the values are evaluated; otherwise the values are evaluated once.
  • The values are evaluated as follows: if the header element has a value attribute, one header is produced using the name of the header being produced, and the evaluated content of the value attribute; otherwise if there are one or more value child elements, one header is produced per value child element; otherwise one header is produced using the inline content of the element.

The header entry order is determined as follows:

  1. document order of header elements
  2. item order of items in ref attribute
  3. document order of value elements

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.

<submission
   id="loadConcepts"
   resource="http://example.com/taxonomy/concepts"
   method="get"
   ref="instance('conceptsList')"
   replace="instance">
   <header name="Accept"
     combine="replace">application/sparql-results+xml</header>
 </submission>

The submission uses the header element to replace the user agent's existing value of the HTTP Accept header with application/sparql-results+xml. Note that the name attribute is a string, but that value, like all such-named attributes in XForms, is an expression, and so the value must be quoted if it is a string.

<instance id="headers">
  <my-headers>
    <my-header><head>Content-Type</head><content>application/xml</content></my-header>
    <my-header><head>Accept</head><content>application/xml,application/json</content></my-header>
  </my-headers>
</instance>
<submission ...>
   <header
     ref="instance('headers')/my-header"
     name="{head}"
     value="content"/>
</submission>

This example produces 2 headers:

Content-Type: application/xml
Accept: application/xml,application/json
The name Element (for header) (Deprecated)

This element, deprecated in favor of using an AVT in the name attribute of the header element, specifies the name of a header entry to be provided to the submission protocol.

Common Attributes: Common, Evaluation, value

Content: PCDATA

If the model attribute is present and does not identify the containing model, an xforms-binding-error is dispatched to the name element.

The header entry name is obtained by evaluating the value attribute if present, and otherwise from the element content. If the result is the empty string, then the entry is considered to be void, and it is not supplied to the submission protocol.

<name>Accept</name>
<name value="'Accept'"/>
<name value="../header"/
The value Element (for header) (Deprecated)

This element, deprecated in favor of using an AVT in the value attribute of the header element, specifies the value component of a header entry; it may be used more than once in a given element header, in which case each value produces a new header entry.

Common Attributes: Common, Evaluation, value

Content: PCDATA

If the model attribute is present and does not identify the containing model, an xforms-binding-error is dispatched to the value element.

The header entry value is obtained by evaluating the value attribute if present, or otherwise from the string content of the value element.

<value>text/css</value>
<value value="'text/css'"/>
<value value="../accepted"/

Note: The string conversion function as described in the expression module combines multiple items by concatenating them into a string separated with spaces. As a result, a header value specified by a value element sequence containing multiple items 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 expressions producing sequences for element header with attribute ref, where each item will produce its own separate header entry, and use expressions resulting in only a single item in element value.

The resource Element (Deprecated)

The resource element (deprecated in favor of using an AVT in the resource attribute) provides the URI used for a submission.

Common Attributes: Common, Evaluation, value

Content: PCDATA

The URI is obtained by evaluating the value attribute, or otherwise from the inline content of the element.

If a submission has more than one resource child element, the first is used.

 <submission method="post">
    <resource value="instance('params')/anyURI"/>
 </submission>
 <submission method="get">
    <resource>http://www.example.com/index.html</resource>
 </submission>

These are deprecated in favour of the equivalent:

 <submission method="post" resource="{instance('params')/anyURI}"/>
 <submission method="get" resource="http://www.example.com/index.html"/>

The method Element (Deprecated)

The method element (deprecated in favor of using an AVT in the method attribute) provides the method to be used by a submission.

Common Attributes: Common, Evaluation, value

Content: PCDATA

The method to be used is obtained by evaluating the value attribute, or otherwise from the string content of the method element.


Submission Processing

In brief, data is selected, checked for validity as necessary, serialized in the required form, and sent to the server. The server sends a response, possibly accompanied by some data which is then dealt with appropriately.

No more than a single submit process can be under way at any time for a particular submission element. 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 for those submissions to fail with submission-in-progress.

For brevity in the following, the text "submission succeeds" means "submission processing concludes after dispatching xforms-submit-done to the submission element, with appropriate context information", and the text "submission fails with error-code" means "the submission processing concludes after dispatching xforms-submit-error to the submission element, with appropriate context information, including an error-type of error-code". Additionally, "and an error-message of some value" means that the context information also includes an entry called error-message with that value.

Selecting and Validating the Submission Data

If the serialization attribute value is "none", no data is selected.

Otherwise an update is done if necessary.

  • If the value attribute is present, it is evaluated and converted to a string.
  • Otherwise, the binding attributes of submission are evaluated; if the result is the empty sequence or an item other than an element or an instance document root node, submission fails with no-data. A copy of the evaluated node and its descendent nodes are selected. Non-relevant nodes are either deselected, or made empty, according to the value of the nonrelevant attribute, or the deprecated relevant attribute. If no nodes remain, submission fails with no-relevant-data. If the attribute validate is true, whether by default or declaration, and any selected instance data node is invalid, submission fails with validation-error.

Serializing the Data

The submission method is obtained from the method attribute if present, otherwise from the first method child element if any, and otherwise is "get".

The submission resource is obtained from the resource attribute if present, otherwise from the deprecated action attribute if present, and otherwise from the first resource child element, if any; otherwise submission fails with resource-error.

If the value of the submission resource is an absolute URI it is used as the submission URI; otherwise (it is a relative URI) the submission URI is constructed by combining the relevant parts of the value of location-uri() and the submission resource.

The protocol to be used is determined from the submission URI.

The serialized data is obtained:

  • If the serialization attribute value is "none", then the empty string is used.
  • Otherwise, the (deprecated) xforms-submit-serialize event is dispatched to the submission element; if the submission-body property of the event is changed from the initial value of empty string, then its content is used.
  • Otherwise, if the value attribute was present, then the string obtained from evaluating that is used.
  • Otherwise, the default serialization format is determined according to the rules stated in Submission Protocols, based on the method and the protocol; if the default is application/xml and the serialization attribute contains a value, that value is used; otherwise the default format is used; the selected data is then serialized in that format according to the rules stated in Serialization Formats.

Submitting the Data

If the data is non-empty and is to be delivered as part of the URI (and has therefore been serialized as application/x-www-form-urlencoded):

  • if the submission URI doesn't contain a ? (question mark) character, one is appended;
  • otherwise if it doesn't end with the separator character from the separator attribute or its default, one is appended;
  • finally the serialized data is appended.

The submission headers are determined using the header entries produced by the header element(s) in the submission and the mediatype attribute or its default.

The submission is performed using the submission headers, method, resource, and serialized data, as defined in Submission Protocols.

If the mode of the submission is asynchronous, processing ends after the above steps. 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 user interaction with all document controls and action processing is suspended until the response from the submission is returned.

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.

<submission resource="..." ...>
   <message ev:event="xforms-submit-error">
      Submission error.
         error-type: <output value="event('error-type')"/>
         error-message: <output value="event('error-message')"/>
         resource-uri: <output value="event('resource-uri')"/>
         response-status-code: <output value="event('response-status-code')"/>
         response-reason-phrase: <output value="event('response-reason-phrase')"/>
   </message>
</submission>

Processing the Response from a Submission

For success responses, if the response does not include a body, submission succeeds; otherwise, processing depends on the value of the replace attribute on element submission:

  • none: submission succeeds.
  • all: the event xforms-submit-done may be dispatched with appropriate context information, and submit processing concludes with the entire containing document being replaced with the returned body.
  • instance: If the type of the body, as overridden by the response-mediatype attribute if present, is not amongst those accepted by the processor, as specified in Creating instance data from external resources, nothing in the document is replaced and submission fails with result-mediatype, and an error-message of the unacceptable mediatype. Otherwise the body is parsed to give an XPath Data Model according to Creating instance data from external resources. If the parse fails, then submission fails with parse-error. If the parse succeeds, then instance data replacement is performed according to Replacing Data with the Submission Response. If this operation succeeds, submission succeeds.
  • text: If the type of the body, as overridden by the response-mediatype attribute if present, is neither amongst those accepted by the processor, as specified in Creating instance data from external resources, nor a text type (i.e. with a content type not matching text/*), nothing in the document is replaced and submission fails with result-text-mediatype, and an error-message of the unacceptable mediatype. Otherwise the content replacement is performed according to Replacing Data with the Submission Response. If this operation succeeds, submission succeeds.

For error responses, processing depends on the value of the replace attribute on element submission:

  • all: either the document is replaced with an implementation-specific indication of an error, or submission fails with result-error-response.
  • any other value: nothing in the document is replaced, and submission fails with result-error-response.

(Further details of the failure are available in the context information).

Behaviors of other possible values for attribute replace are not defined in this specification.

In addition to initiating a submission with its default processing, XForms actions can also provide handlers for the xforms-submit event to perform tasks such as data preparation.

<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.

Replacing Data with the Submission Response

First, the replacement target node is determined from the attributes of the submission element:

  • if there is neither an instance attribute nor a targetref attribute, the replacement target node is the document element node of the default instance of the model;
  • if there is an instance attribute but no targetref attribute, the replacement target node is the document element node of the instance identified by the instance attribute;
  • if there is a targetref attribute, it is evaluated in the in-scope evaluation context for the submission element to obtain the replacement target node, except the context item is modified to be the document element of the instance identified by the instance attribute if present.

Then the target is checked for correctness:

  • if the instance attribute does not indicate an instance in the same model as the submission, submission fails with target-model-error;
  • if the replacement target node is the empty sequence, submission fails with target-empty;
  • if replace="text" and the replacement target node is a readonly node, or, if replace="instance" and the replacement target node is a node whose parent is readonly, submission fails with target-readonly;
  • if replace="instance" and the replacement target node is a non-element, submission fails with target-non-element.

Then the replacement is done according to the value of the replace attribute:

  • text: the response data is encoded as text, regardless of its mediatype, and used to replace the content of the replacement target node using the setvalue action.
  • instance: the XPath Data Model obtained from the submission response is used to replace the target node. This data 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. The replacement is performed as a combination of node insertion and deletion operations.


Note:

For backwards compatibility with earlier versions of this specification, the processor may treat an attribute named target as equivalent to targetref as long as there is no targetref attribute present.

Note:

In an asynchronous submission, the replacement action is an outermost action handler, and so update behavior ensures that the user interface is up to date with the latest calculated values before the xforms-submit-done event is dispatched. With a synchronous submission, the replacement action is not outermost since it occurs during the default processing of xforms-submit; 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 update 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.

<submission
   resource="http://example.com/search"
   replace="instance"
   instance="results"/>
<submission
   resource="http://example.com/search"
   response-mediatype="application/xhtml+xml"
   replace="instance"
   instance="results"/>

On occasions servers report a wrong or misleading mediatype, or use a mediatype that obscures that the underlying data is in an XML format. The response-mediatype allows you to override that.

<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.

<submission
   resource="http://example.com/postalCodeSearch"
   method="get"
   ref="address"
   replace="text"
   targetref="address/postalCode"/>

The address information is passed to a postal code search service that returns a textual result, which is placed into the postalCode element.

<model>
  <instance>
    <data xmlns="">
      <name>
        <first-name>John</first-name>
        <last-name>Doe</last-name>
      </name>
      <address>
        <street>123 Main St.</street>
        <city>Smallville</city>
      </address>
    </data>
  </instance>

  <bind ref="name" readonly="true()"/>
  <bind ref="address/street" readonly="true()"/>

  <submission id="S1" targetref="name" replace="instance" method="post" resource="..."/>
  <submission id="S2" targetref="name/first-name" replace="instance" method="post" resource="..."/>

  <submission id="S3" targetref="name/first-name" replace="text" method="post" resource="..."/>
  <submission id="S4" targetref="address/street" replace="text" method="post" resource="..."/>
</model>

Submission S1 succeeds because a readonly node (name) can be replaced if its parent is not readonly. Submission S2 fails because a node (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 fails because the content of a readonly node cannot be replaced, even if the node's parent is not readonly.

Submission Protocols

How instance data is submitted depends on two aspects:

  • the submission protocol, which is determined by the URI scheme in the submission resource, and
  • the submission method within the protocol, given by the method attribute, and which also determines the default data serialization format:
URI Scheme

Method

Default Serialization Protocol
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 [Deprecated] multipart/related HTTP POST or equivalent
http https mailto form-data-post [Deprecated] multipart/form-data HTTP POST or equivalent
http https mailto urlencoded-post [Deprecated] application/x-www-form-urlencoded HTTP POST or equivalent
(any)

Any other NCName

application/xml

As given by the Submission Method

(any)

PrefixedName

implementation-defined implementation-defined

Note: Foreign-namespaced attribute values are allowed in the Submission Method, but no behavior is defined for them.

The HTTP and HTTPS Protocols

Processors must support HTTP/1.1 [RFC 2616], and HTTPS [RFC 2818].

Seven methods are supported in these protocols: get, put, delete, post, and three versions of post but with different default serializations: multipart-post, form-data-post, and urlencoded-post, all three methods deprecated in favor of using post with the corresponding value of serialization.

  • get: The serialized form data is delivered as part of the URI that is used during the submit process.
  • put: The serialized form data is delivered as the message body.
  • post, multipart-post, form-data-post, and urlencoded-post: The serialized form data is delivered as the message body.
  • delete: The serialized form data is delivered as part of the URI, in the same manner as with get.

Authors are encouraged to follow the finding of the W3C Technical Architecture Group on when to use the GET method: [TAG Finding 7]. See also [RFC 2616] for recommended uses of HTTP GET.

<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.

<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.

<submission
   resource="https://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.

<submission
  resource="../data/temporary.xml"
  method="delete"
  serialization="none"
  replace="none"/>

The File Protocol

Standalone and offline XForms applications can be greatly helped by being able to store and retrieve data locally without recourse to a server. Processors should support the File protocol [RFC 8089]; processors may sandbox the area used for files.

In XForms, the File protocol supports three methods:

  • get: All serialized data, if any, is ignored. A file-open dialog is initiated with the user, initialised to the location given in the URI. The user can accept this suggestion, or choose another file as replacement. If the chosen file is readable, its contents are returned as the body of the response, with a suitable mediatype, and the submission succeeds; if the file is not readable, the submission fails with result-error-response and an error-message of file not readable.
  • put: A file-save dialog is initiated with the user, initialised to the location given in the URI. The user can accept this suggestion, or choose another file location and name as replacement. If the chosen location is writable, its contents are initialised or replaced with the serialized data of the submission, and the submission succeeds; if the location is not writable, the submission fails with result-error-response and an error-message of file not writable.
  • delete: All serialized data, if any, is ignored. A file-delete dialog is initiated with the user, initialised to the location given in the file URI. The user can accept this suggestion, and if the file is deletable, it is deleted, and the submission succeeds; if the file is not deletable, the submission fails with result-error-response and an error-message of file not deletable.

In all three cases, the user can cancel the dialog, in which case the submission fails with result-error-response and an error-message of cancelled.

A submission using any other method with a file: URI fails with result-error-response and an error-message of method not supported.

<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.

<submission
  resource="file:data.xml"
  ref="instance('data')"
  method="put"
  validate="false"
  nonrelevant="keep"
  replace="none"/>

Saves the instance 'data' to the file data.xml without validation checking and relevance pruning.

The Mailto Protocol

Processors may support the mailto: protocol [RFC 6068].

It supports four methods: post, multipart-post, form-data-post, and urlencoded-post, of which the last three are deprecated in favour of using post with a corresponding value of serialization. For all four methods, the serialized data is delivered as the body of the submission.

<instance id="mail">
    <mail to="registrations@example.com" xmlns="">
       <subject>Conference registration</subject>
       <cc>secretariat@example.com</cc>
       <body>Please register me for your conference.</body>
    </mail>
 </instance>
<bind ref="to|cc" type="iemail"/>

<submission ref="instance('mail')" resource="mailto:{instance('mail')/@to}" method="urlencoded-post" replace="none"/>

Serialization Formats

application/xml

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 submission element.

Namespace nodes: 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 includenamespaceprefixes on element submission is 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 the includenamespaceprefixes attribute. The special value #default represents the default namespace.

Mediatype: The default mediatype is application/xml, but can be changed to a compatible type using element submission attribute mediatype. Authors should ensure that the type specified is compatible with application/xml.

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 xs:boolean to replace "yes"|"no": version, indent, encoding, omit-xml-declaration, cdata-section-elements. There are no counterparts for doctype-system or doctype-public.

Note:

We are considering adding extra serialization parameters added by http://www.w3.org/TR/xslt-xquery-serialization/, but are waiting for further implementation experience and user feedback to decide which to add.

The following examples show how attribute includenamespaceprefixes on element submission can affect serialization as application/xml. Given the following XForms fragment:

<model
   xmlns:xforms="http://www.w3.org/2002/xforms"
   xmlns:foo="http://example.org/foo">
   <instance>
     <foo:qname
       xmlns=""
       xmlns:bar="http://example.org/bar"
       xmlns:baz="http://example.org/baz">bar:sample</foo:qname>
   </instance>
   <submission
     method="post"
     resource="..."/>
</model>

The includenamespaceprefixes attribute is not present, which causes all namespace nodes in the instance data (as created following the rules set in The instance Element) to be serialized, resulting in the following serialized instance data:

<foo:qname
   xmlns:foo="http://example.org/foo"
   xmlns:bar="http://example.org/bar"
   xmlns:baz="http://example.org/baz">bar:sample</foo:qname>

If instead the includenamespaceprefixes is present as follows:

<submission
  method="post"
  resource="..."
  includenamespaceprefixes=""/>

Then the serialized XML looks like this:

<foo:qname
   xmlns:foo="http://example.org/foo">bar:sample</foo:qname>

Note that xmlns:foo="http://example.org/foo" is present even if not listed because it is used by an element qualified name. On the other hand the other namespaces are not present because they are not used by element or attribute qualified names and are not listed.

If instead the includenamespaceprefixes is present as follows:

<submission
  method="post"
  resource="..."
  includenamespaceprefixes="bar"/>

Then the serialized XML looks like this:

<foo:qname
   xmlns:foo="http://example.org/foo"
   xmlns:bar="http://example.org/bar">bar:sample</foo:qname>

multipart/related

XML instance data is serialized as one part of the [RFC 2387] multipart/related message, using the rules as described in Serialization as application/xml. Binary content from xs:anyURI instance nodes populated by the upload (see 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/related message header requirements:
    • Must contain a type parameter of the mediatype of the serialized XML instance.
    • Must contain a start parameter referring to the Content-ID first body part (root).
  • First body part (root) requirements:
    • Must have Content-Type parameter of the type specified by the submission mediatype attribute.
    • Content is serialized by the rules at Serialization as application/xml.
  • Subsequent part requirements:
    • One part for each node with a datatype of xs:anyURI populated by upload with:
      • A Content-Type header that represents the type of the attachment if known, otherwise application/octet-stream.
      • A Content-Transfer-Encoding header.
      • A Content-ID header whose value matches the URI in the associated instance data node.
      • The binary content associated with the URI, serialized according to the Content-Transfer-Encoding heading.
<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--

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, ignoring or treating as empty non-relevant elements according to the nonrelevant attribute or the deprecated relevant attribute.
  • 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-data MIME parts as defined in [RFC 2388], with the name parameter being the element local name.
  • Element nodes of any datatype populated by upload also have a Content-Disposition filename parameter, if the filename is available.
  • Element nodes of any datatype populated by upload are serialized as the specified binary content. In the case of xs:anyURI and derived types, the serialization content is obtained from the URI. For xs:base64Binary, xs:hexBinary, and derived types, the serialization content is obtained by decoding the element string value.
  • Element nodes of any datatype not populated by upload are 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-Type must be text/plain except for xs:anyURI, xs:base64Binary, xs:hexBinary, and derived types, in which case the header represents the mediatype of the attachment if known, otherwise application/octet-stream. If a character set is applicable, the Content-Type may have a charset parameter.
<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--

application/x-www-form-urlencoded

This format consists of simple name-value pairs, without any structuring retained. It 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 binary content.

The steps for serialization are as follows:

  1. Each element node is visited in document order, ignoring or treating as empty non-relevant elements according to the nonrelevant attribute or the deprecated relevant attribute. 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). Attribute information is not preserved.
  2. Element nodes selected for inclusion are encoded as EltName=value, where = is a literal character, EltName represents the element local name, and value represents the string value of the element (the concatenation of all text node children, or empty string if the element has no text node children). Note that contextual path information is not preserved, nor are namespaces and namespace prefixes. As a result, different elements might serialize to the same name.
    The encoding of EltName and value are as follows: space characters are replaced by +, and 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, where HH represents 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).
  3. All such encodings are concatenated, maintaining document order. The value of the separator attribute on submission is used between pairs of encoded name/value pairs, e.g. for the separator ";" EltName1=value1;EltName2=value2;EltName3=value3.

Consider the following instance data:

<PersonName title="Mr">
  <GivenName>René</GivenName>
</PersonName>

This will give as serialization:

GivenName=Ren%C3%A9

Note that little of the data is preserved. When greater data integrity is needed a different serialization should be chosen.

application/json and text/csv

As described in the sections on External JSON values and External CSV values, instances adhering to certain formats may also be serialized in JSON and CSV formats.

Submission Events

The xforms-submit Event

This event initiates a submission.

Target: submission Bubbles: Yes Cancelable: Yes Context Info: None

Default action: Submission processing is started for the submission element.

The xforms-submit-serialize Event (Deprecated)

Dispatched at the beginning of submission serialization (see Submission Processing).

Target: submission Bubbles: Yes Cancelable: No

Context Info:

submission-body (node-sequence)
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 Item 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 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.

 <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.

The xforms-submit-ready Event

This notification event is dispatched as an indication of readiness just before effective submission

Target: submission Bubbles: Yes Cancelable: No

Context Info:

resource-uri (string)
The submission resource URI that has been prepared for submission (xs:anyURI)
method (string)
The protocol method to be used to transmit the submission
request-mediatype (string)
The mediatype of the serialization to be used in the Content-type header of HTTP
request-headers (node-sequence)
Zero or more elements, each one representing a content header in the prepared request for the submission. The returned node-sequence is empty if there will be 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.
request-body (object (string or node))
According to the media-type defined for the submission, a node is returned when possible, if not a string is returned.
<submission resource="https://example.com/data" method="put" replace="none">
    <action ev:event="xforms-submit-ready">
         <message value="event('resource-uri')"/>
         <message value="event('mediatype')"/>
         <message value="serialize(event('request-body'))"/>
    </action>
</submission>

The submission details are inspected before the submission being performed.

<submission resource="https://example.com/data" replace="instance" instance="results">
    <action ev:event="xforms-submit-ready">
         <replace ref="instance('results')" with="instance('substitute')"/>
         <cancel/>
    </action>
</submission>

The submission is simulated replacing the target instance with a substitute.

The xforms-submit-done Event

This notification event is dispatched as an indication of successful completion of a submission process

Target: submission Bubbles: Yes Cancelable: No

Context Info:

resource-uri (string)
The submission resource URI that succeeded (xs: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-sequence)
Zero or more elements, each one representing a content header in the success response received by the submission. The returned node-sequence 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.
<submission resource="https://example.com/data" method="put" replace="none">
    <send ev:event="xforms-submit-done" submission="head"/>
</submission>
<submission id="head" resource="https://example.com/data" method="head"
            serialization="none" replace="none">
    <setvalue ev:event="xforms-submit-done"
              ref="mod-time" 
              value="event('response-headers')[name='last-modified']/value" />
</submission>

The default instance data is submitted; upon successful completion, a second submission is performed to access the time that the server has recorded as the modification time.

The xforms-submit-error Event

This notification event is dispatched on failure of a submission process.

Target: submission Bubbles: Yes Cancelable: Yes

Context Info:

error-type (string)
One of the following: submission-in-progress, no-data, no-relevant-data, validation-error, parse-error, resource-error, result-mediatype, result-text-mediatype, result-error-response, target-model-error, target-empty, target-readonly, target-non-element.
error-message (string)
A message containing further details of the error.
resource-uri (string)
The submission resource URI that failed (xs: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-sequence)
Zero or more elements, each one representing a content header in the error response received by a failed submission. The returned node-sequence 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-sequence))
When the error response specifies an XML mediatype 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 mediatype (starting with text/), then the response body is returned as a string. Otherwise, an empty string is returned.

Default action: A warning message must be displayed containing at least all the context info values listed above. For example:

<message ev:event="xforms-submit-error">
   Submission error.
      error-type: <output value="event('error-type')"/>
      error-message: <output value="event('error-message')"/>
      resource-uri: <output value="event('resource-uri')"/>
      response-status-code: <output value="event('response-status-code')"/>
      response-reason-phrase: <output value="event('response-reason-phrase')"/>
  </message>
<submission resource="https://example.com/getRecord" method="post"
            replace="instance" instance="record">
  <message ev:event="xforms-submit-error" ev:default="cancel">A submission error 
                   (<output value="event('error-type')"/>) occurred.</message>
</submission>

Processing

XForms processing is based on responding to events that signal change of state: in general whenever there is a change of state, events are dispatched to parts of the document affected by the change. Event handlers are then able to respond as needed.

After this initialization the system goes into stasis, until either the user interacts with the document, thus setting off a new chain of events, or an action handler reacting to xforms-ready initiates a chain of events.

Events are classified in the following categories:

  • Initialization
  • Interaction
  • Notification
  • Error Conditions.

Event Sequencing

An event happening usually sets of a chain of other events responding to the changes. Here, we give the sequences of related events that occur in several common situations; events that may be fired more than once are prefixed with [n].

For Initialization

These may cause a number of xforms-link-error and xforms-compute-error.
These may cause a number of xforms-binding-error.

For input, secret, textarea, range, or upload Controls

  • When the control is interactively changed, and has the incremental="true" setting, the event sequence described at Sequence: Value Change may be initiated at implementation dependent intervals.
  • When the control is interactively changed and does not have the incremental="true" setting, no events are required to be dispatched, and thus no order is defined.
  • When the user activates the control and the value has changed, then, after the new value is placed into the bound instance node, the event sequence consists of the events described at Sequence: Value Change followed by dispatching the DOMActivate event. See The input Element for an example.
  • When focus changes from the control and the value has changed, then, after the new value is placed into the bound instance node, the event sequence is as described at Sequence: Value Change.

For output Controls, and elements that use output

  • The implementation of an output (and any element that uses it, namely label, help, hint, and alert) dispatches xforms-output-error if it is unable to process the output data (such as corrupt image data when the output mediatype indicates it is image data). This event may occur each time the output is given new data (such as a change of data in the bound data node or a change of the bound data node).

For select or select1 Controls

  • When a selection is interactively changed, and the control has the incremental="true" setting (which is the default for the select or select1 elements), the event sequence is described at Sequence: Selection Without Value Change, which may be followed immediately by the sequence described at Sequence: Value Change.
  • When a selection is interactively changed, and the select or select1 control has the incremental="false" setting, the event sequence is described at Sequence: Selection Without Value Change.
  • When the user activates the control and the selection has changed, then, after the new value is placed into the bound instance node, the event sequence consists of the events described at Sequence: Value Change followed by dispatching the DOMActivate event. Note that this event sequence will have been preceded by the event sequence described at Sequence: Selection Without Value Change at the moment the selection was changed.
  • When focus changes from the control and the selection has changed, then, after the new value is placed into the bound instance node, the event sequence is as described at Sequence: Value Change. Note that this event sequence will have been preceded by the event sequence described at Sequence: Selection Without Value Change at the moment the selection was changed.

For trigger Controls

For submit Controls

Sequence: Selection Without Value Change

  1. xforms-deselect (for each item deselected by the change, if any)
  2. xforms-select (for each item selected by the change, if any)

Sequence: Value Change

After an update, a refresh performs re-evaluation of UI binding expressions and dispatches these events accordingly (the order in which they are dispatched is not defined):

  • [n] xforms-value-changed
  • [n] xforms-valid or xforms-invalid
  • [n] xforms-enabled or xforms-disabled
  • [n] xforms-optional or xforms-required
  • [n] xforms-readonly or xforms-readwrite
  • [n] xforms-out-of-range or xforms-in-range.

Sequence: Activating a Trigger

  1. DOMActivate

Sequence: Submission

  1. xforms-submit
  2. xforms-submit-serialize
  3. xforms-submit-done or xforms-submit-error

Resolving ID References

The element of a document for which an IDREF must be resolved is called the source element, and the element bearing the matching ID, if there is one, is called the target element. Due to the run-time expansion of repeated content in XForms, it is possible that there will be more than one occurrence of both the source and target elements. This section describes how XForms IDREF resolution works to accommodate such repetition of the originating document's content.

Each run-time occurrence of the source element is called a source object, and each run-time occurrence of the target element is called a target object. It is the source object that performs the IDREF resolution, and the result of the search is either null or a target object.

Whether or not repeated content is involved, a null search result for an IDREF resolution is handled differently depending on the source object. If there is a null search result for the target object and the source object is an XForms action such as dispatch, send, setfocus, setindex or toggle, then the action is terminated with no effect. Similarly, a submit control does not dispatch xforms-submit if its submission attribute does not indicate an existing submission element. Likewise, when a function associated with the source object performs the IDREF search and a null result is obtained, the function returns an empty result such as NaN for the index() function or the empty sequence for the instance() function. However, an xforms-binding-error occurs if there is a null search result for the target object indicated by attributes bind, model and instance.

If the target element is not repeated, then the search for the target object is trivial since there is only one associated with the target element that bears the matching ID. This is true regardless of whether or not the source object is repeated. However, if the target element is repeated, then additional information must be used to help select a target object from among those associated with the identified target element.

References to Elements within a repeat Element

When the target element that is identified by the IDREF of a source object has one or more repeat elements as ancestors, then the set of ancestor repeats are partitioned into two subsets, those in common with the source element and those that are not in common. Any ancestor repeat elements of the target element not in common with the source element are descendants of the repeat elements that the source and target element have in common, if any.

For the repeat elements that are in common, the desired target object exists in the same set of run-time objects that contains the source object. Then, for each ancestor repeat of the target element that is not in common with the source element, the current index of the repeat determines the set of run-time objects that contains the desired target object.

References to Elements within a bind Element

When a source object expresses a binding with a bind attribute, the IDREF of the bind attribute is resolved to a target bind object whose associated sequence is used by the source binding. However, if the target bind element has one or more bind element ancestors, then the identified bind may be a target element that is associated with more than one target bind object.

If a target bind element is outermost, or if all of its ancestor bind elements have ref attributes that select only one node, then the target bind only has one associated bind object, so this is the desired target bind object whose sequence is used in the source binding. Otherwise, the in-scope evaluation context item of the source object containing the bind attribute is used to help select the appropriate target bind object from among those associated with the target bind element.

From among the bind objects associated with the target bind element, if there exists a bind object created with the same in-scope evaluation context item as the source object, then that bind object is the desired target bind object. Otherwise, the IDREF resolution produces all the bind objects identified. For sources that require only one object, and therefore one item, the first-item rule applies.

DOM Interface for Access to Instance Data

Processors that implement the DOM must provide DOM access to instance data via this interface.

Note:

Instance data always has a single root element, and thus corresponds to a DOM Document.

The IDL for the interface is:

#include "dom.idl"
 
 pragma prefix "w3c.org"
 
 module xforms {
   interface XFormsModelElement : dom::Element {
       dom::Document getInstanceDocument(in dom::DOMString instanceID)
          raises(dom::DOMException);
       void rebuild();
       void recalculate();
       void revalidate();
       void refresh();
    };
 };

The getInstanceDocument() Method

If the instance-id parameter is the empty string, then the document element of the default instance is returned. Otherwise, this method returns a DOM Document that corresponds to the instance data associated with the instance element containing an ID matching the instance-id parameter. If there is no matching instance data, a DOMException is thrown.

The implementation of the DOM interface for the instance document must not permit direct mutations of readonly instance nodes. Specifically, the implementation must not allow insertion into a readonly node, direct deletion of a child of a readonly node, nor setting the content of a readonly node. A node that is not readonly can be deleted, including all descendants, even if it has readonly descendants.

The rebuild() Method

This method rebuilds any internal data structures used to track computational dependencies within this Model. This method takes no parameters and raises no exceptions.

The recalculate() Method

This method performs a full recalculation of this Model. This method takes no parameters and raises no exceptions.

The revalidate() Method

This method performs a full revalidation of this Model. This method takes no parameters and raises no exceptions.

The refresh() Method

This method performs a refresh of the user interface based on instance nodes within this Model. This method takes no parameters and raises no exceptions.

The update() Method

This method performs an update of this Model, doing as necessary a rebuild, recalculate, revalidate, and refresh. This method takes no parameters and raises no exceptions.

Feature string for the hasFeature method call

For this version of the XForms specification, the feature string for the [DOM2 Core] DOMImplementation interface hasFeature method call is "org.w3c.xforms.dom" and the version string is "1.0".

Events

XForms uses the events system defined in [DOM2 Events][XML Events], with an event capture phase, arrival of the event at its target element, the event bubbling phase, and finally the performance of the event's default action. A handler can stop the event at any stage, and cancel the default action if needed, and perform other actions if needed. An event can carry context information with it, giving further details of the event. A notification event has no default action, and so cannot be cancelled.

Some events have a related action that dispatches the event. These are listed with the events.

Event name Cancelable? Bubbles? Effect Context Target element Related action

Initialization Events

xforms-model-construct Not Bubbles Effect None model
xforms-model-construct-done Not Bubbles Effect None model
xforms-ready - Bubbles Notification None model
xforms-model-destruct - Bubbles Notification None model

Interaction Events

xforms-rebuild(deprecated) Cancelable Bubbles Effect None model rebuild
xforms-recalculate(deprecated) Cancelable Bubbles Effect None model recalculate
xforms-revalidate(deprecated) Cancelable Bubbles Effect None model revalidate
xforms-refresh(deprecated) Cancelable Bubbles Effect None model refresh
xforms-reset(deprecated) Cancelable Bubbles Effect None model reset
xforms-focus Cancelable Doesn't Effect None Controls setfocus
xforms-previous Cancelable Doesn't Effect None Core Controls previousfocus
xforms-next Cancelable Doesn't Effect None Core Controls nextfocus
xforms-help Cancelable Bubbles Effect None Core Controls
xforms-hint Cancelable Bubbles Effect None Core Controls
DOMActivate Cancelable Bubbles Effect None Core Controls
xforms-submit Cancelable Bubbles Effect None submission send
xforms-submit-serialize(deprecated) Not Bubbles Effect Context submission
xforms-dialog-show Cancelable Bubbles Effect None dialog show
xforms-dialog-hide Cancelable Bubbles Effect None dialog hide

Notification Events

xforms-insert - Bubbles Notification Context instance
xforms-delete - Bubbles Notification Context instance
xforms-value-changed - Bubbles Notification None Core Controls
xforms-valid - Bubbles Notification None Core Controls|group|switch
xforms-invalid - Bubbles Notification None Core Controls|group|switch
xforms-readonly - Bubbles Notification None Core Controls|group|switch
xforms-readwrite - Bubbles Notification None Core Controls|group|switch
xforms-required - Bubbles Notification None Core Controls|group|switch
xforms-optional - Bubbles Notification None Core Controls|group|switch
xforms-enabled - Bubbles Notification None Core Controls|group|switch
xforms-disabled - Bubbles Notification None Core Controls|group|switch
DOMFocusIn - Bubbles Notification None Controls
DOMFocusOut - Bubbles Notification None Controls
xforms-select - Bubbles Notification None item or case
xforms-deselect - Bubbles Notification None item or case
xforms-in-range - Bubbles Notification None Core Controls
xforms-out-of-range - Bubbles Notification None Core Controls
xforms-scroll-first - Bubbles Notification None repeat
xforms-scroll-last - Bubbles Notification None repeat
xforms-submit-done - Bubbles Notification Context submission
xforms-dialog-shown - Bubbles Notification None dialog
xforms-dialog-hidden - Bubbles Notification None dialog

Error Handling

xforms-binding-error Cancelable Bubbles Fatal Context any element that can contain a binding expression
xforms-expression-error Cancelable Bubbles Fatal Context any element that is not an action element and that can contain an expression which is not a binding expression
xforms-action-error Cancelable Bubbles Fatal Context any element that is an event observer for an action handler
xforms-action-warning Cancelable Bubbles Warning Context any element that is an event observer for an action handler
xforms-compute-error Cancelable Bubbles Fatal Context model
xforms-version-error Cancelable Bubbles Fatal Context The default model
xforms-link-error Cancelable Bubbles Fatal Context model
xforms-output-error Cancelable Bubbles Warning Context output|label|help|hint|alert
xforms-submit-error Cancelable Bubbles Warning Context submission

Initialization Events

Initialization is started by dispatching the event xforms-model-construct to each Model in the containing document. How the Processor itself initializes is implementation dependent.

The xforms-model-construct Event

Dispatched to each model to initiate processing.

Target: model Bubbles: Yes Cancelable: No Context Info: None

Default action: a model initialization is done for the model.

The xforms-model-construct-done Event

Dispatched to each model after the completion of xforms-model-construct processing.

Target: model Bubbles: Yes Cancelable: No Context Info: None

Default action: If not already done, a User Interface Initialization is done, and a copy of each instance in the model is retained for use by the reset action.

The xforms-ready Event

This notification event is dispatched once for each model, when initialization is completed and user interaction can start.

Target: model Bubbles: Yes Cancelable: No Context Info: None

The xforms-model-destruct Event

This notification event is dispatched once for each model, before shutdown of the Processor, which can occur from user action, from the load action, or as a result of form submission.

Target: model Bubbles: No Cancelable: No Context Info: None

Interaction Events

The DOMActivate Event

This event is dispatched when the "default action request" for a core control is activated, for instance by pressing a button or hitting enter.

Target: Core Controls Bubbles: Yes Cancelable: Yes Context Info: None

Default action: varies according to the control it is used on.

The xforms-focus Event

Dispatched to set focus to a control.

Target: Controls Bubbles: No Cancelable: Yes Context Info: None

Default action: The target control is given focus, if it is able to accept it.

See the section on interaction for all controls for details.

This event is implicitly invoked when the user changes the focus and to implement accessibility features such as accesskey.

The xforms-next and xforms-previous Events

Dispatched to navigate to the next or previous Core Control in navigation order.

Target: Core Controls Bubbles: No Cancelable: Yes Context Info: None

Default action: focus is given to the next/previous control in navigation order.

See the section on interaction for all controls for details.

<dispatch ev:event="xforms-value-changed"
          name="xforms-next"
          targetid="here"
          if="string-length(.)=4"/>

The xforms-help and xforms-hint Events

Dispatched to provide help or hint information.

Target: Core Control Bubbles: Yes Cancelable: Yes Context Info: None

Default action: If the control has help/hint information attached, it is used to construct a message that is made available to the user.

In the absence of such information, default help or hint messages may be made available.

The xforms-submit Event

See chapter The xforms-submit Event.

The xforms-submit-serialize Event (Deprecated)

See chapter The xforms-submit-serialize Event.

The xforms-dialog-show Event

See chapter The xforms-dialog-show Event.

The xforms-dialog-hide Event

See chapter The xforms-dialog-hide Event.

The xforms-rebuild Event (Deprecated)

Dispatched to recompute the computational dependencies within a Model. Deprecated in favor of the related action.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

Default action: a rebuild is done for the model.

The xforms-recalculate Event (Deprecated)

Dispatched to recalculate all calculations associated with a Model. Deprecated in favor of the related action.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

Default action: a recalculate is done for the model.

The xforms-revalidate Event (Deprecated)

Dispatched to revalidate a Model. Deprecated in favor of the related action.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

Default action: a revalidate is done for the model.

The xforms-refresh Event (Deprecated)

Dispatched to update all controls associated with a Model. Deprecated in favor of the related action.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

Default action: a refresh is done for the model.

The xforms-reset Event (Deprecated)

Dispatched to reset a model back to its original values. Deprecated in favor of the related action.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

Default action: a reset is done for the model.

Notification Events

Notifications events have no default action, and are therefore not cancelable.

The xforms-insert Event

This notification event is dispatched after successful insertion of one or more nodes by an insert action.

Target: instance Bubbles: Yes Cancelable: No

Context Info:

inserted-nodes (node-sequence)
The instance data node or nodes inserted.
updated-nodes (node-sequence)
The instance data text nodes which have been updated by merging text nodes, if any.
origin-nodes (node-sequence)
The instance data nodes referenced by the insert action's origin attribute if present, or the empty sequence if not present.
insert-location-node (node-sequence)
The insert location node as defined by the insert action.
position (string)
The insert position, before or after.

The xforms-delete Event

This notification event is dispatched after successful deletion of one or more nodes by a delete action.

Target: instance Bubbles: Yes Cancelable: No

Context Info:

deleted-nodes (node-sequence)
The instance data node or nodes deleted. Note that these nodes are no longer referenced by their parents.
updated-nodes (node-sequence)
The instance data text nodes which have been updated by merging text nodes, if any.
delete-location (number)
The delete location as defined by the delete action, or NaN if there is no delete location.

The xforms-replace Event

13.3.x The xforms-replace Event

This notification event is dispatched after successful execution of a replace action.

Target: instance Bubbles: Yes Cancelable: No

Context Info:

inserted-nodes (node-sequence)
The new instance data node or nodes.
updated-nodes (node-sequence)
The instance data text nodes which have been updated by merging text nodes, if any.
deleted-nodes (node-sequence)
The instance data node or nodes replaced. Note that these nodes are no longer referenced by their parents.

The xforms-value-changed Event

This notification event is dispatched during a refresh after a change to an instance data node bound to a core control.

Target: Core Controls Bubbles: Yes Cancelable: No Context Info: None

Note:

For controls with incremental=true, it is not defined how often this event is fired. Implementations should optimize processing (for instance not flashing the entire screen for each character entered, etc.).

The xforms-valid and xforms-invalid Events

These notification events are dispatched during refresh when a bound instance data node changes and is valid/invalid, or it becomes valid/invalid.

Target: Core Controls|group|switch Bubbles: Yes Cancelable: No Context Info: None

The xforms-readonly and xforms-readwrite Events

These notification events are dispatched during refresh when a bound instance data node changes and is readonly/read-write or it becomes readonly/read-write.

Target: Core Controls|group|switch Bubbles: Yes Cancelable: No Context Info: None

The xforms-required and xforms-optional Events

These notification events are dispatched during refresh when a bound instance data node changes and is required/optional or it becomes required/optional.

Target: Core Controls|group|switch Bubbles: Yes Cancelable: No Context Info: None

The xforms-enabled and xforms-disabled Events

These notification events are dispatched during refresh when a bound instance data node changes and is enabled/disabled or it becomes enabled/disabled.

Target: Core Controls|group|switch Bubbles: Yes Cancelable: No Context Info: None

The xforms-refresh-done Event

This notification event is dispatched when a refresh has completed.

Target: Default model Bubbles: Yes Cancelable: No Context Info: None

The DOMFocusIn and DOMFocusOut Events

These notification events are dispatched when a control receives/loses focus.

Target: Controls Bubbles: Yes Cancelable: No Context Info: None

The xforms-select and xforms-deselect Events

These notification events are dispatched when an item in a select, select1, or a case in a switch becomes selected or deselected.

Target: item or case Bubbles: Yes Cancelable: No Context Info: None

The xforms-in-range and xforms-out-of-range Events

These notification events are dispatched during a refresh when a value has changed and can now be represented by the control/not represented by the control.

Target: Core Controls Bubbles: Yes Cancelable: No Context Info: None

The xforms-scroll-first and xforms-scroll-last Events

These notification events are dispatched when attempting to set a repeat index outside the range of a repeat.

Target: repeat Bubbles: Yes Cancelable: No Context Info: None

The xforms-submit-done Event

See chapter The xforms-submit-done Event.

The xforms-dialog-shown Event

See chapter The xforms-dialog-shown Event.

The xforms-dialog-hidden Event

See chapter The xforms-dialog-hidden Event.

Error Handling

When errors happen during processing, error events are dispatched, usually to the offending element, allowing the events to be caught and responded to if necessary. XForms 2.0 enhances error handling with the ability to recover from errors, optionally continuing processing after catching an error.

The default action of most error events is to halt processing, but handlers can use defaultAction="cancel" to implement custom error handling and allow processing to continue.

For three events, xforms-action-warning, xforms-output-error, and xforms-submit-error, the default action is to issue a warning, and then allow processing to continue. Cancelling the default in these cases means continuing processing without the warning.

<action ev:event="xforms-expression-error" ev:defaultAction="cancel">
  <!-- Custom error handling here -->
</action>

Error Recovery Outside Actions

On encountering an error with an expression or binding, a recovery value is determined for the expression before dispatching an event. Specifically:

  1. For control bindings, model bindings, values, variables:
    • Upon expression errors, a default value is chosen:
      • the empty sequence for bindings and variable values
      • the empty string for string values
      • xforms-expression-error is dispatched
    • Upon binding errors with the bind attribute
      • the binding resolves to the empty sequence
      • xforms-binding-error is dispatched
    • Upon binding errors with the model attribute
      • the model doesn't change, as if the model attribute was missing
      • the binding resolves to the empty sequence
      • xforms-binding-error is dispatched
  2. For expression MIP values:
    • Upon expression errors for calculate
      • the destination value is set to blank
      • xforms-expression-error is dispatched
    • Upon expression errors for other MIPs
      • the MIP is not modified, as if the attribute specifying the property was missing
      • xforms-expression-error is dispatched
    • Upon binding errors with complex or readonly content (calculate only)
      • the instance value is not modified
      • xforms-binding-error is dispatched to the model
  3. For the submission instance attribute:
    • Upon incorrect instance id
      • xforms-submit-error is dispatched, for compatibility with the case of a target error with the targetref attribute

Error Recovery Inside Actions

Any error taking place during action processing stops the outermost action handler. Errors include:

  • expression errors
  • binding errors with the bind or model attribute
  • binding errors with complex or readonly content
  • missing mandatory attributes or unsupported attribute values on action elements

The xforms-action-error and xforms-action-warning events are dispatched to the observer of the action. Observers include: controls and the model, instance, and submission elements.

Note:

Some actions silently ignore error conditions and are not subject to the processing above, including:

  • setvalue pointing to the empty sequence or to an atomic item (such as a string) instead of a node
  • delete with the empty sequence or an empty overridden context
  • insert with an empty or non-element insert context, an empty overridden context, or an empty origin
  • actions with AVTs evaluating to the empty sequence.

The xforms-binding-error Event

Dispatched as an indication of any error with a binding not within an action handler.

Target: the element that contains the binding expression that is in error Bubbles: Yes Cancelable: Yes

Context Info:

error-message (string)
Implementation-optional, implementation-dependent error message, or the empty sequence.

Default action: Fatal error (halts processing).

Examples include:

  • a bind attribute IDREF value that refers to an ID not on a bind element
  • a model attribute IDREF value that refers to an ID not on a model element
  • a model attribute which does not refer to the containing model element, when applicable
  • a static or dynamic error with a binding expression expressed with the ref attribute.

Note:

Binding errors occurring within action handlers dispatch the xforms-action-error event instead.

The xforms-expression-error Event

Dispatched as an indication of any error occurring during evaluation of an expression not within an action handler, excluding binding expressions.

Target: any element that is not an action element and that can contain an expression which is not a binding expression Bubbles: Yes Cancelable: Yes

Context Info:

error-message (string)
Implementation-optional, implementation-dependent error message, or the empty sequence.

Default action: Fatal error (halts processing).

Examples include:

  • a bind computed expression
  • a value attribute on output and var

Note:

Expression errors occurring within action handlers dispatch the xforms-action-error event instead.

The xforms-action-error Event

Dispatched as an indication of any error occurring during the execution of an action handler, including expression and binding errors.

Target: the event observer that caused the action to be executed Bubbles: Yes Cancelable: Yes

Context Info:

error-type (string)
One of: expression-error, binding-error, script-error, script-language, setvalue-children, setvalue-root, setindex-repeat, toggle-case, setfocus-control, dispatch-targetid, reset-instance, retain-instance, send-submission.
error-message (string)
Implementation-optional, implementation-dependent error message, or the empty sequence.

Default action: Fatal error (halts processing).

The xforms-action-warning Event

A non-fatal version of xforms-action-error, dispatched as an indication of any warning occurring during the execution of an action handler.

Target: the event observer that caused the action to be executed Bubbles: Yes Cancelable: Yes

Context Info:

error-type (string)
Currently only: load-error.
error-message (string)
Implementation-optional, implementation-dependent error message, or the empty sequence.

Default action: Warning.

The xforms-compute-error Event

Dispatched as an indication of an error occurring with computing expressions.

Target: model Bubbles: Yes Cancelable: Yes

Context Info:

error-message (string)
An implementation-specific string that should contain the expression being processed when the error was detected.

Default action: Fatal error (halts processing).

Examples include:

  • an extension function is declared on the functions attribute but is not implemented by the XForms Processor;
  • a circular dependency is detected during recalculate;
  • a computed expression violates a Binding Expression Constraint during recalculate.

The xforms-version-error Event

Dispatched as an indication of failure of the version checks defined in the description of the version attribute in Section The model Element.

Target: the default model Bubbles: Yes Cancelable: Yes

Context Info:

error-message (string)
An implementation-specific error string

Default action: Fatal error (halts processing).

Note:

This event can be dispatched early during XForms Processor initialization. While the default action of this event can be canceled by an event handler, XForms Processors are not expected to produce XForms user interface elements or execute further XForms action handlers (such as a message action) in response to this event. This event is mainly dispatched for the benefit of implementation-specific processing code that may be monitoring the behavior of an XForms Processor.

The xforms-link-error Event

Dispatched as an indication of a failure to traverse or process the result of a link, such as schema or instance initialization.

Target: model associated with the element performing the link. If the element has a model attribute, that model is used. Otherwise, the model attribute of the closest ancestor element is used. Otherwise, the first model is used. Bubbles: Yes Cancelable: Yes

Context Info:

resource-uri (string)
The URI associated with the failed link (xs:anyURI)

Default action: Fatal error (halts processing).

Note:

When this event is not canceled, XForms Processors are not expected to produce XForms user interface elements nor even execute XForms action handlers (such as a message action) in response to this event.

The xforms-output-error Event

Dispatched on failure of an output, label, help, hint, or alert element to render content.

Target: The output, label, help, hint, or alert that caused the error. Bubbles: Yes Cancelable: Yes Context Info: None.

Default action: Warning.

Note:

The output element content can include XForms actions, so an output element can contain an event handler for the xforms-output-error event. See Section The output Element.

The xforms-submit-error Event

See chapter The xforms-submit-error Event.

Actions

Actions allow change of state not based directly on user interaction. By listening for events on different elements, actions can be used to react to those events.

Actions are declarative XML event handlers [XML Events] that capture high-level semantics, and as a consequence, are more tractable than methods that rely exclusively on scripting, and thus enhance the accessibility of applications.

The elements and attributes included in this module are:

Element Attributes and Their Content (after AVT evaluation) Minimal Content Model

action

Action Common, type (xs:string), src (xs:anyURI), charset (xs:string)

(Action|var)* | param*, body

setvalue

Action Common, Single Item Binding, value (string Expression)

PCDATA

insert

Action Common, Sequence Binding, at (number Expression), position ("before"|"after"), origin (node-sequence Expression)

EMPTY

delete

Action Common, Sequence Binding, at (number Expression)

EMPTY

setindex

Action Common, repeat (xs:IDREF), index (number Expression)

EMPTY

toggle

Action Common, case (xs:IDREF)

case? [deprecated]

setfocus

Action Common, control (xs:IDREF)

control? [deprecated]

dispatch

Action Common, name (xs:NMTOKEN), targetid (xs:IDREF), delay (xs:nonNegativeInteger), bubbles (xs:boolean), cancelable (xs:boolean)

name? [deprecated], targetid? [deprecated], delay? [deprecated], property* [in any order]

signal

Action Common, name (xs:NMTOKEN), control (xs:IDREF), delay (xs:nonNegativeInteger), bubbles (xs:boolean), cancelable (xs:boolean)

property*

rebuild

Action Common

EMPTY

recalculate

Action Common

EMPTY

revalidate

Action Common

EMPTY

update

Action Common

EMPTY

refresh

Action Common

EMPTY

reset

Action Common

EMPTY

retain

Action Common

EMPTY

load

Action Common, Single Item Binding (optional; deprecated), resource (xs:anyURI), show ("new" | "replace")

resource? [deprecated]

send

Action Common, submission (xs:IDREF)

EMPTY

return

Action Common, nonrelevant ("keep"|"remove"|"empty")

EMPTY

renew

Action Common, control (xs:IDREF)

EMPTY

message

Action Common, Single Item Binding (optional), level ("ephemeral" | "modeless" | "modal"|PrefixedName)

(PCDATA|UI Inline)*

Support elements are:

Element Attributes and Their Content (after AVT evaluation) Minimal Content Model

param

Common, value, name (xs:string)

PCDATA

body

Common, Events

PCDATA

case (deprecated)

Common, value

PCDATA

control (deprecated)

Common, value

PCDATA

name (deprecated)

Common, value

PCDATA

targetid (deprecated)

Common, value

PCDATA

delay (deprecated)

Common, value

PCDATA

property

Common, value, name (xs:string)

PCDATA

resource (deprecated)

Common, value

PCDATA

This module also defines the content set "Action", which includes all the above elements:

(action|setvalue|insert|delete|setindex|toggle|setfocus|dispatch|
 rebuild|recalculate|revalidate|update|refresh|reset|retain|
 load|send|message)*
<trigger label="Reset" label="Reset">
  <reset ev:event="DOMActivate" model="thismodel"/>
</trigger>

This example defines a trigger that resets all instance values in a model back to their original values. The action is the element reset which is activated when the DOMActivate event occurs on the trigger element.

Common Attributes for Actions

The following attributes are available to all Action elements.

Action Common

Element Attributes and Their Content (after AVT evaluation)

Action

Common, Evaluation, Events, if (boolean Expression), while (boolean Expression), iterate (node-sequence Expression)

An action is normally performed once when encountered. However, execution may be conditional or iterated with the use of these attributes.

if
Optional expression defined below in Section The if Attribute.
while
Optional expression defined below in Section The While Attribute.
iterate
Optional expression defined below in Section The Iterate Attribute.

XML Events

Element Attributes and Their Content (after AVT evaluation)

Action

event(NMTOKEN), observer (IDREF), target (IDREF), handler (URI), phase ("capture" | "default"*), propagate ("stop" | "continue"*), defaultAction ("cancel" | "perform"*)

All of the "global" attributes defined in the [XML Events] specification are usable when prefixed with the XML Events namespace. Processing is defined in section 2.3 of [XML Events].

Processing Common to All Actions

If an action has a model attribute which does not identify a model element, then an xforms-action-error with an error-type of binding-error is dispatched.

If an error occurs during the evaluation of a binding expression on an action, then an xforms-action-error with an error-type of binding-error is dispatched.

If an error occurs during the evaluation of a non-binding expression on an action, then an xforms-action-error with an error-type of expression-error is dispatched.

If any value of type IDREF, except for model, on an action is required to identify a certain type of element, and doesn't, then an xforms-action-error with an error-type of element-attribute is dispatched, where element is the name of the action, and attribute is the name of the attribute at fault.

Conditional and Iterated Execution of Actions

Any action can be guarded by an expression that determines if, or how often, the action is performed.

The if attribute

An if attribute contains an expression that is evaluated in the element evaluation context before the action is executed; the result is converted to boolean. The action is performed only if the result is true.

If this attribute is applied to an action element and it evaluates to false, then none of the contained actions are performed.

Note:

In insert and delete actions, the context attribute is evaluated before the if attribute.

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">
  <setfocus
    ev:event="xforms-value-changed"
    control="ExchangeControl"
    if="string-length(.)=3 and . > 0"/>
</input>
<input ref="exchange" id="ExchangeControl" incremental="true" label="Exchange">
  <setfocus
    ev:event="xforms-value-changed"
    control="LocalControl"
    if="string-length(.)=3 and . > 0"/>
</input>
<input ref="local" id="LocalControl" incremental="true" label="Local">
  <setfocus
    ev:event="xforms-value-changed"
    control="ExtensionControl"
    if="string-length(.)=4 and . > 0"/>
</input>

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">
  <action ev:event="DOMActivate">
    <insert
      context="purchaseOrder/lines"
      ref="line"
      at="index('PurchaseOrderRepeat')"
      origin="instance('prototype')"/>
    <setfocus control="PurchaseOrderRepeat"/>
  </action>
</trigger>
<repeat ref="purchaseOrder/lines/line" id="PurchaseOrderRepeat">
  ...
  <trigger label="Delete Row">
    <action ev:event="DOMActivate">
      <setfocus control="InsertControl" if="last()=1"/>
      <delete ref="../line" at="index('PurchaseOrderRepeat')"/>
    </action>
  </trigger>
  ...
</repeat>

The while attribute

The while attribute contains an expression that is evaluated in the element evaluation context before the action is executed; the result is converted to boolean. If the value is true, then the XForms action is performed and then the expression is re-evaluated. The XForms action is executed repeatedly until 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 the expression yields true.

When XForms actions are iteratively executed, they are still subject to the normal action processing rules of updating 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.

Counter and accumulator variables are created in instance data to sum a selection of values chosen by the user

<trigger label="Get Sum">
  <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>

The iterate attribute

The iterate attribute contains an expression that is evaluated once in the element evaluation context before the action is executed, resulting in a sequence of items. The action is then executed once for each item in the sequence, with the item replacing the default in-scope evaluation context.

 <setvalue iterate="*/total" ref="." value="0"/>
Note:

Iterate changes the evaluation context for if and while attributes, and is evaluated before either of the two.

Note:

Since the iterate expression is evaluated once using the element evaluation context, before the action is executed, the action will also be executed for nodes that are deleted by the action or its descendent actions. A deleted node no longer belongs to a document, and you can use this characteristic in the if attribute to skip deleted nodes if you need to.

The action Element

This is a container for other actions.

Common Attributes: Action Common

Special Attributes:

type
Optional MIME type of the language of the script.

Content: (Action|var)* | param*, body

If there is no type attribute, this element is a container for one or more other Actions: when the element is activated, the contained actions are activated one-by-one in order.

If the type attribute is present, and the language it indicates is not supported, then when the action element is activated, an xforms-action-error with an error-type of script-language is dispatched. The error-message context information may contain a more specific error message. The supported languages depend on the implementation, which may not support any extra languages at all.

Otherwise, the script in the inline content is executed. If an error occurs during execution, an xforms-action-error with an error-type of script-error is dispatched. The error-message context information may contain a more specific error message.

<action ev:event="DOMActivate">
  <setvalue ref="ready">yes</setvalue>
  <send/>
</action>
<action type="text/javascript" ev:event="DOMActivate">
  alert('JavaScript alert: ');
</action>

The param Element (for action)

The param element allows passing one or more parameters to a script when the type attribute of the action element is present. If a param element is present, the body element is required.

Common Attributes: Common, Evaluation, value

Special Attributes:

name
Required attribute containing the name of the parameter to pass to the script.

Content: PCDATA

The value of the parameter is obtained from the value attribute, if present, or otherwise from the inline text. The value can be any sequence of items but is converted to a value compatible with the script type as needed.

The body Element (for action)

This element specifies the body of the script when the type attribute of the action element is present and one or more param elements are present.

Common attributes: Common, Evaluation

Content: ANY

<action ev:event="DOMActivate" type="text/javascript">
  <param name="star"   value="instance()/star"/>
  <param name="planet" value="instance()/planet"/>
  <body>
    alert('I was just passed a few parameters: star = "' + star + '" and planet = "' + planet + '".');
  </body>
</action>

The setvalue Element

This action sets the value of an instance data node.

Common Attributes: Action Common, Single Item Binding, value

Content: PCDATA

If the Single Item Binding does not select an instance data node, or the instance data node is readonly, this action has no effect.

The value to be used is obtained by evaluating the value attribute, or otherwise from the element content. If neither is present, the empty string ("") is used.

The resulting string is inserted into the instance data as follows:

  • Element nodes: If element child nodes are present, then an xforms-action-error event with an error-type of setvalue-children is dispatched; otherwise the string becomes the new content of the element.
  • Attribute nodes: The string-value of the attribute is replaced with the new value.
  • Text nodes: If the new value is the empty string the text node is eliminated; otherwise the text node is replaced with the new value.
  • Namespace, processing instruction, and comment nodes: behavior is undefined (implementation-dependent).
  • the root node of an instance: an xforms-action-error Event with an error-type of setvalue-root is dispatched.

Note:

The context() function that returns the in-scope evaluation context item, can be used to provide the same initial evaluation context item to both the ref and value attributes. See Appendix Patterns for Data Mutations for numerous further usage patterns for setvalue, insert and delete.

<setvalue ref="a" value="0"/>
<setvalue ref="a">0</setvalue>
<setvalue ref="name"/>
<setvalue ref="count" value=".+1"/>
<setvalue bind="put-here" value="a/b/c"/>
<setvalue iterate="player/score" ref="." value="0"/>

The insert Element

This action inserts items into a sequence. In brief:

  • ref or bind gives a target sequence;
  • origin gives one or more items to be inserted in the sequence (default: a copy of the last item of the target sequence);
  • at gives an index into the target sequence for the insertions (default: the end of the sequence);
  • position says whether to insert before or after the given position (default: after).

If the target sequence is empty (and origin is present and non-empty) the origin items are inserted into the context node, ignoring at and position.

Common Attributes: Action Common, Sequence Binding (optional)

Special Attributes:

origin
Optional expression giving a sequence of items to be inserted; default: the last item of the target sequence.
at
Optional number expression giving an index into the target sequence where items are to be inserted; default: the end of the sequence.
position
Optional selector that indicates where to put the inserted nodes relative to the insert index. Possible values are before and after; default: after.

Content: EMPTY

The target-sequence is obtained from the element evaluation context.

The origin-sequence is determined:

  • if the origin attribute is given, it is evaluated in the in-scope evaluation context;
  • otherwise, if the target-sequence is non-empty, its last node is used;
  • otherwise, the insert action has no effect.

Root nodes (parents of document elements) are removed from the origin-sequence, and the result used. An implementation may choose not to include namespace nodes in the origin-sequence, in particular if the namespace axis is not supported or if inserting the namespace node would make the data model inconsistent.

If the resulting origin-sequence is empty, the insert action has no effect.

The insert index is determined:

  • if the target-sequence is empty, there is no insert index;
  • if the at attribute is present, it is evaluated as a number in the Element Evaluation Context and rounded to the nearest integer. If it is not a number, is greater than the target-sequence size, or is less than 1, the insert action has no effect;
  • otherwise, the size of the target-sequence is used.

The insert location node is determined:

  • if the target-sequence is empty, the context node from the in-scope evaluation context is used;
  • otherwise the target-sequence at the position given by the insert index is used.

If the insert location node is readonly and the target-sequence is empty, or if the parent of the insert location node is readonly, the insert action has no effect.

In the origin-sequence, each item is treated in order: a node and its entire subtree is copied; a text node is created for each atomic value.

The target location is determined for each copied node:

  • if the target-sequence is non-empty, then the copied node will become the sibling of the insert location node:
    • if the insert location node is an attribute or root node, the target location is undefined;
    • otherwise the target location is immediately before or after the insert location node, depending on the position attribute setting or its default;
  • if the target-sequence is empty, then the copied node will become a child of the insert location node. The target location is determined by the type of the insert location node:
    • the root node of an instance (which is the parent of the root element):
      • if the copied node is an element, then the target location is the root element of the instance;
      • if the copied node is not an element, then the target location is before the first child of the insert location node;
    • an element:
      • if the copied node is an attribute, then the target location is the attribute list of the element;
      • if the copied node is not an attribute, then the target location is before the first child of the insert location node, or the child list of the insert location node if it is empty;
    • otherwise (it cannot be the parent of the copied node, so:) the target location is undefined.

If the target location is undefined, or there is a node type conflict between the copied node and the target location (for example, an attribute cannot be inserted as a sibling of an element), the insertion for that copied node is ignored.

The copied node is inserted:

  • 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 copied node is an element, then the instance root element is deleted before the copied node is inserted at the target location;
  • if the copied 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;
  • otherwise the copied node is inserted into its target location depending on node type.

Each copied node that is inserted is added to an inserted-nodes list that is provided in the xforms-insert event context information. Each copied node used to update an existing attribute node, the existing attribute node is added to the list of inserted-nodes.

If the list of inserted-nodes is empty, the insert action has no effect.

The insert action is successfully completed by dispatching the xforms-insert event with appropriate context information to the instance.

Note: A repeat updates its index in response to this event if its repeat collection changes size as a result of the insertion. See Section Repeat Processing for details.

Processors must at all times keep the data consistent with the constraints imposed by the XPath Data Model. See The Instance Element for details.

<instance>
  <data xmlns="">
    <list><a>1</a><a>2</a><a>3</a></list>
  
</instance>
<trigger label="+">
  <insert ref="list/a" ev:event="DOMActivate"/>
</trigger>

The trigger duplicates the last element of the list (and so if the list is empty, nothing happens).

<instance>
  <data xmlns="">
    <list><a>1</a><a>2</a><a>3</a></list>
    <blank><a>0</a></blank>
  
</instance>
<trigger label="+">
  <insert context="list" ref="a" origin="../blank/a" ev:event="DOMActivate"/>
</trigger>

This trigger inserts the 'blank' element at the end of the list, whether empty or not.

To insert it at the beginning of the list, use:

<insert context="list" ref="a" at="1" position="before" origin="../blank/a" ev:event="DOMActivate"/>
<instance resource="data.xml"/>
<instance id="template">
   
</instance>
...
<action ev:event="xforms-ready">
   <insert context="/data" origin="instance('template')/@total"/>
</action>

On initialization, if the document element /data doesn't have a total attribute, one will be created; if it does, it will be replaced.

<instance>
  <purchaseOrder xmlns="">
    <subtotal/>
    <tax/>
    <total/>
  </purchaseOrder>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    ...
    <item>
      <product/>
      <quantity/>
      <unitcost/>
      <price/>
    </item>
    ...
  </prototypes>
</instance>
<repeat ref="/purchaseOrder/item" id="R">
   ...
</repeat>
<trigger label="Add to purchase order">
  <action ev:event="DOMActivate">
    <insert context="/purchaseOrder" ref="item" at="index('R')" 
            origin="instance('prototypes')/item"/>
    <setfocus control="R"/>
  </action>
</trigger>

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.

<model>
  <instance>
    <data xmlns="">
      <name>
        <first>John</first>
        <last>Doe</last>
      </name>
      <address>
        <street>123 Main St.</street>
        <city>Smallville</city>
      </address>
    
  </instance>

  <bind ref="name" readonly="true()"/>
  <bind ref="address/street" readonly="true()"/>

  <action ev:event="xforms-model-construct-done">
    <insert id="I1" ref="name/*" .../>
    <insert id="I2" ref="address/street" at="1" >
  </action>
</model>

Insert I1 fails because it attempts to insert into the content of a readonly node (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 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 Patterns for Data Mutations for numerous further usage patterns for setvalue, insert and delete.

The delete Element

This action deletes one or more nodes from instance data.

Common Attributes: Action Common, Sequence Binding

Special Attributes:

at
Optional number expression giving the position in the target sequence where an item is to be deleted.

Content: EMPTY

The target-sequence is obtained from the element evaluation context. The delete action has no effect if the target-sequence is empty.
Note:

Not expressing the Sequence Binding is deprecated.

The delete index, if any, is determined:

  • if the at attribute is not given, there is no delete index;
  • otherwise, the at attribute is evaluated in an evaluation context where the context node is the first node of the target-sequence, the context size is the size of the target-sequence, and the context position is 1. It is evaluated as a number and rounded to the nearest integer. If it is not a number, greater than the size of the target-sequence, or less than 1, the delete action has no effect.

If there is no delete index, each item in the target-sequence is treated, otherwise only the item at the delete index in the target-sequence is treated.

Items are treated as follows:

  • an item is ignored if it is a root node, the root document element of an instance, an atomic value, or its parent is a readonly node;
  • otherwise, it is deleted.

If the target-sequence contains nodes from more than one document, the nodes are deleted from their respective document.

If no node is deleted in the preceding steps, the delete action has no effect, otherwise, the delete action is successfully completed by dispatching the xforms-delete event with appropriate context information to the instance.

Note:

An implementation may choose not to delete namespace nodes, in particular if the namespace axis is not supported or if deleting a namespace node would make the data model inconsistent.

Note:

When a node is deleted from an instance it will no longer have a parent.

Note:

When a deleted node provides the evaluation context for an action, it will keep providing that context as long as the action is running.

Note:

Processors must at all times keep the data consistent with the constraints imposed by the XPath Data Model. See The Instance Element for details.

Delete the first element of a list:

<delete ref="list/a" at="1"/>

The last:

<delete ref="list/a" at="last()"/>

Delete all the elements:

<delete ref="list/a"/>

In this example, the trigger is not in the repeat. When it is activated, the indexed item in the repeat is first deleted. 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.

<trigger label="Delete from purchase order">
  <action ev:event="DOMActivate">
    <delete context="/purchaseOrder" ref="item" at="index('R')"/>
    <insert
      context="/purchaseOrder"
      if="not(item)"
      ref="item"
      origin="instance('prototypes')/item"/>
    <setfocus control="R"/>
  </action>
</trigger>

The delete could read <delete ref="/purchaseOrder/item" at="index('R')"/>, but the context attribute is here used for symmetry with the insert.

<model>
  <instance>
    <data xmlns="">
      <name>
        <first>John</first>
        <last>Doe</last>
      </name>
      <address>
        <street>123 Main St.</street>
        <city>Smallville</city>
      </address>
    </data>
  </instance>

  <bind ref="name" readonly="true()"/>
  <bind ref="address/street" readonly="true()"/>

  <action ev:event="xforms-model-construct-done">
    <delete id="D1" ref="name/first"/>
    <delete id="D2" ref="address/street" at="1" >
    <delete id="D3" ref="address" at="1" >
  </action>
</model>

Delete D1 fails because it attempts to delete from the content of a readonly node (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.

The replace Element

This action replaces an instance data node with another, a complement of setvalue.

Common Attributes: Action Common, Single Item Binding

Special Attribute:

with
Required expression giving an item which will replace the Single Item Binding.

Content: EMPTY.

The Single Item Binding is evaluated to give the target node; if it does not select an instance data node, or the instance data node's parent is readonly, the action has no effect.

The with attribute is evaluated in the element evaluation context to give an item; the first-item rule is applied if necessary. If the item is an atomic value, a text node is created from it.

If there is a node type conflict between the source node and the target (for example, trying to replace an attribute with an element), an xforms-action-error event with an error-type of replace-with is dispatched, and the action has no further effect.

The target node is replaced with the source node (including its entire subtree), and the xforms-replace event is dispatched with appropriate context information to the instance containing the target node.

<replace ref="address" with="contact/address[@type='home']"/>

See Appendix Patterns for Data Mutations for numerous further usage patterns for setvalue, insert, delete and replace.

The setindex Element

This action sets the repeat index of a repeat control.

Common Attributes: Action Common

Special Attributes:

repeat
Required reference to the ID of a repeat element.
index
Required expression that evaluates to a 1-based offset into the sequence.

Content: EMPTY

An update is done if necessary.

The element referred to by the repeat attribute is identified. If no such repeat element exists, then an xforms-action-error event with an error-type of setindex-repeat is dispatched.

The index attribute is evaluated as a number; if it is not a number, this action has no effect. Otherwise the index of the identified repeat is set to the value rounded to the nearest integer. See index processing for how this may be responded to by the Processor.

Note:

If the repeat element bearing the matching ID resides within another repeating construct such as repeat, the general method described in Resolving ID References is used to determine the desired run-time repeat object.

<setindex repeat="R" index="1"/>
<setindex repeat="R" index="index('R')+1"/>

The toggle Element

This action selects one possible case from an exclusive list of alternatives in a switch element.

Common Attributes: Action Common

Special Attributes:

case
Optional reference to the ID of a case element child of a switch element.

Content: case?

An update is done if necessary.

A case identifier is obtained from the case child element of the toggle element or otherwise from the case attribute. If no case element is identified by this value, then an xforms-action-error event with an error-type of toggle-case is dispatched.

If the identified case has a name attribute, and its containing switch has a Single Item Binding which identifies a node that is not readonly, then the node is set to the value of the name attribute as if by a setvalue action.

The case is selected.

Note:

If the case element bearing the matching ID resides in a repeating construct such as repeat, the general method described in Resolving ID References is used to determine the desired run-time case object.

<toggle case="home"/>
<toggle case="{state}"/>

The case Element (for toggle) (Deprecated)

The case element (deprecated in favor of using an AVT in the case attribute) provides the identity of a case element to select within a switch.

Common Attributes: Common, Evaluation, value

Content: PCDATA

The case to be selected is identified by evaluating the value attribute, or otherwise from the inline content of the element.

<toggle>
  <case value="concat('case_', ../addressBlockType)"/>
</toggle>
<toggle>
  <case>home</case>
</toggle>

The setfocus Element

This action gives input focus to a control.

Common Attributes: Action Common

Special Attribute:

control
Optional reference to the ID of a control.

Content: control?

The control to which focus should be given is identified by the control attribute if present, and otherwise by the control element. If no such control is identified, then an xforms-action-error event with an error-type of setfocus-control is dispatched.

An update is done if necessary.

An xforms-focus event is then dispatched to the identified control.

Note:

If the control to be identified is in a repeating construct such as repeat, the method described in Resolving ID References is used.

Note:

Changing the focus to a control within a repeat object may cause one or more repeat index values to be changed as described in the Repeat Processing section.

<setfocus ev:event="xforms-ready" control="start"/>
<setfocus control="{next-incomplete}"/>

The control Element (for setfocus) (Deprecated)

This element (deprecated in favor of using an AVT in the control attribute) provides the identity of a control to receive focus.

Common Attributes: Common, Evaluation, value

Content: PCDATA

The control to receive focus is identified by evaluating the value attribute, or otherwise from the inline content of the element.

<setfocus><control>start</control></setfocus>
<setfocus>
  <control value="concat('input_', ../paymentType)"/>
</setfocus>

The previousfocus Element

This action gives input focus to the previous control in navigation order.

Common Attributes: Action Common

Content: EMPTY

An update is done if necessary.

If no control currently has focus, this action has no effect; otherwise the previous control in navigation order is identified, and an xforms-focus event is dispatched to it.

See the section on interaction for all controls for details of navigation order.

Note:

Changing the focus to a control within a repeat object may cause one or more repeat index values to be changed as described in the Repeat Processing section.

<previousfocus/>

The nextfocus Element

This action gives input focus to the next control in navigation order.

Common Attributes: Action Common

Content: EMPTY

An update is done if necessary.

If no control currently has focus, this action has no effect; otherwise the next control in navigation order is identified, and an xforms-focus event is dispatched to it.

See the section on interaction for all controls for details of navigation order.

Note:

Changing the focus to a control within a repeat object may cause one or more repeat index values to be changed as described in the Repeat Processing section.

<repeat ref="entry">
   <input ref="." incremental="true" label="4 chars:">
       <nextfocus ev:event="xforms-value-changed" if="string-length(.)=4"/>
   </input>
</repeat>
<input ref="name" label="Your name"/>

A number of entries of exactly 4 characters have to be entered. After typing 4 characters, the user is automatically taken to the next entry. After all entries have been filled in, however many there are, the user will be taken to the control to input their name.

The dispatch Element

This action dispatches an event to an element.

Common Attributes: Action Common

Special Attributes:

name
Required string giving the name of the event to dispatch.
targetid
Required IDREF identifying a target element.
delay
Optional number giving the minimum number of milliseconds to delay dispatching the event. The default is no delay.
bubbles
Optional boolean indicating if this event bubbles — as defined in [DOM2 Events]. The default value is true for a custom event. For predefined events, this attribute has no effect.
cancelable
Optional boolean indicating if this event is cancelable — as defined in [DOM2 Events]. The default value is true for a custom event. For predefined events, this attribute has no effect.

Content: name? [deprecated], targetid? [deprecated], delay? [deprecated], property* [in any order]

Two kinds of event can be dispatched:

  1. Predefined events (e.g., xforms-focus), in which case the bubbles and cancelable attributes are ignored and the standard semantics as defined in Processing Model apply;
  2. User-defined events.

Events can be dispatched either immediately (while the current handler is still active), which is the default, or after the current handler has finished, by using the delay attribute.

The details of the event to be dispatched are collected:

  • The name of the event is obtained from the name attribute or otherwise from the name child element. If the event name is not specified or an empty string, this action has no effect.
  • The event delay, in milliseconds, is obtained from the delay attribute or otherwise from the delay child element. If the value is not a positive or zero integer, this action has no effect; if the value is not specified or an empty string, there is no delay.
  • If the event name does not identify a pre-defined event, then the values of cancelable and bubbles are obtained from their respective attributes.
  • If the dispatch element has any property child elements, the event context is updated with their values.

The targetid attribute or child element is evaluated to identify an element; if no such element exists, an xforms-action-error event with an error-type of dispatch-target is dispatched to the default model.

If there is no delay specified then the event is dispatched immediately; otherwise (including when the delay is specified as zero), if there is no event with the same name and target element on the delayed event queue, the event is added to the queue. As soon as possible after the specified delay in milliseconds has elapsed, the event is removed from the delayed event queue and 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.

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, such as removal of controls associated by a repeat with an instance data node that is destroyed.

<dispatch name="DOMActivate" targetid="zoomin"/>
<dispatch name="tick" delay="1000" targetid="clock"/>
<dispatch name="{../eventname}" targetid="map" bubbles="false">
   <property name="factor" value="10"/>
</dispatch>

Note:

If the target element is in a repeating construct such as repeat, the method described in Resolving ID References is used to determine it.

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.

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.

The property Element (for dispatch)

Adds context information to an event to be dispatched.

Common Attributes: Common, Evaluation, value

Special Attributes:

name
The name of the context information to pass.

Content: PCDATA

The context information is obtained by evaluating the value attribute, or otherwise from the inline content of the element, and is added to the event's context information for the name. The value can be any sequence of items.

<dispatch name="update-person" target="my-model">
  <property name="person" value="instance('person')"/>
  <property name="min-age" value="21"/>
  <property name="new-first-name">Michelle</property>
</dispatch>

Using the information:

<action ev:event="update-person">
  <insert context="..." origin="event('person')"/>
  <setvalue ref="..." value="event('min-age')"/>
  <setvalue ref="..." value="event('new-first-name')"/>
</action>

The name Element (for dispatch) (Deprecated)

The dispatch element (deprecated in favor of using an AVT in the name attribute) provides the name of an event to be dispatched.

Common Attributes: Common, Evaluation, value

Content: PCDATA

The name of the event to be dispatched is obtained by evaluating the value attribute, or otherwise from the inline content of the element.

<dispatch targetid="clock"><name>tick</name></dispatch>
<dispatch targetid="map"><name value="../eventname"/></dispatch>

The targetid Element (for dispatch) (Deprecated)

The targetid element (deprecated in favor of using an AVT in the targetid attribute) specifies the target of an event to be dispatched.

Common Attributes: Common, Evaluation, value

Content: PCDATA

The ID of the target element is obtained by evaluating the value attribute, or otherwise from the inline content of the element.

<dispatch name="tick"><targetid>clock</targetid></dispatch>
<dispatch name="ping"><targetid value="../target"/></dispatch>

The delay Element (for dispatch) (Deprecated)

The delay element (deprecated in favor of using an AVT in the delay attribute) specifies the delay in milliseconds before the event should be dispatched.

Common Attributes: Common, Evaluation, value

Content: PCDATA

The delay for the event is obtained by evaluating the value attribute, or otherwise from the inline content of the element.

<dispatch name="tick" targetid="clock"><delay>1000</delay></dispatch>
<dispatch name="ping" targetid="pong"><delay value="../timer"/></dispatch>

The signal Element

This action causes an event to be dispatched to an embedded or embedding form.

Common Attributes: Action Common

Special Attributes:

name
String giving the name of the event to be dispatched.
control
Optional IDREF identifying a control element.
delay
Optional number giving the minimum number of milliseconds to delay dispatching the event. The default is no delay.
bubbles
Optional boolean indicating if this event bubbles — as defined in [DOM2 Events]. The default value is true for a custom event. For predefined events, this attribute has no effect.
cancelable
Optional boolean indicating if this event is cancelable — as defined in [DOM2 Events]. The default value is true for a custom event. For predefined events, this attribute has no effect.

Content: property*

Processing imitates that of the dispatch action.

If the element has a control attribute:

  • if the attribute's IDREF does not identify a control element, an xforms-action-error event with an error-type of signal-control is dispatched to the default model;
  • otherwise, if the form embedded by the identified control has no shared element, this action has no further effect;
  • otherwise, the specified event is dispatched to the shared element of the form embedded by the identified control element.

If the element has no control attribute:

  • if this form is not embedded, this element has no further effect;
  • otherwise, the specified event is dispatched to the control element that caused this form to be embedded.
<signal name="ready"/>
<signal if="count = 0" name="finished"/>
<signal control="game" name="restart"/>

The cancel Element

This action cancels the default action of the event currently being handled.

Common Attributes: Action Common

Content: EMPTY.

If the current event is cancelable, its default action is cancelled; otherwise the cancel action has no effect.

    <action ev:event="xforms-submit">
        <cancel if="state = 'dryrun'"/>
    </action>

The rebuild Element

Causes a rebuild on a model.

Common Attributes: Action Common

Content: EMPTY

A rebuild is done on:

  • the model identified by the model attribute, if present;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.
Note that since implementations may combine rebuild, recalculate, revalidate, and refresh into fewer steps, this action may result in more than just a rebuild.

The recalculate Element

This action causes a recalculate on a model.

Common Attributes: Action Common

Content: EMPTY

A recalculate is done on:

  • the model identified by the model attribute, if present;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.
Note that since implementations may combine rebuild, recalculate, revalidate, and refresh into fewer steps, this action may result in more than just a recalculate.

The revalidate Element

This action causes a revalidate on a model.

Common Attributes: Action Common

Content: EMPTY

A revalidate is done on:

  • the model identified by the model attribute, if present;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.
Note that since implementations may combine rebuild, recalculate, revalidate, and refresh into fewer steps, this action may result in more than just a revalidate.

The update Element

This action causes an update on a model.

Common Attributes: Action Common

Content: EMPTY

An update is done on:

  • the model identified by the model attribute, if present;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.

The refresh Element

This action causes a refresh on a model.

Common Attributes: Action Common

Content: EMPTY

A refresh is done on:

  • the model identified by the model attribute, if present;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.

Note that since a refresh causes the dispatch of notification events, if it is required for everything to be up-to-date in the middle of an action, then refresh allows you to do that. Some actions, such as toggle and setindex in effect force a refresh as part of their execution.

Any function which requires asking controls for information, such as index and case, will be up-to-date only after a refresh.

The reset Element

This action causes one or all of the instances of a model to be reset to their retained values.

Common Attributes: Action Common

Special attribute:

instance
Optional instance identifier.

Content: EMPTY

If the instance attribute is present, and it does not identify an instance, then an xforms-action-error event with an error-type of reset-instance is dispatched. Otherwise, the instance identified is returned to the state it had the last time it was retained, either during initialization, or as a result of a retain action.

If the attribute is not present, all instances in a model are so treated:

  • the model identified by the model attribute, if present;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.
<reset/>
<reset model="m"/>
<reset instance="admin"/>

The retain Element

This action causes one or all of the instances of a model to be retained for future use by the reset action. This is also done automatically for all instances at initialization.

Common Attributes: Action Common

Special attribute:

instance
Optional instance identifier.

Content: EMPTY

If the instance attribute is present, and it does not identify an instance, then an xforms-action-error event with an error-type of retain-instance is dispatched. Otherwise, the state of the instance identified is retained.

If the attribute is not present, all instances of a model are so treated:

  • the model identified by the model attribute, if present;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.
<retain/>
<retain model="m"/>
<retain instance="admin"/>

The load Element

This action traverses a link, giving a similar effect to clicking on an a element in HTML.

Common Attributes: Action Common, Single Item Binding (optional; deprecated)

Special Attributes:

resource
Optional URI of a resource to load.
target
Optional presentation environment name or keyword. Behavior is defined for values "_self" and "_blank". In addition, an implementation-dependent presentation name can be specified. The default is "_self".
show [deprecated]
Optional link behavior specifier. The allowed values are "replace", and "new".

Content: resource?

A URI is obtained from the resource attribute if present, otherwise from the resource child element if present [deprecated], and otherwise from the Single Item Binding [deprecated]; if none is present the action has no effect.

If the result is an empty sequence, an xforms-action-warning is dispatched, with an error-type of load-error, and the load action has no further effect.

The URI is the address of a resource, defined as an [XLink 1.0] link between the load element and the resource indicated. (No XLink actuate value is defined, since control of actuation is defined by XML Events.)

The target presentation environment is obtained from the target attribute, or otherwise the show attribute. If neither is present, "_self" is used.

The link indicated by the URI is traversed. Processing of the resource reached by traversing the link depends on the target presentation environment:

_self or replace
The document is loaded into the current presentation environment. XForms processing is ended, exactly as if the user had requested navigating to a new document.
_blank or new
The document is loaded into a new presentation environment, e.g., a new window or tab. XForms processing in the original context continues.
Any other value
Behavior is implementation-dependent.
Note:

If the host language is HTML, the implementation is encouraged to handle the target attribute as defined in HTML for the a element. In particular, values of "_blank", "_self", "_parent", "_top", as well as browsing context names should be supported.

If traversal is not possible or fails, then an xforms-action-warning should be dispatched, with an error-type of load-error; however, it is recognized that there are circumstances where this is not possible, such as when the error is discovered after XForms processing has ended.

<load resource="{../document}" target="_blank"/>
<load resource="http://example.com/index.html"/>

The resource Element (for load) (Deprecated)

The resource child element of load (deprecated in favor of using an AVT in the resource attribute) specifies the URI of a resource.

Common Attributes: Common, Evaluation, value

Content: PCDATA

The URI is obtained by evaluating the value attribute, or otherwise from the inline content of the element.

 <load target="_blank"><resource value="../document"/></load>
 <load><resource>http://example.com/index.html</resource></load>

The send Element

This action initiates submit processing by dispatching an xforms-submit event to a submission element.

Common Attributes: Action Common

Special Attributes:

submission
Optional reference to the ID of a submission element. If omitted, then the first submission in document order from the model associated with the in-scope evaluation context is used.

Content: EMPTY

A submission element is identified from the submission attribute or its default: if no such element is identified then an xforms-action-error event with an error-type of send-submission is dispatched; otherwise an xforms-submit event is dispatched to the element.

Processing of the xforms-submit event is defined in the processing model — see The xforms-submit Event.

<send submission="update"/>
<send/>
<send model="M1"/>

The return Element

This action returns values from an embedded XForm.

Common Attributes: Action Common

Special Attributes:

nonrelevant
Optional string indicating whether non-relevant values are included in the returned data. Values are "keep": all values are returned, "remove": non-relevant values are not returned, "empty": non-relevant nodes are returned as empty values. The default is "remove".

If the current XForm has not been embedded in another, or the control command invoking this XForm has not supplied a receiving binding, then an xforms-action-error event with an error-type of return-error is dispatched.

Otherwise, an update is done if necessary, and the binding attributes evaluated to give a nodeset, which is filtered for relevance according to the nonrelevant attribute as for a submission, and returned to the embedding XForm, where it is used to replace the node specified in the binding attribute of the control element in that XForm, as if by a submission with replace="instance" targetref="...".

<return ref="instance('result')"/>
<return ref="value[@selected=true()]"/>
<return ref="address" nonrelevant="keep"/>

The renew Element

This action causes the initial values of an embedded XForm to be re-initialised, possibly with new values.

Common Attributes: Action Common

Special Attributes:

control
Required ID of a control element.

Content: EMPTY

<instance id="start">
  <data xmlns="">
     <attempt>1</attempt>
     <score>0</score>
  
</instance>
...
<control id="game" resource="game.xml" initial="instance('start')"/>
<trigger label="restart">
  <action ev:event="DOMActivate">
     <setvalue ref="attempt" value=". + 1"/>
     <setvalue ref="score" value="0"/>
     <renew control="game"/>
  </action>
</trigger>

The message Element

This action presents a message to the user.

Common Attributes: Action Common, Single Item Binding, value (all optional)

Special Attributes:

level
Optional message-level identifier, one of ("ephemeral"|"modeless"|"modal"|PrefixedName). The default is "modal". There is no defined behavior for PrefixedName values.

Content: (PCDATA|UI Inline)*

The message text is obtained by evaluating the value attribute if given, otherwise from the Single Item Binding, if given, and otherwise from the inline content of the element. If the message is obtained from the inline content, then the output of any output controls in the message content is based on the instance data available when the message action occurs.

The user interface for the message action is created, and the message made available to the user in a manner based on the level attribute or its default.

<message value="concat('The time is ', substring-after(now(), 'T'))"/>
<model>
  <instance>
    <data xmlns="">
      <name>John</name>
    </data>
  </instance>
 
  <action ev:event="xforms-ready">
    <setvalue ref="name">world</setvalue>
    <message>Hello, <output ref="name"/>!</message>
    ...
  </action>
</model>

The message includes the latest user input even though other controls not in the message action are not guaranteed to be updated until the end of refresh processing:

<input ref="birthday" label="Enter birthday:">
  <message ev:event="xforms-invalid">
      <output ref="."/> isn't a valid date
  </message>
</input>

Since updates are not done during the processing of an action handler, if a message action is preceded by actions that change instance nodes, and the message references nodes that are computationally dependent on the changed nodes, then an update action should be done before the message action. For instance, with

<model>
  <instance>
    <data xmlns="">
      <a>0</a>
      
    
  </instance>
  <bind ref="b" calculate="../a+1"/>
  <action ev:event="xforms-ready">
    <setvalue ref="a" value="1"/> 
    <message><output ref="b"/></message>
  </action>
</model>

this will result in the value 1 being output. However, changing the action to

<action ev:event="xforms-ready">
  <setvalue ref="a" value="1"/>
  <update/> 
  <message><output ref="b"/></message>
</action>

will result in the output value 2.

Modal messages

With level="modal", further user interface operations are blocked until the message is explicitly dismissed by the user.

The Processor should support styling of modal messages in the host language integration.

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>

An alert popup, with a warning message.

Modeless messages

A modeless message is presented until explicitly dismissed, but does not inhibit other user interface operations. A Processor should support styling of ephemeral messages in the host language integration.

A graphical browser might render a modeless message as follows:

<secret ref="/login/password" label="Password:">
  <message level="modeless" ev:event="xforms-value-changed"
          if="length(.) > 3
              and matches(., '[A-Z]+$')
              and not(matches(., '[a-z]+'))">
     Is your caps-lock key on?
  </message>
</secret>

A password text entry form controls, with a tooltip below, reading 'Is your caps-lock key on?'

Ephemeral messages

An ephemeral message is presented only briefly, and need not be explicitly dismissed. A Processor should support styling of ephemeral messages in the host language integration.

In this example, the message appears briefly when a submit control is activated, offering an encouraging message.

<group label="Change of Address:">
    <input ref="name" label="Name:">
      <hint appearance="minimal">Last, First</hint>
    </input>
    <input ref="website" label="Website:">
      <hint appearance="minimal">http://</hint>
    </input>
    <submit submission="apply" label="Apply">
      <message level="ephemeral" ev:event="DOMActivate">Don't forget to write!</message>
    </submit>
</group>

A graphical browser might render an ephemeral message as follows: A group of text entry form controls, with a mouse pointer visible on a submit button, and a tooltip below, reading 'Don't forget to write!'

Actions from Other Modules

Of the action handlers detailed in this chapter, XForms defines some to be part of the XForms Switch and Repeat modules: The toggle Element and The setindex Element.

Conformance

Conforming XForms Documents

All XForms Containing Documents must conform to the following specifications, except as qualified below:

XForms elements are typically inserted into a containing document in multiple places. The root element for each individual fragment of XForms must be model, or a control. Individual XForms fragments are expected to be schema-valid according to the XML Schema for XForms (Schema for XForms), except that the host language may add elements of its own namespace to the content models of the following elements: group, repeat, case, label, help, hint, alert and message.

A host language may introduce additional conformance requirements.

Conforming XForms Generators

XForms generators should generate conforming XForms documents.

Base Technologies for XForms Processors

The following are base technologies for XForms. An XForms Processor therefore must conform to the following specifications, except as qualified below:

Conformance Levels

There are two levels of conformance: "model", and "full".

XForms Model

This conformance level is distinguished by the processor's property() function returning a string beginning with "model" for the conformance-level property.

An XForms Model Processor must support:

  • all attributes of the model element;
  • all attributes and content of the instance element;
  • all of [XPath 1.0], including all XForms extension functions (though the index() function may return 1 if the processor has no information about the identified repeat element);
  • the automatic datatype information defined by XForms;
  • parsing inline and external declared XML Schema and consuming their XML Schema datatype information [XML Schema part 2]; the processor should consume all XML Schema information available where appropriate in the processing model;
  • all of the Submission module except:
    • all NCName submission methods should be supported;
    • the mode attribute should be supported;
    • at least one of asynchronous or synchronous submission must be supported;
    • the file, mailto and ftp schemes may be supported;
    • submission headers may be combined with those from the user agent in the manner specified by the combine attribute;
  • all local attributes defined for every supported action, including conditional and iteration attributes;
  • the actions action, insert, delete, setvalue, reset, retain, rebuild, recalculate, revalidate, update, and dispatch;
  • the events xforms-model-construct-done, xforms-ready, xforms-link-error and xforms-version-error;
  • the ev:event attribute so that XForms action handlers can appear as children of either the target elements of the events they handle or ancestors of those elements.

An XForms Model Processor should support:

  • the attribute ev:target so action handlers can identify the events targetted at a particular descendant of the action handler's parent element (e.g. the xforms-insert or xforms-delete event on a particular instance of the model);
  • the notification events xforms-insert and xforms-delete, and all other events targetted at model elements except for xforms-refresh;
  • the actions send, load, refresh, setindex, setfocus, toggle, and message.

An XForms Model Processor may support:

  • user interface creation and refresh behaviors described for model processing;
  • the xforms-refresh event;

XForms Full

This conformance level is distinguished by the processor's property() function returning a string beginning with "full" for the conformance-level property.

An XForms Full Processor is an XForms Processor consisting of a conforming XForms Model Processor along with the following additional required, recommended and implementation-optional features.

The processor must support:

  • user interface creation and refresh behaviors described for model processing;
  • all core controls, including all of their attributes and child elements;
  • all container controls, including all of their attributes and child elements, except that support of the repeat-* attributes is implementation-optional;
  • the actions refresh, setfocus, and message;
  • all interaction and notification events targetted at controls and their descendant elements.

The processor may support the Extension module.

Glossary Of Terms

Atomic value
A value in the value space of an atomic type.
Atomic type
A primitive simple type or a type derived by restriction from another atomic type, as defined in XPath Data Model.
Binding
A connection using a binding expression from a control or a model item property to an item.
Binding expression
An expression used in a binding. The language used for the expression is defined by the expression module.
Compound Document
A document that combines multiple document formats either by reference, by inclusion or both, as defined in [CDRF 1.0].
Computed expression
An expression used by model item properties such as relevant and calculate to include dynamic functionality.
Containing document
A specific document, for example an XHTML document, in which one or more model elements are found.
Control
A point of user interaction (a core control) or a container for other controls (a container control).
Datatype
From XML Schema part 2: A 3-tuple, consisting of a) a set of distinct values, called its value space, b) a set of lexical representations, called its lexical space, and c) a set of facets that characterize properties of the value space, individual values or lexical items.
Disabled Control
A control failing at least one of the availability conditions.
Empty sequence
A sequence containing no items.
Enabled Control
A control satisfying all of the availability conditions.
Expression module
A separate specification defining the expression language used for addressing instance data nodes in binding expressions, to express constraints, and to specify calculations.
Facet
From XML Schema part 2: A single defining aspect of a value space. Generally speaking, each facet characterizes a value space along independent axes or dimensions.
First-item rule
When a Single Item Binding selects a sequence of size > 1, the first item in the sequence is used.
Host language
An XML vocabulary, such as XHTML, into which XForms is embedded.
Instance data
An internal representation of the values and states of data being processed.
Instance data node
A Node from the instance data.
Item
A node, or an atomic value (such as an integer, date, or string).
Lax schema processing
From XML Schema part 1: For an element or attributes Schema validity to be assessed, then the applicable schema must provide a definition of the item. If not, Schema validation makes no contribution to the validity test for the item.
Lexical space
From XML Schema part 2: A lexical space is the set of valid literals for a datatype. The XML serialization that may occur during submission expresses the instance data using lexical space literals.
Model Binding expression
An expression used in the ref attribute of a bind element in a model. Often, a bind also declares computed expressions for model item properties of the nodes.
Model item
An instance data node with associated constraints.
Model item property
An XForms-specific annotation to an instance data node.
Node
One of the seven kinds of node defined in the XPath Data Model: document, element, attribute, text, namespace, processing instruction, and comment.
Observer
An element that responds to an event through an event handler attached to it, as defined in XML Events.
PrefixedName
A QName that is not an NCName as defined in Namespaces in XML.
Schema constraint
A restriction, applied to instance data, based on XML Schema datatypes.
Sequence
A succession of zero or more items as defined in XPath Data Model.
simpleContent
Content of a node that has no element children.
Strict schema processing
From XML Schema part 1: If the applicable schema does not provide a definition for an element or attribute, then Schema validation marks the item as invalid.
String-value
A property of a Node, the string of characters that go to make up its content, as defined in XPath Data Model.
Typed-value
A property of a Node, the string-value of the node interpreted according to the type property of the node, as defined in XPath Data Model.
UI Binding Expression
An expression used in binding a control to the instance.
Valid node
An instance data node that is empty and not required, or otherwise whose value satisfies all applicable types and constraint model item properties.
Value space
From XML Schema part 2: A set of values for a given datatype. Each value in the value space of a datatype is denoted by one or more literals in its lexical space.
versionList
A list ([XML Schema part 2]) with an atomic datatype ([XML Schema part 2]) of versionNumber.
versionNumber
A string consisting of a non-zero digit (1 to 9) followed by zero or more digits (0 to 9), then a period character (.), and then one or more digits (0-9). A version number is derived from string by restriction based on the following pattern value (excluding the quote marks): "[1-9]\d*\.\d+".
XForms Model
The individual model items and constraints and other run-time aspects of XForms.
Processor
A software application or program that implements and conforms to the XForms specification.

References

Normative References

Exc-C14N
Exclusive XML Canonicalization Version 1.0, J. Boyer, D. Eastlake 3rd, J. Reagle, 2002. W3C Recommendation available at http://www.w3.org/TR/2002/REC-xml-exc-c14n-20020718/.
HMAC
RFC 2104 - HMAC: Keyed-Hashing for Message Authentication, H. Krawczyk, M. Bellare, R. Canetti, 1997. Available at http://www.ietf.org/rfc/rfc2104.txt
HTML5
HTML5, 2012. W3C Candidate Recommendation available at: http://www.w3.org/TR/html5/forms.html.
Language Identification in XML
Section Language Identification in XML 1.0.
Luhn Patent
Computer for Verifying Numbers, H. P. Luhn, U.S. Patent 2,950,048, 1960.
MD5
RFC 1321: The MD5 Message-Digest Algorithm, R. Rivest, 1992. Available at http://www.ietf.org/rfc/rfc1321.txt
RFC 2046
RFC 2046: Multipurpose Internet Mail Extensions (MIME) Part Two: Media Types, N. Freed, N. Borenstein, 1996. Available at http://www.ietf.org/rfc/rfc2046.txt.
RFC 2119
RFC 2119: Key words for use in RFCs to Indicate Requirement Levels, S. Bradner, 1997. Available at http://www.ietf.org/rfc/rfc2119.txt.
RFC 2387
RFC 2387: The MIME Multipart/Related Content-type, E. Levinson, 1998. Available at: http://www.ietf.org/rfc/rfc2387.txt.
RFC 2388
RFC 2388: Returning Values from Forms: multipart/form-data, L. Masinter, 1998. Available at: http://www.ietf.org/rfc/rfc2388.txt.
RFC 2396
RFC 2396: Uniform Resource Identifiers (URI): Generic Syntax, T. Berners-Lee, R. Fielding, L. Masinter, 1998. Available at: http://www.ietf.org/rfc/rfc2396.txt.
RFC 2616
RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1, R. Fielding, J. Gettys, J. Mogul, H. Frystyk, L. Masinter, P. Leach, T. Berners-Lee,1999. Available at: http://www.ietf.org/rfc/rfc2616.txt.
RFC 2818
RFC 2818: HTTP Over TLS, E. Rescorla, 2000. Available at: http://www.ietf.org/rfc/rfc2818.txt.
RFC 3023
RFC 3023: XML Media Types, M Murata, S. St. Laurent, D. Kohn, 2001. Available at: http://www.ietf.org/rfc/rfc3023.txt.
RFC 3987
RFC 3987: Internationalized Resource Identifiers (IRIs), M. Duerst, M. Suignard, 2005. Available at: http://www.ietf.org/rfc/rfc3987.txt.
RFC 5321
RFC 5321: Simple Mail Transfer Protocol, J. Klensin, 2008. Available at: http://www.ietf.org/rfc/rfc5321.txt.
RFC 6531
RFC 6531: SMTP Extension for Internationalized Email, J. Yao, W. Mao, 2012. Available at: http://www.ietf.org/rfc/rfc6531.txt.
SHA2
SECURE HASH STANDARD. FIPS PUB 180-2, August 2002. Available at http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf
SOAP 1.1
Simple Object Access Protocol (SOAP) 1.1 , D. Box, D. Ehnebuske, G. Kakivaya, A. Layman, N. Mendelsohn, H. F. Nielsen, S. Thatte, D. Winer, 2000. Available at: http://www.w3.org/TR/2000/NOTE-SOAP-20000508/.
SOAP 1.2
SOAP Version 1.2 Part 1: Messaging Framework, M. Gudgin, M. Hadley, N. Mendelsohn, J.-J. Moreau, H. F. Nielsen, A. Karmarkar, Y. Lafon, 2007. Available at: http://www.w3.org/TR/2007/REC-soap12-part1-20070427/.
Unicode Character Database
Unicode Standard Annex #44, Unicode Character Database, Available at: http://www.unicode.org/reports/tr44/.
Unicode Collation Algorithm
Unicode Technical Standard #10, Unicode Collation Algorithm, Available at: http://www.unicode.org/reports/tr10/.
XForms 2.0 -- XPath Expressions Module
XForms 2.0: XPath Expressions Module, Nick Van den Bleeken (ed.) W3C.
XHTML Modularization
XHTML Modularization 1.1, D. Austin, S. Peruvemba, S. McCarron, M. Ishikawa, M. Birbeck, 2008. W3C Recommendation available at http://www.w3.org/TR/2008/REC-xhtml-modularization-20081008.
XML Base
XML Base (Second Edition), J. Marsh, R. Tobin, 2009. W3C Recommendation available at: http://www.w3.org/TR/2009/REC-xmlbase-20090128/.
XML Events
XML Events - An events syntax for XML, Steven Pemberton, T. V. Raman, Shane P. McCarron, 2003. W3C Recommendation available at: http://www.w3.org/TR/2003/REC-xml-events-20031014/.
XHTML 1.0
XHTML 1.0: The Extensible HyperText Markup Language - A Reformulation of HTML 4 in XML 1.0, Steven Pemberton, et al., 2002. W3C Recommendation available at: http://www.w3.org/TR/2002/REC-xhtml1-20020801/.
XML 1.0
Extensible Markup Language (XML) 1.0 (Fourth Edition), Tim Bray, Jean Paoli, C. M. Sperberg-McQueen, Eve Maler, 2006. W3C Recommendation available at: http://www.w3.org/TR/2006/REC-xml-20060816/
XML Names
Namespaces in XML (Second Edition), Tim Bray, Dave Hollander, Andrew Layman, and Richard Tobin, 2006. W3C Recommendation available at: http://www.w3.org/TR/2006/REC-xml-names-20060816/.
XPath 1.0
XML Path Language (XPath) Version 1.0, James Clark, Steve DeRose, 1999. W3C Recommendation available at: http://www.w3.org/TR/1999/REC-xpath-19991116.
XPath 2.0
XML Path Language (XPath) 2.0, Anders Berglund et al., 2010. W3C Recommendation available at: http://www.w3.org/TR/2010/REC-xpath20-20101214/.
XPath Data Model
XQuery 1.0 and XPath 2.0 Data Model, Anders Berglund et al., 2010. W3C Recommendation available at: http://www.w3.org/TR/2010/REC-xpath-datamodel-20101214/ .
XML Schema part 1
XML Schema Part 1: Structures, Henry S. Thompson, David Beech, Murray Maloney, Noah Mendelsohn, 2004. W3C Recommendation available at: http://www.w3.org/TR/2004/REC-xmlschema-1-20041028/.
XML Schema part 2
XML Schema Part 2: Datatypes, Paul V. Biron, Ashok Malhotra, 2004. W3C Recommendation available at: http://www.w3.org/TR/2004/REC-xmlschema-2-20041028/.
XSLT 1.0
XSL Transformations (XSLT) Version 1.0, James Clark, 1999. W3C Recommendation available at: http://www.w3.org/TR/1999/REC-xslt-19991116.
XPath and XQuery Functions and Operators 3.0
XPath and XQuery Functions and Operators 3.0 , Michael Kay, 2013. W3C Candidate Recommendation available at: http://www.w3.org/TR/xpath-functions-30/.
XSLT and XQuery Serialization 3.0
XSLT and XQuery Serialization 3.0, Henry Zongaro, 2013. W3C Candidate Recommendation available at: http://www.w3.org/TR/xslt-xquery-serialization-30/.

Informative References

Algorithms
The Art of Computer Programming: Volume 1 Fundamental Algorithms, D. E. Knuth, Addison-Wesley, Reading, MA. 1968. Third edition, 1997. ISBN:0-2018-9683-4.
AUI97
Auditory User Interfaces--Toward The Speaking Computer, T. V. Raman, Kluwer Academic Publishers, 1997. ISBN:0-7923-9984-6.
CDRF 1.0
Compound Document by Reference Framework 1.0, Timur Mehrvarz, Lasse Pajunen, Julien Quint, and Daniel Applequist, 2007. W3C Candidate Recommendation available at: http://www.w3.org/TR/2007/CR-CDR-20070718/.
CSS2
Cascading Style Sheets, level 2 (CSS2) Specification, Bert Bos, HÃ¥kon Wium Lie, Chris Lilley, Ian Jacobs, 1998. W3C Recommendation available at: http://www.w3.org/TR/1998/REC-CSS2-19980512/.
CSV
Common Format and MIME Type for Comma-Separated Values (CSV) Files, Y. Shafranovich, 2005, available at https://tools.ietf.org/html/rfc4180.
DDJ-ArrayDoubling
Resizable Arrays, Heaps and Hash Tables, John Boyer, Doctor Dobb's Journal, CMP Media LLC, January 1998 Issue.
DOM2 Core
Document Object Model (DOM) Level 2 Core Specification, Tom Pixley, 2000. W3C Recommendation available at: http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/.
DOM2 Events
Document Object Model (DOM) Level 2 Events Specification, Tom Pixley, 2000. W3C Recommendation available at: http://www.w3.org/TR/2000/REC-DOM-Level-2-Events-20001113/.
EXSLT
EXSLT Web site. Available at http://exslt.org.
ICANN
New gTLD Dotless Domain Names Prohibited, ICANN, 2013. Available at https://www.icann.org/news/announcement-2013-08-30-en.
ITU E.123
Notation for national and international telephone numbers, e-mail addresses and web addresses, International Telecommunication Union, 2001, available at http://www.itu.int/rec/T-REC-E.123-200102-I/en.
JSON
The application/json Media Type for JavaScript Object Notation (JSON), D. Crockford, 2006, available at http://www.ietf.org/rfc/rfc4627.txt.
Media Types
Media Types, IANA, 2017, available at http://www.iana.org/assignments/media-types/media-types.xhtml.
ODF 1.1
NOTREF Open Document Format for Office Applications (OpenDocument) v1.1, Patrick Durusau, Michael Brauer, and Lars Oppermann (editors), 2007. OASIS Standard available at: http://docs.oasis-open.org/office/v1.1/OS/OpenDocument-v1.1-html/OpenDocument-v1.1.html.
P3P 1.0
The Platform for Privacy Preferences 1.0 (P3P1.0) Specification, Lorrie Cranor, Marc Langheinrich, Massimo Marchiori, Martin Presler-Marshall, Joseph Reagle, 2002. W3C Recommendation available at: http://www.w3.org/TR/2002/REC-P3P-20020416/.
RELAXNG
RELAXNG Specification, James Clark, MURATO Makoto, 2001. OASIS Committee Specification available at: http://www.relaxng.org/spec-20011203.html.
RELAXNG Compact
RELAXNG Compact Syntax, James Clark, 2002. OASIS Committee Specification available at: http://www.relaxng.org/compact-20021121.html.
SVG 1.1
SVG 1.1, Jon Ferraiolo, FUJISAWA Jun, Dean Jackson, 2003. W3C Recommendation available at: http://www.w3.org/TR/2003/REC-SVG11-20030114/.
TAG Finding 7
TAG Finding: URIs, Addressability, and the use of HTTP GET, Ian Jacobs, 2004. Available at: http://www.w3.org/2001/tag/doc/whenToUseGet-20040321
Unicode Script Names
ISO 15924: Codes for the representation of names of scripts, Available at: http://unicode.org/iso15924/iso15924-codes.html.
UAAG 1.0
User Agent Accessibility Guidelines 1.0, Ian Jacobs, Jon Gunderson, Eric Hansen, 2002. Working Draft available at http://www.w3.org/TR/UAAG10/.
Unicode Scripts
Script Names, Mark Davis, 2001. Unicode Technical Report #24 available at http://www.unicode.org/reports/tr24/.
XForms 1.0
XForms 1.0 Third Edition, John Boyer, 2007. W3C Recommendation available at: http://www.w3.org/TR/2007/REC-xforms-20071029/.
XLink 1.0
XML Linking Language (XLink) Version 1.0, Steve DeRose, Eve Maler, David Orchard, 2001. W3C Recommendation available at: http://www.w3.org/TR/2001/REC-xlink-20010627/.
XML Schema part 0
XML Schema Part 0: Primer Second Edition, David C. Fallside and Priscilla Walmsley, 2004. W3C Recommendation available at: http://www.w3.org/TR/2004/REC-xmlschema-0-20041028/.

Integration with SOAP

This section describes the integration of XForms submission with [SOAP 1.1] and [SOAP 1.2]

Representation of SOAP Envelope

The Single Item 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).

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.

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+xml
  • If the submission mediatype contains a charset MIME parameter, then it is appended to the application/soap+xml MIME type. Otherwise, a charset MIME parameter with same value as the encoding attribute (or its default) is appended to the application/soap+xml MIME type.
  • No other MIME parameters from the mediatype are copied to the application/soap+xml MIME type
  • The q MIME parameter must not be specified in the application/soap+xml MIME 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-type HTTP header is changed to text/xml
  • the charset MIME parameter is appended . The charset parameter value from the mediatype attribute is used if it is specified. Otherwise, the value of the encoding attribute (or its default) is used.
  • if the action MIME parameter appears in the mediatype then a SOAPAction HTTP header is added and given a value equal to the content of the action MIME parameter

Note:

XForms 2.0 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 2.0 does not support the SOAP 1.1 binding to the HTTP Extension Framework.

Example:

Consuming a SOAP 1.1 Request-Response Web Service
<model
   xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:tns="http://www.webservice.net">
   <instance id="data">
     <data xmlns="">
       <city>Victoria</city>
       <country>Canada</country>
       <weather>Mostly sunny and cool. High 12°C. Low 3°C.</weather>
     </data>
   </instance>

   <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>
   </instance>
   <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 12°C. Low 3°C.</GetWeatherResult>
         </GetWeatherResponse>
       </soap:Body>
     </soap:Envelope>
   </instance>

   <submission
     id="GetWeather" resource="http://www.webservice.net/getweather.asmx"
     method="post"
     ref="instance('GetWeatherSoapIn')"
     mediatype="application/soap+xml;
     resource=http://www.webservice.net/GetWeather"
     replace="instance"
     instance="GetWeatherSoapOut">
       <action ev:event="xforms-submit">
         <setvalue
           ref="instance('GetWeatherSoapOut')/soap:Body/tns:GetWeather/tns:CityName"
           value="instance('data')/city"/>
         <setvalue
          ref="instance('GetWeatherSoapOut')/soap:Body/tns:GetWeather/tns:CountryName"
          value="instance('data')/country"/>
       </action>
       <action ev:event="xforms-submit-done">
         <setvalue
           ref="instance('data')/weather"
           value="instance('GetWeatherSoapOut')/soap:Body/tns:GetWeatherResponse/tns:GetWeatherResult"/>
       </action>
   </submission>
 </model>

 <input ref="city" label="City">
    <send ev:event="xforms-value-changed" submission="GetWeather"/>
 </input>
 <input ref="country" label="Country">
    <send ev:event="xforms-value-changed" submission="GetWeather"/>
 </input>
 <output ref="weather" label="The weather forecast is"/>

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>

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.


Patterns for Data Mutations (Non-Normative)

This appendix provides several usage patterns for the setvalue, insert and delete actions that perform various kinds of mutations of instance data elements and attributes.

Prepend Element Copy

Operation: Prepend a new, empty person element into a list of people

Pattern: <insert context="parent of new element" origin="element to copy"/>

The context attribute is used so that it works whether or not the parent element is empty.

<insert context="people" origin="instance('prototypes')/person"/>

Data Before Operation

<instance>
  <data xmlns="">
    <people>
      <person>
        <name>Jane Doe</name>
      </person>
    </people>
  </data>
 </instance>
 <instance id="prototypes">
   <prototypes xmlns="">
     <person>
       <name/>
     </person>
   </prototypes>
</instance>

Data After Operation

<instance>
  <data xmlns="">
    <people>
      <person>
        <name/
      </person>
      <person>
        <name>Jane Doe</name>
      </person>
    </people>
 </data>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <person>
      <name/>
    </person>
  </prototypes>
</instance>

Append Element Copy

Operation: Append a new, empty person element into a list of people

Pattern: <insert context="parent of new element" ref="*" origin="element to copy"/>

The context attribute is used so that this pattern will work whether or not the parent element is empty.

<insert context="people" ref="person" origin="instance('prototypes')/person"/>

Data Before Operation

<instance>
  <data xmlns="">
    <people>
      <person>
        <name>Jane Doe</name>
      </person>
    </people>
  </data>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <person>
      <name/>
    </person>
  </prototypes>
</instance>

Data After Operation

<instance>
  <data xmlns="">
    <people>
      <person>
        <name>Jane Doe</name>
      </person>
      <person>
        <name/>
      </person>
    </people>
  </data>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <person>
      <name/>
    </person>
  </prototypes>
</instance>

Duplicate Element

Operation: Duplicate the selected element and place it as a following sibling

Pattern: <insert ref="exact element to duplicate"/>

The context attribute is not used because this pattern assumes the ability to indicate an exact element to duplicate, so ref is used. If the element does not exist, the operation will have no effect.

<insert ref="paragraph[2]"/>

Data Before Operation

<instance>
  <document xmlns="">
    <header>Lorem ipsum</header>
    <paragraph>Lorem ipsum verterem voluptaria ...</paragraph>
    <paragraph>Primis abhorreant delicatissimi ..</paragraph>
    <header>Lorem ipsum</header>
    <header>Lorem ipsum</header>
  </document>
</instance>

Data After Operation

<instance>
  <document xmlns="">
    <header>Lorem ipsum</header>
    <paragraph>Lorem ipsum verterem voluptaria ...</paragraph>
    <paragraph>Primis abhorreant delicatissimi ...</paragraph>
    <paragraph>Primis abhorreant delicatissimi ...</paragraph>
    <header>Lorem ipsum</header>
    <header>Lorem ipsum</header>
  </document>
</instance>

Set Attribute

Operation: Create or replace an attribute with a copy of a given attribute

Pattern: <insert context="container element receiving attribute" origin="attribute to copy"/>

The ref attribute is not used because this pattern cannot indicate an exact attribute sibling of the attribute being inserted. This is true not only because attribute order is not guaranteed but also because the attribute being inserted may already exist, in which case the existing attribute is replaced. The context attribute is used when it is necessary to indicate the parent of the node being inserted.

<insert context="item[2]" origin="../item[1]/@rating"/>
<insert context="item[3]" origin="../item[1]/@rating"/>

Data Before Operation

<instance>
  <items xmlns="">
    <item key="23" rating="classified"/>
    <item key="42"/>
    <item key="68" rating="unknown"/>
  </items>
</instance>

Data After Operation

<instance>
  <items xmlns="">
    <item key="23" rating="classified"/>
    <item key="42" rating="classified"/>
    <item key="68" rating="classified"/>
  </items>
</instance>

Remove Element

Operation: Remove item element in case it exists

Pattern: <delete ref="exact element to remove"/>

The context attribute is not used because this pattern assumes the ability to indicate an exact element to remove, so ref is used. If the element does not exist, the operation will have no effect.

<delete ref="item[2]"/>

Data Before Operation

<instance>
  <shoppingcart xmlns="">
    <item>
      <product>SKU-0815</product>
      <quantity>1</quantity>
      <unitcost>29.99</unitcost>
      <price>29.99</price>
    </item>
    <item>
      <product>SKU-4711</product>
      <quantity>3</quantity>
      <unitcost>7.49</unitcost>
      <price>22.47</price>
    </item>
  </shoppingcart>
</instance>

Data After Operation

<instance>
  <shoppingcart xmlns="">
    <item>
      <product>SKU-0815</product>
      <quantity>1</quantity>
      <unitcost>29.99</unitcost>
      <price>29.99</price>
    </item>
  </shoppingcart>
</instance>

Remove Attribute

Operation: Remove rating attribute in case it exists.

Pattern: <delete ref="exact attribute to remove"/>

The context attribute is not used because this pattern assumes the ability to indicate an exact attribute to remove, so ref is used. If the attribute does not exist, the operation will have no effect.

<delete ref="item/@rating"/>

Data Before Operation

<instance>
  <items xmlns="">
   <item key="23" rating="classified"/>
  </items>
</instance>

Data After Operation

<instance>
  <items xmlns="">
    <item key="23"/>
  </items>
</instance>

Remove Sequence

Operation: Remove track sequence in case it exists

Pattern: <delete ref="sequence to remove"/>

The context attribute is not used because this pattern assumes the ability to indicate a sequence to remove, so ref is used. If the sequence does not exist, the operation will have no effect.

<delete ref="track"/>

Data Before Operation

<instance>
  <playlist xmlns="">
    <name>Music for Airports</name>
    <track id="382"/>
    <track id="461"/>
    <track id="629"/>
  </playlist>
</instance>

Data After Operation

<instance>
  <playlist xmlns="">
    <name>Music for Airports</name>
  </playlist>
</instance>

Copy Sequence

Operation: Append a person sequence into a list of people

Pattern: <insert context="parent of new sequence" ref="*" origin="sequence to copy"/>

The context attribute is used so that this pattern will work whether or not the parent element is empty.

<insert context="people" ref="person" origin="instance('prototypes')/person"/>

Data Before Operation

<instance>
  <data xmlns="">
    <people/>
  </data>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <person>
      <name>Jane Doe</name>
    </person>
    <person>
      <name>John Doe</name>
    </person>
    <person>
      <name>Joe Sixpack</name>
    </person>
  </prototypes>
</instance>

Data After Operation

<instance>
  <data xmlns="">
    <people>
      <person>
        <name>Jane Doe</name>
      </person>
      <person>
        <name>John Doe</name>
      </person>
      <person>
        <name>Joe Sixpack</name>
      </person>
    </people>
  </data>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <person>
      <name>Jane Doe</name>
    </person>
    <person>
      <name>John Doe</name>
    </person>
    <person>
      <name>Joe Sixpack</name>
    </person>
  </prototypes>
</instance>

Copy Attribute List

Operation: Copy attribute list from one item to another

Pattern: <insert context="exact element receiving attribute list" origin="attribute list to copy"/>

<insert context="item[2]" origin="../item[1]/@*"/>

Data Before Operation

<instance>
  <items xmlns="">
    <item key="0" rating="classified"/>
    <item/>
  </items>
</instance>

Data After Operation

<instance>
  <items xmlns="">
    <item key="0" rating="classified"/>
    <item key="0" rating="classified"/>
  </prototypes>
</instance>

Replace Element

Operation: Replace a person element with a new one.

Pattern: <replace ref="exact element to replace" with="element to copy"/>

The context attribute is not used because this pattern assumes the ability to indicate an exact element to replace, so ref is used. If the element does not exist, the operation will have no effect.

<replace ref="person[1]" with="instance('prototypes')/person"/>

Data Before Operation

<instance>
  <people xmlns="">
    <person>
      <name>John Doe</name>
    </person>
  </people>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <person>
      <name/>
    </person>
  </prototypes>
</instance>

Data After Operation

<instance>
  <people xmlns="">
    <person>
      <name/>
    </person>
  </people>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <person>
      <name/>
    </person>
  </prototypes>
</instance>

Replace Attribute

Operation: Replace an attribute with the copy of a given attribute

Pattern: <setvalue ref="exact attribute to replace" value="attribute to copy"/>

If the attribute does not exist, the operation will have no effect.

<setvalue ref="item[2]/@key" value="../../item[1]/@key"/>

Data Before Operation

<instance >
  <items xmlns="">
    <item key="0"/>
    <item key="4711"/>
  </items>
</instance>

Data After Operation

<instance >
  <items xmlns="">
    <item key="0"/>
    <item key="0"/>
  </items>
</instance>

Replace Instance with Insert

Operation: Replace instance root node with an empty shoppingcart element

Pattern: <insert ref="root node of instance to replace" origin="element to copy"/>

The context attribute is not used because this pattern assumes the ability to indicate an instance root node to replace, so ref is used. Since an instance cannot be empty, ref will always be non-empty. Insert implements special handling for instance root nodes, thus a delete operation is not necessary.

<insert ref="." origin="instance('prototypes')/shoppingcart"/>

Data Before Operation

<instance>
  <shoppingcart xmlns="">
    <item>
      <product>SKU-0815</product>
      <quantity>1</quantity>
      <unitcost>29.99</unitcost>
      <price>29.99</price>
    </item>
    <item>
      <product>SKU-4711</product>
      <quantity>3</quantity>
      <unitcost>7.49</unitcost>
      <price>22.47</price>
    </item>
  </shoppingcart>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <shoppingcart/>
  </prototypes>
</instance>

Data After Operation

<instance>
  <shoppingcart xmlns=""/>
</instance>
<instance>
  <prototypes xmlns="">
    <shoppingcart/>
  </prototypes>
</instance>

Move Element

Operation: Copy an existing element to a new parent and remove the original

Pattern: <insert context="new parent of element" ref="*" origin="exact element to move"/> <delete ref="exact element to move"/>

The context attribute is used for insert so that this pattern will work whether or not the new parent element is empty. For delete the ref attribute is used instead because this pattern assumes the ability to indicate an exact element to move. If the element to be moved does not exist, both insert and delete operation will have no effect.

<insert context="playlist[2]" ref="track" origin="../playlist[1]/track[2]"/>
<delete ref="playlist[1]/track[2]"/>

Data Before Operation

<instance>
  <library xmlns="">
    <playlist>
      <name>Music for Airports</name>
      <track id="382"/>
      <track id="461"/>
      <track id="629"/>
    </playlist>
    <playlist>
      <name>Lullabies</name>
      <track id="251"/>
      <track id="331"/>
    </playlist>
  </library>
</instance>

Data After Operation

<instance>
  <library xmlns="">
    <playlist>
      <name>Music for Airports</name>
      <track id="382"/>
      <track id="629"/>
    </playlist>
    <playlist>
      <name>Lullabies</name>
      <track id="251"/>
      <track id="331"/>
      <track id="461"/>
    </playlist>
  </library>
</instance>

Move Attribute

Operation: Copy an existing attribute to a new element and remove the original

Pattern: <insert context="exact element receiving attribute" origin="exact attribute to move"/> <delete ref="exact attribute to move"/>

If the attribute to be moved does not exist, both insert and delete operation will have no effect.

<insert context="item[2]" origin="../item[1]/@rating"/>
<delete ref="item[1]/@rating"/>

Data Before Operation

<instance>
  <items xmlns="">
    <item key="23" rating="classified"/>
    <item key="42"/>
  </items>
</instance>

Data After Operation

<instance>
  <items xmlns="">
    <item key="23"/>
    <item key="42" rating="classified"/>
  </items>
</instance>

Insert Element into Non-Contiguous, Heterogeneous Sequence

Operation: Copy an existing element into a non-contiguous, heterogeneous sequence at a specified position

Pattern: <insert ref="non-contiguous, heterogeneous sequence" origin="element to copy" at="insert location"/>

The context attribute is not used because it adheres to the first-item rule and therefore would not allow to select a non-contiguous sequence. The ref attribute is used instead to select a sequence consisting of nodes with different names and different parents. The parent of the new node is the same as the parent of the insert location node selected by the combination of ref and at.

<insert ref="chapter/*" origin="instance('prototypes')/paragraph" at="7" position="before"/>

Data Before Operation

<instance>
  <document xmlns="">
    <chapter>
      <header>Lorem ipsum</header>
      <paragraph>Lorem ipsum verterem voluptaria ...</paragraph>
      <diagram>Exemplum 1</diagram>
      <diagram>Exemplum 2</diagram>
      <paragraph>Primis abhorreant delicatissimi ...</paragraph>
    </chapter>
    <chapter>
      <header>Lorem ipsum</header>
      <diagram>Exemplum 3</diagram>
    </chapter>
  </document>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <chapter/>
    <header/>
    <paragraph/>
    <diagram/>
  </prototypes>
</instance>

Data After Operation

<instance>
  <document xmlns="">
    <chapter>
      <header>Lorem ipsum</header>
      <paragraph>Lorem ipsum verterem voluptaria ...</paragraph>
      <diagram>Exemplum 1</diagram>
      <diagram>Exemplum 2</diagram>
      <paragraph>Primis abhorreant delicatissimi ...</paragraph>
    </chapter>
    <chapter>
      <header>Lorem ipsum</header>
      <paragraph/>
      <diagram>Exemplum 3</diagram>
    </chapter>
  </document>
</instance>
<instance id="prototypes">
  <prototypes xmlns="">
    <chapter/>
    <paragraph/>
    <diagram/>
  </prototypes>
</instance>

Move Elements Up and Down in a List

Operation: Reorder elements in a list by moving them up and down, for instance to sort a list into order of preference.

Pattern: <insert origin="context()" ref="preceding/following-sibling::*[1]" position="before/after"/> <delete ref="."/>

Example data:

<instance>
   <films xmlns="">
      <film>The Sound of Music</film>
      <film>The Big Lebowski</film>
      <film>Gone with the Wind</film>
      <film>Inception</film>
   </films>
</instance>

Example controls to effect the movement:

<repeat ref="film">
   <input ref="." label="Film:"/>
   <trigger ref=".[preceding-sibling::*]" label="↑">
      <action ev:event="DOMActivate">
         <insert origin="context()" ref="preceding-sibling::*[1]" position="before"/>
         <delete ref="."/>
      </action>
   </trigger>
   <trigger ref=".[following-sibling::*]" label="↓">
      <action ev:event="DOMActivate">
         <insert origin="context()" ref="following-sibling::*[1]"/>
         <delete ref="."/>
      </action>
   </trigger>
</repeat>

What it might look like:

A repeat with controls for reordering the list items

Recalculation Sequence Algorithm (Non-Normative)

This appendix gives an example of how a recalculate might be done. The algorithm considers model items and model item properties to be vertices in a directed graph. Edges between the vertices represent computational dependencies.

  1. A master dependency directed graph is created.
  2. A pertinent dependency subgraph is computed consisting only of vertices and edges that are reachable from nodes that require recomputation. (Note that on a first recomputation, such as on initialization, the pertinent dependency subgraph will be the same as the master dependency directed graph.)
  3. A topological sort is performed on the vertices of the pertinent dependency subgraph, resulting in an order of evaluation in which each vertex is evaluated only after those vertices on which it depends and before all vertices which depend on it. An example of a topological sort algorithm can be found in [Algorithms].

Creating the Master Dependency Directed Graph

The master dependency directed graph can be considered an array with one record for each vertex, each having the following fields:

InstanceNode: a reference to the associated instance data node
type: indicates the aspect of the instance node represented by the vertex (the text content or a model item property such as readOnly or required)
depList: a list of vertices that refer to this vertex
in-degree: the number of vertices on which this vertex depends
visited: a flag used to ensure vertices are not added to a subgraph multiple times
index: an association between vertices in the master dependency directed graph and a subgraph.

The depList for each vertex is assigned based on the referenced XML nodes of instance nodes, which are obtained by parsing the computed expression bound to the node (e.g., by calculate, relevant, readonly, or required).

Specifically, the depList for a vertex v is assigned to be the vertices other than v whose computational expressions reference v (described below). Vertex v is excluded from its own depList to allow self-references to occur without causing a circular reference error.

A computational expression appearing in a calculate attribute controls the text content (value) of one or more instance nodes. A vertex exists for each instance node to represent the expression in the context of the node. Likewise, computational expressions for model item properties such as readOnly and required are applied to one or more instance nodes, and vertices are created to represent such expressions in the context of each applicable node. The computational expression of each vertex must be examined to determine the XML nodes to which it refers.

A computation expression refers to a vertex v if a subexpression indicates the InstanceNode for v and v represents the instance node text content (its value). In this version of XForms, model item properties such as readonly and required cannot be referenced in an expression.

Any expression violating any Binding Expression Constraint causes the recalculate flag to be cleared and an xforms-compute-error event to be dispatched. If the event is not canceled, processing halts (this is the default action of the xforms-compute-error event). If the event is canceled, the recalculate process is terminated after the recalculate flag is cleared, but XForms processing otherwise continues.

Creating the Pertinent Dependency Subgraph

If all calculations must be performed, which is the case initially, then the pertinent dependency subgraph is simply a duplicate of the master dependency directed graph. If the recalculation algorithm is invoked with a list of changed instance data nodes since the last recalculation, then the pertinent dependency subgraph is obtained by exploring the paths of edges and vertices in the computational dependency directed graph that are reachable from each vertex in the change list. The method of path exploration can be depth first search, a suitable version of which appears in the pseudo-code below.

The algorithm creates a pertinent dependency subgraph S from a list of changed instance data nodes Lc. Variables such as v and w represent vertices in the master dependency directed graph. The same variables ending with S indicate vertices in the pertinent dependency subgraph S.

It uses depth-first search to explore the master digraph subtrees rooted at each changed vertex. A visited flag is used to stop exploration at the boundaries of previously explored subtrees (since subtrees can overlap in directed graphs).

for each vertex r in Lc
  if r is not visited
  {
    Push the pair (NIL, r) onto a stack
    while the stack is not empty
    {
      (v, w) = pop dependency pair from stack
      if w is not visited
      {
        Set the visited flag of w to true
        Create a vertex wS in S to represent w
        Set the index of w equal to the array location of wS
        Set the index of wS equal to the array location of w
        Set the InstanceNode of wS equal to the InstanceNode of w
        Set the type of wS equal to the type of w
        For each dependency node x of w
          Push the pair (w, x) onto the stack
      }
      else Obtain wS from index of w
      if v is not NIL
      {
        Obtain vS from index of v
        Add dependency node for wS to vS
        Increment inDegree of wS
      }
    }
  }
// Now clear the visited flags set in the loop above
for each vertex vS in S
{
  Obtain v from index of vS
  Assign false to the visited flag of v
}

Note that the number of vertices and dependency nodes in the pertinent dependency subgraph is not known beforehand, but a method such as array doubling (see [DDJ-ArrayDoubling]) can be used to ensure that building the subgraph is performed in time linear in the size of S.

Computing Individual Vertices

The following steps process vertices:

  1. A vertex with inDegree of 0 is selected for evaluation and removed from the pertinent dependency subgraph. In the case where more than one vertex has inDegree zero, no particular ordering is specified. If the pertinent dependency subgraph contains vertices, but none have an inDegree of 0, then the calculation structure has a loop. In this case, the recalculate flag is cleared and an xforms-compute-error event is dispatched. If the event is not canceled, processing halts (this is the default action of the xforms-compute-error event). If the event is canceled, the recalculate process is terminated after the recalculate flag is cleared, but processing otherwise continues.
  1. If the vertex corresponds to a computed item, computed expressions are evaluated as follows:
    1. calculate: If the value of the model item changes, the corresponding instance data is updated and the dirty flag is set.
    2. relevant, readonly, required, constraint: If any or all of these computed properties change, the new settings are placed into effect for associated controls.
  2. For each vertex in the depList of the removed vertex, decrement the inDegree by 1.
  3. If no vertices remain in the pertinent dependency subgraph, then the calculation has successfully completed. Otherwise, repeat this sequence from step 1.

Example of Calculation Processing

For example, consider six vertices a, b, v, w, x, and y. Let a and b represent the text content of instance nodes that will be set by a binding from user input controls. Let v and w be vertices representing the calculated value and the validity property of a third instance node c. These vertices would result from a bind element B with calculate and constraint attributes and a ref attribute that indicates c. Suppose that the value of c is the product of a and b and that the value is only valid if it does not exceed 100. Likewise, suppose x and y are vertices representing the calculated value and the validity property of a fourth instance node d. Let the value of d be the sum of a and b, and let d be valid if the value does not exceed 20. The figure below depicts the dependency digraph for this example.

Dependency graph

Vertices a and b have edges leading to v and x because these vertices represent the calculate expressions of c and d, which reference a and b to compute their product and sum, respectively. Similarly, v and x have directed edges to w and y, respectively, because w and y represent the constraint expressions of c and d, which reference the values of c and d to compare them with boundary values.

If a and b are initially equal to 10, and the user changes a to 11, then it is necessary to first recalculate v (the value of c) then recalculate w (the validity property of the value of c). Likewise, x (the value of d) must be recalculated before recalculating y (the validity property of the value of d). In both cases, the validity of the value does not change to false until after the new product and sum are computed based on the change to a. However, there are no interdependencies between v and x, so the product and sum could be computed in either order.

The pertinent subgraph excludes b and only vertex a has in-degree of zero. The vertex a is processed first. It is not a computed vertex, so no recalculation occurs on a, but its removal causes v and x to have in-degree zero. Vertex v is processed second. Its value changes to 121, and its removal drops the in-degree of vertex w to zero. Vertex x is processed next, changing value to 21. When x is removed, its neighbor y drops to in-degree zero. The fourth and fifth iterations of this process recalculate the validity of w and y, both of which change to false.

Privacy Considerations (Non-Normative)

Using P3P with XForms

P3P privacy policies may be associated with any forms transmitted over HTTP that have URIs associated with them. In the future, mechanisms may be specified for associating P3P policies with content transmitted over other protocols.

P3P allows for policies to be associated with an individual URI or a set of URIs. By associating a separate policy with each URI a site can declare a very precise policy that addresses exactly what data is collected with a particular HTTP request and how that data will be used. However, site management is substantially easier for many sites if they declare a single policy that covers many URIs, or even their entire Web presence.

The P3P specification specifies several methods for referencing a P3P policy reference file, which in turn associates P3P policies with URIs and cookies. XForms can be P3P enabled using any of the methods that are appropriate for the Web site in which they are embedded. Some special considerations regarding forms are addressed in the P3P Specification. [P3P 1.0]

Different P3P policies may be applied to the representation of a form embedded in a containing document to that which is associated with the data submitted via that form. If the form representation is served from a different server than the form is submitted to, it is likely that separate P3P policy reference files and policies will be needed. Typically the form representation causes only clickstream data (as defined in [P3P 1.0] section 5.6.4) to be transferred, while a form submission causes much more data to be transferred.

Input Modes (Non-Normative)

The attribute inputmode provides a hint to the user agent to select an appropriate input mode for the text input expected in an associated control. The input mode may be a keyboard configuration, an input method editor (also called front end processor) or any other setting affecting input on the device(s) used.

Using inputmode, the author can give hints to the agent that make form input easier for the user. Authors should provide inputmode attributes wherever possible, making sure that the values used cover a wide range of devices.

inputmode Attribute Value Syntax

The value of the inputmode attribute is a white space separated list of tokens. Tokens are either sequences of alphabetic letters or absolute URIs. The latter can be distinguished from the former by noting that absolute URIs contain a ':'. Tokens are case-insensitive. All the tokens consisting of alphabetic letters only are defined in this specification, in List of Tokens (or a successor of this specification).

This specification does not define any URIs for use as tokens, but allows others to define such URIs for extensibility. This may become necessary for devices with input modes that cannot be covered by the tokens provided here. The URI should dereference to a human-readable description of the input mode associated with the use of the URI as a token. This description should describe the input mode indicated by this token, and whether and how this token modifies other tokens or is modified by other tokens.

User Agent Behavior

Upon entering an empty control with an inputmode attribute, the user agent should select the input mode indicated by the inputmode attribute value. User agents should not use the inputmode attribute to set the input mode when entering a control with text already present. To set the appropriate input mode when entering a control that already contains text, user agents should rely on platform-specific conventions.

User agents should make available all the input modes which are supported by the (operating) system/device(s) they run on/have access to, and which are installed for regular use by the user. This is typically only a small subset of the input modes that can be described with the tokens defined here.

Note:

Additional guidelines for user agent implementation are found at [UAAG 1.0].

The following simple algorithm is used to define how user agents match the values of an inputmode attribute to the input modes they can provide. This algorithm does not have to be implemented directly; user agents just have to behave as if they used it. The algorithm is not designed to produce "obvious" or "desirable" results for every possible combination of tokens, but to produce correct behavior for frequent token combinations and predictable behavior in all cases.

First, each of the input modes available is represented by one or more lists of tokens. An input mode may correspond to more than one list of tokens; as an example, on a system set up for a Greek user, both "greek upperCase" and "user upperCase" would correspond to the same input mode. No two lists will be the same.

Second, the inputmode attribute is scanned from front to back. For each token t in the inputmode attribute, if in the remaining list of tokens representing available input modes there is any list of tokens that contains t, then all lists of tokens representing available input modes that do not contain t are removed. If there is no remaining list of tokens that contains t, then t is ignored.

Third, if one or more lists of tokens are left, and they all correspond to the same input mode, then this input mode is chosen. If no list is left (meaning that there was none at the start) or if the remaining lists correspond to more than one input mode, then no input mode is chosen.

Example: Assume the list of lists of tokens representing the available input modes is: {"cyrillic upperCase", "cyrillic lowerCase", "cyrillic", "latin", "user upperCase", "user lowerCase"}, then the following inputmode values select the following input modes: "cyrillic title" selects "cyrillic", "cyrillic lowerCase" selects "cyrillic lowerCase", "lowerCase cyrillic" selects "cyrillic lowerCase", "latin upperCase" selects "latin", but "upperCase latin" does select "cyrillic upperCase" or "user upperCase" if they correspond to the same input mode, and does not select any input mode if "cyrillic upperCase" and "user upperCase" do not correspond to the same input mode.

List of Tokens

Tokens defined in this specification are separated into two categories: Script tokens and modifiers. In inputmode attributes, script tokens should always be listed before modifiers.

Script Tokens

Script tokens provide a general indication of the set of characters that is covered by an input mode. In most cases, script tokens correspond directly to [Unicode Scripts]. However, this neither means that an input mode has to allow input for all the characters in the script, nor that an input mode is limited to only characters from that specific script. As an example, a "latin" keyboard doesn't cover all the characters in the Latin script, and includes punctuation which is not assigned to the Latin script.

The script tokens that are allowed are listed in [Unicode Script Names], "codes for the representations of scripts". The allowable values are those listed in the column "Property Value Alias" with the underscore character (_) removed, and excluding the two values "Common", and "Unknown". At the time of writing, these values are:

Arabic, Armenian, Balinese, Bengali, Bopomofo, Braille, Buginese, Buhid, CanadianAboriginal, Carian, Cherokee, Coptic, Cuneiform, Cypriot, Cyrillic, Deseret, Devanagari, Ethiopic, Georgian, Glagolitic, Gothic, Greek, Gujarati, Gurmukhi, Han, Hangul, Hanunoo, Hebrew, Hiragana, Kannada, Katakana, KatakanaOrHiragana, KayahLi, Kharoshthi, Khmer, Lao, Latin, Lepcha, Limbu, LinearB, Lycian, Lydian, Malayalam, Mongolian, Myanmar, NewTaiLue, Nko, Ogham, OlChiki, OldItalic, OldPersian, Oriya, Osmanya, PhagsPa, Phoenician, Rejang, Runic, Saurashtra, Shavian, Sinhala, Sundanese, SylotiNagri, Syriac, Tagalog, Tagbanwa, TaiLe, Tamil, Telugu, Thaana, Thai, Tibetan, Tifinagh, Ugaritic, Vai, Yi

Seven other values are allowed:

Input Mode Token Comments
ipa International Phonetic Alphabet
hanja Subset of 'han' used in writing Korean
kanji subset of 'han' used in writing Japanese
math

mathematical symbols and related characters, representing the [Unicode Script Names] code "Zmth"

simplifiedHanzi

representing the [Unicode Script Names] code "Hans"

traditionalHanzi

representing the [Unicode Script Names] code "Hant"

user special value denoting the 'native' input of the user according to the system environment

Modifier Tokens

Modifier tokens can be added to the scripts they apply in order to more closely specify the kind of characters expected in the control. Traditional PC keyboards do not need most modifier tokens (indeed, users on such devices would be quite confused if the software decided to change case on its own; CAPS lock for upperCase may be an exception). However, modifier tokens can be very helpful to set input modes for small devices.

Input Mode Token Comments
lowerCase lowercase (for bicameral scripts)
upperCase uppercase (for bicameral scripts)
titleCase title case (for bicameral scripts): words start with an upper case letter
startUpper start input with one uppercase letter, then continue with lowercase letters
digits digits of a particular script (e.g. inputmode='thai digits')
symbols symbols, punctuation (suitable for a particular script)
predictOn text prediction switched on (e.g. for running text)
predictOff text prediction switched off (e.g. for passwords)
halfWidth half-width compatibility forms (e.g. Katakana; deprecated)

Relationship to XML Schema pattern facets

User agents may use information available in an XML Schema pattern facet to set the input mode. Note that a pattern facet is a hard restriction on the lexical value of an instance data node, and can specify different restrictions for different parts of the data item. Attribute inputmode is a soft hint about the kinds of characters that the user may most probably start to input into the control. Attribute inputmode is provided in addition to pattern facets for the following reasons:

  1. The set of allowable characters specified in a pattern may be so wide that it is not possible to deduce a reasonable input mode setting. Nevertheless, there frequently is a kind of characters that will be input by the user with high probability. In such a case, inputmode allows to set the input mode for the user's convenience.
  2. In some cases, it would be possible to derive the input mode setting from the pattern because the set of characters allowed in the pattern closely corresponds to a set of characters covered by an inputmode attribute value. However, such a derivation would require a lot of data and calculations on the user agent.
  3. Small devices may leave the checking of patterns to the server, but will easily be able to switch to those input modes that they support. Being able to make data entry for the user easier is of particular importance on small devices.

Examples

<input ref="name" inputmode="kanji" label="Family name:"/>
<input ref="nameKana" inputmode="katakana" label="Family name in kana:"/>
<input ref="given" inputmode="kanji" label="Given name:"/>
<input ref="givenKana" inputmode="katakana" label="Given name in kana:"/>
<input ref="email" inputmode="latin lowerCase" label="Email:"/>
<input ref="phone" inputmode="latin digits" label="Telephone:"/>
<textarea ref="comments" inputmode="user predictOn" label="Comments:"/>
<submit submission="sendit" label="Send It"/>

Schema for XForms (Non-Normative)

The XML Schema for XForms, which has a target namespace http://www.w3.org/2002/xforms, is located at http://www.w3.org/MarkUp/Forms/2007/XForms-11-Schema.xsd.

The RELAXNG ([RELAXNG], [RELAXNG Compact]) Schema for XForms, which includes the target namespace http://www.w3.org/2002/xforms as well as the version suitable for import to a host language namespace, is located at http://www.w3.org/MarkUp/Forms/2007/XForms-11-RELAXNG.zip.

Schema for XML Events

This XML Schema for XML Events is referenced by the XML Schema for XForms, and located at http://www.w3.org/TR/2003/REC-xml-events-20031014/#a_schema_attribs.

XForms and Styling (Non-Normative)

This informative section provides a broad outline of new and existing CSS features needed to style XForms content. A future Recommendation from the CSS Working Group will fully develop the specification of these features.

Pseudo-classes

A CSS pseudo-class is used to select elements for styling based on information that lies outside of the document tree or that cannot be expressed using the other selectors.

Name Relationship to XForms
:enabled & :disabled

Selects any control that is enabled or disabled (respectively). Defined in [CSS3].

:required & :optional Selects any core control bound to a node with the model item property required evaluating to true or false (respectively).
:valid & :invalid Selects any core control bound to a node that is currently valid or invalid (respectively), as defined by XForms.
:read-only & :read-write Selects any core control bound to a node with the model item property readonly evaluating to true or false (respectively).
:out-of-range & :in-range Selects any core control bound to a node that contains a value the control is not or is capable of rendering, (respectively).
:value-empty & :value-non-empty Selects any core control bound to a node whose content is the empty string or not the empty string (respectively).

This list is not exhaustive; other pseudo-classes may be defined.

Pseudo-elements

Pseudo-elements are abstractions about the document tree beyond those specified by the document language. Pseudo-elements do not appear in the DOM; they are used only for purposes of styling.

Name Relationship to XForms
::value Represents the "active" area of a control excluding the label; this corresponds in HTML to input and other control elements. This pseudo-element is a child of the control element, and appears immediately after the required label element.
::switch-case Represents the identity of the selected case of a switch.
::repeat-item Represents a single item from a repeating sequence. Its position is as a parent to all the elements in a single repeating item. Each ::repeat-item is associated with a particular item, and is affected by the model item properties (e.g. 'relevant') found there, as the related style properties will cascade to the child elements.
::repeat-index Represents the current item of a repeating sequence. Its position is as a parent of all the elements in the index repeating item (and as a child to the ::repeat-item pseudo-element), thus any style declarations applying to this pseudo-element override those on the parent ::repeat-item.

This list is not exhaustive; other pseudo-elements may be defined.

Styling Examples

The following examples collect together styling recommendations from this document, expressed in CSS. The following namespace declaration is assumed:

@namespace xf url('http://www.w3.org/2002/xforms');

Most controls have an inline layout by default.

 xf|input:enabled, xf|secret:enabled, xf|textarea:enabled, xf|output:enabled,
 xf|upload:enabled, xf|range:enabled, xf|trigger:enabled, xf|submit:enabled,
 xf|select:enabled, xf|select1:enabled { display: inline; }
 xf|output:enabled { display: inline; }
 xf|switch:enabled { display: inline; }
 xf|repeat:enabled { display: inline; }
 ::repeat-item:enabled, xf|group:enabled { display:block; }

Disabled content is not presented, or it may be styled as disabled.

 xf|input:disabled, xf|secret:disabled, xf|textarea:disabled,
 xf|output:disabled, xf|upload:disabled, xf|range:disabled,
 xf|trigger:disabled, xf|submit:disabled, xf|select:disabled,
 xf|select1:disabled
 {
   display: none;
 }

 xf|output:disabled { display: none; }
 xf|group:disabled, xf|switch:disabled { display: none; }
 ::repeat-item:disabled { display: none; }
 

The default display:none styling of :disabled can be overidden. Note that the implementation must also implement the behavior of not accepting user input in the disabled control.

xf|input.authorization:disabled {
   display: inline; background-color: #bbbbbb
}

A read-only control should render in a way which indicates that entering or changing the value is not allowed. For example:

xf|input:enabled:read-only::value
{
  display: inline; background-color: #888888
}

Except as noted, enabled controls must distinguish rendering between being bound to a required node versus a non-required node. Exceptions are controls that do not directly render the string value of the bound node (including trigger and the container controls). Below is an example styling controls bound to required nodes with a soft yellow background. An implementation could use this style by default, and an author would only need to use styling to override the default.

xf|input:enabled:required, xf|secret:enabled:required,
xf|textarea:enabled:required, xf|output:enabled:required,
xf|upload:enabled:required, xf|range:enabled:required,
xf|trigger:enabled:required, xf|submit:enabled:required,
xf|select:enabled:required, xf|select1:enabled:required
{
   background-color: #FFFFD0
}

Enabled controls must distinguish rendering between valid and invalid states. Below is an example styling input controls bound to non-empty but invalid nodes with a reddish background.

xf|input:enabled:invalid:value-non-empty {
   background-color: #ff8080;
}

Enabled controls must indicate when the bound instance data contains a value or content that the control is not capable of rendering. In this example, select, select1, and range controls bound nodes whose values are not presentable by the controls are styled with in red.

xf|select1:enabled:out-of-range, xf|select1:enabled:out-of-range,
xf|range:enabled:out-of-range {
  color: red;
}

Complete XForms Examples (Non-Normative)

This section presents complete XForms examples.

<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:ev="http://www.w3.org/2001/xml-events" 
      xml:lang="en">
  <head>
    <title>XForms in XHTML</title>
    <model xmlns="http://www.w3.org/2002/xforms">
       <instance>
          <payment as="credit" xmlns="">
             <cc/>
             <expiry/>
          </payment>
       </instance>
       <submission resource="http://www.example.com/buy.rb" method="post"/>
       <bind ref="cc" type="card-number" constraint="is-card-number(.)"
             relevant="../@as='credit'" required="true()" whitespace="remove"/>
       <bind ref="expiry" constraint="matches(., '^[0-9][0-9]/(0[1-9]|1[012])$')
             relevant="../@as='credit'" required="true()"/>
    </model>
  </head>
  <body>
    ...
    <group xmlns="http://www.w3.org/2002/xforms">
       <select1 ref="@as" label="Select Payment Method">
          <item label="Cash" value="'cash'">
             <message level="modeless" ev:event="xforms-select">
                      Please do not mail cash.</message>
          </item>
          <item label="Credit">credit</item>
       </select1>

       <input ref="cc" label="Credit Card Number"
              alert="Please specify a valid credit card number (spaces permitted)"/>

       <input ref="expiry" label="Expiry Date" hint="YY/MM" alert="Format: YY/MM"/>

       <submit label="Buy"/>
    </group>
    ...
 </body>
 </html>
<html xml:lang="en"
      xmlns="http://www.w3.org/1999/xhtml"
      xmlns:xforms="http://www.w3.org/2002/xforms"
      xmlns:ev="http://www.w3.org/2001/xml-events">
  <head>
     <title>Editing Hierarchical Bookmarks</title>
     <model version="2.0" xmlns="http://www.w3.org/2002/xforms">
        <instance resource="bookmarks.xml"/>
        <bind ref="section/bookmark/@href" type="anyURI"/>
        <instance id='template'>
            <section name="" xmlns="">
                <bookmark href="" name=""/>
            </section>
        </instance>
        <submission method="post" resource="http://examples.com/"/>
     </model>
  </head>
  <body>
     <group xmlns="http://www.w3.org/2002/xforms">
        <!-- Display bookmarks -->
        <repeat ref="section" id="Sections">
           <input ref="@name" class="editField">
              <label class="sectionLabel">Section</label>
           </input>
           <repeat ref="bookmark" id="Bookmarks">
              <input ref="@name" label="Bookmark name"/>
              <input ref="@href" label="URL"/>
           </repeat>
        </repeat>

        <!-- Insert Bookmark -->
        <trigger label="Insert bookmark">
           <insert ref="section[index('Sections')]/bookmark" origin="instance('template')/bookmark"
                   at="index('Bookmarks')" ev:event="DOMActivate"/>
        </trigger>

        <!-- Delete Bookmark -->
        <trigger label="Delete bookmark">
           <delete ref="section[index('Sections')]/bookmark" 
                   at="index('Bookmarks')" ev:event="DOMActivate"/>
        </trigger>

        <!-- Insert Section -->
        <trigger label="Insert section">
           <insert ref="section" at="index('Sections')" origin="instance('template')"
                   ev:event="DOMActivate"/>
        </trigger>

        <!-- Delete Section -->
        <trigger label="Delete section">
           <delete ref="section" at="index('Sections')" 
                   ev:event="DOMActivate"/>
        </trigger>

        <submit label="Save" hint="Click to submit"/>
    </group>
  </body>
 </html>

Initial instance file bookmarks.xml:

<bookmarks>
    <section name="main">
       <bookmark href="http://www.example.com/xforms.xml" name="Main page"/>
    </section>
    <section name="demos">
       <bookmark href="http://www.example.com/demo/images.fo" name="images"/>
       <bookmark href="http://www.example.com/demo/xf-ecma.xml" name="ecma"/>
       <bookmark href="http://www.example.com/demo/sip.fo" name="sip"/>
    </section>
    <section name="XForms">
       <bookmark href="file:/source/xmlevents.xml" name="XML events"/>
       <bookmark href="file:/source/model3.xml" name="model3"/>
       <bookmark href="file:/source/repeat.fo" name="repeat"/>
    </section>
 </bookmarks>

The following example shows one possible way of integrating XForms with [SVG 1.1]. Note that the complete set of rules for integrating XForms and SVG are not fully specified at the time this specification was published. Future versions of the XForms, SVG, or other W3C specifications might define more complete rules for integration.

<html xmlns="http://www.w3.org/1999/xhtml" 
      xmlns:xf="http://www.w3.org/2002/xforms">
 <head>
    <title>Barchart</title>
    <style type="text/css">
        .xforms-repeat-item {display: inline}
        .histogram  { border: thin black solid; text-anchor:middle; }
        .box    { fill: blue; stroke: black; stroke-width:1; }
        .title  { fill: gray;  }
    </style>
    <model xmlns="http://www.w3.org/2002/xforms">
        <instance id="data" resource="years.xml"/>
        <bind id="histdata" ref="instance('data')/y"/>
 
        <instance id="chart">
            <barchart xmlns="">
                <title>Values</title>
                <n/><miny/><maxy/><depth/><height/><range/><vscale/><hscale/>
            </barchart>
        </instance>
        <bind ref="n"      calculate="count(bind('histdata'))"/>
        <bind ref="maxy"   calculate="max(bind('histdata'))"/>
        <bind ref="miny"   calculate="min(bind('histdata'))"/>
 
        <bind ref="height" calculate="if(../maxy > 0, ../maxy, 0)"/>
        <bind ref="depth"  calculate="if(../miny &lt; 0, 0 - ../miny, 0)"/>
        <bind ref="range"  calculate="../height + ../depth"/>
        <bind ref="vscale" calculate="100 div ../range" type="double"/>
        <bind ref="hscale" calculate="100 div ../n"     type="double"/>
    </model>
 </head>
 <body>
    <svg xmlns="http://www.w3.org/2000/svg" version="1.0" viewBox="0 0 200 200" height="400" width="400" class="histogram">
        <g transform="translate(50,150)">
            <xf:repeat bind="histdata">
                <rect x="{(position() - 1) * instance('chart')/hscale}" 
                      y="{(0 - (choose(. < 0, 0, .) + instance('chart')/depth)) * instance('chart')/vscale}"
                      height="{choose(. < 0, 0 - ., .) * instance('chart')/vscale}" 
                      width="{instance('chart')/hscale}" class="box"/>
            </xf:repeat>
            <text x="50" y="20" class="title"><xf:output ref="title"/></text>
        </g>
    </svg>
 </body>
 </html>

This example might produce a histogram like the following:


A histogram for a number of values.

Differences between XForms 2.0 and XForms 1.1 (Non-Normative)

  • Expressions
    • Uses higher versions of XPath, instead of XPath 1; allows amongst other things atomic values and typed values
    • Attribute Value Templates (AVTs) allow calculated values to be used in attributes, enabling the deprecation of many child elements
    • Custom functions and variables have been added
    • New functions: valid() relevant() readonly() required() case() serialize() seconds-from-epoch() bind() element() attribute() parse() eval() eval-in-context() location-uri() location-param() uri-scheme() uri-scheme-specific-part() uri-authority() uri-user-info() uri-host() uri-port() uri-path() uri-query() uri-fragment() uri-param-names() uri-param-values()
  • Data
    • External instance fallback: if @src on <instance/> fails, the instance is initialised with the inline content.
    • Multiple MIPs of the same property allowed on one node.
    • New whitespace MIP defines how space is treated in values
    • json, csv and other external instance data formats are supported
    • slight change in how nested binds select items.
  • Types
    • The definition of validity has been slightly changed to allow empty non-required values to be considered valid. Consequently, the XForms datatypes no longer all include empty as a possible value.
    • better email type
    • new types:
      • two IRI types
      • iemail type
      • telephone number type
      • HTMLFragment type
  • Controls
    • The @nodeset attribute is deprecated in favour of @ref everywhere
    • The @dir attribute is allowed everywhere for specifying text direction
    • a new dialog element
    • a new <control/> element for embedding an XForm in an XForm, plus actions <return/>, and <renew/>
    • repeat has an @indexref attribute
    • <repeat appearance='minimal' .../> <group appearance='minimal' ...>
    • switch has a @caseref attribute
    • an item of a select1 can be deselected
    • label, hint, help, alert
      • attributes have been added as alternatives to the child elements
      • properties have been added to the bind element
      • label elements/attributes are consequently now optional on controls
      • Unification of how output, label, help, hint, and alert work.
      • No linking on <help/>
      • @appearance on <alert> (erratum)
  • Actions
    • @iterate has been added to actions
    • <update/>
    • <cancel/> action added
    • <insert/> no longer makes values of type ID unique
    • <insert/> and <delete/> indexes must be in range.
    • All actions that have an IDREF attribute now dispatch an xforms-action-error if that attribute does not identify a (suitable) element.
    • ability to call script (such as JavaScript) from actions, including passing parameters
    • <reset instance="id"/> and <retain/>
    • <return/>, and <renew/> to go with <control/> element.
    • Small change in the order of evaluation of <load/> attributes
  • Events
    • add properties to dispatched events
    • xforms-action-warning event added
    • xforms-submit-ready event added
    • xforms-refresh-done event added
    • xforms-rebuild, xforms-recalculate, xforms-revalidate, xforms-refresh, and xforms-reset events deprecated in favour of the respective actions
    • xforms-submit-serialize deprecated
    • event handlers are no longer disabled when their associated controls are disabled.
    • events now conditionally cancellable with <cancel/> action
  • Submission
    • @response-mediatype overrides incoming mediatype
    • get is default submission method
    • @nonrelevant replaces @relevant, with new options
    • @value available for providing data to be submitted
  • Other
    • <form> element as root element if one is needed
    • p3ptype has been deprecated


Acknowledgements (Non-Normative)

This document was produced with the participation of Forms Working Group participants, including:

  • John M. Boyer, IBM (Past Editor, Past Chair)
  • Erik Bruchez, Orbeon
  • Kurt Cagle, Invited expert
  • Alain Couthures, Invited expert
  • Philip Fennell, MarkLogic
  • Leigh L. Klotz, Jr., Xerox Corporation (Past Editor, Past Co-chair)
  • Ulrich Nicolas Lissé, DreamLab
  • Dan McCreary, Invited expert
  • Steven Pemberton, CWI (Chair)
  • T.V. Raman, Google
  • Sebastian Schnitzenbaumer
  • Nick Van den Bleeken, Inventive Designers n.v. (Past Editor)
  • Alessandro Vernet, Orbeon
  • Charles Wiecha, IBM

Production Notes (Non-Normative)

This document was created using an instance of MediaWiki. The sources were transformed to W3C format using a modified version of Sandro Hawke's revdoc.

<script src="//www.w3.org/scripts/TR/2016/fixup.js"></script>