XForms 2.0

From XForms Users Community Group
Jump to: navigation, search
__NUMBEREDHEADINGS__



Document title:
XForms 2.0
Editors
Erik Bruchez, Orbeon
Steven Pemberton, CWI
Nick Van den Bleeken, Inventive Designers
Past Editors
John M. Boyer, IBM
Leigh L. Klotz, Jr., Xerox
Abstract
XForms is an XML markup for a new generation of forms and form-like applications on the Web. XForms is not a free-standing document type, but is integrated 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. The underlying data of a form is organized into instances. XForms allows processing of data to occur 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 form 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.

Contents

1 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 platform-independent markup language for online interaction.

The original version of XForms was purely about forms, and followed HTML fairly closely in what it could do. However, because of 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.

1.1 Differences between XForms 2.0 and XForms 1.1

Editorial note: Complete list 2016-12-05
Complete list of differences below

New:

  • XPath 2, also allows atomic values, typed values
  • AVTs - many child elements deprecated
  • label, hint, help, alert available as attributes as well as child elements
  • Expressions: Custom functions and Variable support
  • json, csv and other external instance data formats supported
  • repeat @indexref
  • switch @caseref
  • @iterate
  • dialog
  • add properties to dispatched events
  • @nodeset is deprecated in favour of @ref
  • p3ptype is deprecated
  • Multiple MIPs of the same property allowed on one node.
  • whitespace MIP
  • get is default submission method
  • @appearance on <alert> (erratum)
  • ability to call script (such as JavaScript) from actions, including passing parameters
  • <insert/> no longer makes values of type ID unique
  • <insert/> and <delete/> indexes must be in range.

1.2 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.

1.3 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, may, and optional in accord with [RFC 2119]. Generally, the elements, attributes, functions and behaviors of XForms defined in this specification are required to be implemented unless explicitly specified otherwise. The term author-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. The term author-optional is orthogonal to the conformance status (required, recommended, or 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.

2 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. So you never have to worry about, for instance, the total price of goods being out-of-date, and the user doesn't have to press a 'recalculate' button.
  • 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.

The original version of XForms was purely about forms, and followed HTML fairly strictly in what it could do in many cases. However, because of 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.

2.1 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.

2.2 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>2017-08</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=2017-08

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

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

2.3 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.

2.4 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.

2.5 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 it is possible to assign types to values. For instance in the example, there are datatypes that represent an integer, and a decimal type for representing monetary values:

<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(.)"/>

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"/>

2.6 Relevance and Required Values

In the example, the input controls 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()"/>
   <submission resource="https://example.com/submit" method="post"/>
 </model>

2.7 Attribute Values

Values can be displayed using the output element, but a new feature is the ability to output into attributes as well, with a feature known as attribute value templates (AVTs). These are marked with braces "{" and "}". Any part of an attribute may be replaced.

For instance, with

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

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.

2.8 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.

3 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.

3.1 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. XForms always requires such a host language.

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>

3.2 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

ANY

3.2.1 The extension Element

Author-optional element extension 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

<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>

4 Core Attribute Collections

4.1 Common Attributes

The Common Attribute Collection applies to every element.

anyAttribute
Foreign attributes are allowed on all elements.
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, i.e. since authors are most likely to place Events attributes on the actual event handler elements.
id [not AVT]
An author-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.
model [not AVT]
Author-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 author-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.

4.2 Binding Attributes

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

bind [not AVT]
Reference to a bind element. If the value of the attribute does not refer to a 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)
Author-optional 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 author-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"/>

4.3 The Value Attribute

This attribute is an expression that is used by elements in a variety of ways.

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.

4.4 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.

4.5 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 curly brackets ({}). A fixed part may contain any characters, except that a left curly bracket must be written as {{ and a right curly bracket must be written as }}.

Note: An expression within a variable part may contain an unescaped curly bracket within a StringLiteral or within a comment.

If one of the following error conditions occur, an xforms-expression-error event is dispatched to the element containing the expression:

  • an unescaped left curly bracket appears in a fixed part of an attribute value template without a matching right curly bracket.
  • an unescaped right curly bracket occurs in a fixed part of an attribute value template.
  • the string contained between matching curly brackets in an attribute value template is not a valid expression, or contains other static errors.

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

4.5.1 AVT Evaluation

The result of evaluating an attribute value template is called the effective value of the attribute. The effective value is the string obtained by concatenating the expansions of the fixed and variable parts:

  • The expansion of a fixed part is obtained by replacing any double curly brackets ({{ or }}) by the corresponding single curly bracket.
  • The expansion of a variable part is obtained by evaluating the enclosed expression as a string, using the in-scope evaluation context.

Curly brackets are not treated specially in attributes that can't contain an attribute value template.

Attribute value templates are evaluated when necessary. If the attribute is on a control, its effective value is calculated on refresh. If the attribute is on an Action, its effective value is calculated when the action is executed.

Note:

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

<output class="{if (total ge 0) then 'positive' else 'negative'}" ref="total"/>
<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 brackets. If the id element pointed to contains the string C72E5, the resource attribute would take the value:

/forms/detail/C72E5

5 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]

(ANY)

bind

Common, 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)*
function Common, signature[not AVT], override? (var*, result)?
result Common, value (expression) EMPTY
var Common, name (QName), value (expression) EMPTY

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.

The Processor must ignore unrecognized foreign-namespaced attributes.

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

5.1 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]
Author-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]
Author-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 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]
Author-optional attribute 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.
<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.

5.2 The instance Element

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

Common Attributes: Common

Special Attributes:

src [not AVT]
Author-optional link to externally defined initial instance data.
resource [not AVT]
Author-optional link to externally defined initial instance data.

The data for the instance is obtained from the link in the src attribute, if present, otherwise from the inline content of the instance element if present, and otherwise from the link in the resource attribute. If a link traversal fails, an xforms-link-error event is dispatched to the parent model.

All data relevant to the XPath data model must be preserved during processing and as input to submission serialization, including processing instructions, comment nodes and all whitespace.

Note that the only difference between the src and resource attributes is the precedence over inline content, which is principally of use in automatically-generated forms.

<instance>
  <screen xmlns="">
    <height>1024</height>
    <width>1920</width>
  </screen>
</instance>
<instance resource="https://example.org/templates/a1.xml"/>

5.2.1 Creating instance data from inline content

If the initial instance data is given by inline content, then instance data is obtained as follows:

  1. A detached copy of the first and only 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 event is dispatched 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 of the xforms-link-error event). If the event is canceled, processing continues.

The resulting XML document is converted to an XPath data model and associated with the source instance element.

<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>

5.2.2 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 [XDM] 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 media type accepted for external sources by the processor, the processor must provide an equivalent serialization using the serialization attribute of the submission element.

If the initial instance data is given by a link (from src or resource), and the link cannot be traversed, or the link can be traversed but the XPath data model cannot be created from the resource:

  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 event with a resource-uri of the link that failed is dispatched. If the event is not canceled, processing halts (this is the default action of the xforms-link-error event). If the event is canceled, processing continues.

Otherwise the instance data is formed by creating an XPath data model of the linked resource as described below.

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

5.2.2.1 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].

5.2.2.2 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</load>
    <_ type="number">0.33</load>
    <_ type="number">0.32</load>
  </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"><p type="null"/></json>
p
{"p": ""}
<json type="object"><p/></json>
p
{"p": []}
<json type="object"><p type="array"/></json>
p
{"p": {}}
<json type="object"><p 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.

5.2.2.3 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 media type), 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"/>
5.2.2.4 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>

5.3 The bind Element

The bind element associates properties with values in instance data.

Common Attributes: Common

Special Attributes:

ref
An author-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 item.
nodeset [deprecated]
A synonym for ref. It has no meaning if attribute ref is present.
type [not AVT]
An author-optional type. Default is type xf:string.
constraint
An author-optional boolean expression. Default is true.
relevant
An author-optional boolean expression. Default is true.
required
An author-optional boolean expression. Default is false.
readonly
An author-optional boolean expression. Default is false.
calculate
An author-optional expression. Default is no calculated expression.
whitespace
An author-optional string value with allowable values "preserve", "remove", "trim", "collapse", and "normalize". Default is "preserve".
p3ptype [deprecated] [not AVT]
An author-optional string. Default is empty string.

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="c"><bind calculate="../a + ../b"/></bind>
<bind ref="c"><bind context=".." calculate="a+b"/></bind>

5.3.1 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.

If Model Item Properties are attached to atomic values or nodes that don't belong to an instance, an xforms-binding-error event 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
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.

5.3.2 The type Property

This property associates a datatype with an instance 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 string-value (as defined in [XPath 1.0]) of the instance node. It can be applied to both elements and attributes, but not to instance nodes that contain child elements.

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. It does not prevent controls and Actions from setting invalid values into data nodes.

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:my="http://example.org">
 
   <xs:schema targetNamespace="http://example.org" xmlns:my="http://example.org">
     <xs:simpleType name="Currency">
       <xs:restriction base="xs:string">
         <xs:enumeration value="USD"/>
         <xs:enumeration value="EUR"/>
       </xs:restriction>
     </xs:simpleType>
 
     <xs:complexType name="Price">
       <xs:simpleContent>
         <xs:extension base="xs:double">
           <xs:attribute name="currency" type="my:Currency" use="optional" default="USD"/>
         </xs:extension>
       </xs:simpleContent>
     </xs:complexType>
   </xs: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="my:simpleType/my:price" type="double"/>
   <bind ref="my:complexType/my:price" type="my:Price"/>
   <bind ref="my:complexType/my:price[3]/@currency" type="my:Currency"/>
 
 </model>

5.3.3 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.

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'.

5.3.4 The required Property

This property describes whether a value is required before the instance data can be submitted.

Computed Expression: Yes.

Legal Values: Any boolean expression.

Default Value: false.

Inheritance Rules: does not inherit.

This property indicates whether the instance data node must be non-empty before a submission of the instance data can occur. A value is non-empty if it would have a length greater than zero if converted to string using the string conversion function as described in the expression module.

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.

5.3.5 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 not relevant, this value is also not relevant. Otherwise, the local value is used.

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. When a control is bound to a relevant node it is called 'enabled', and 'disabled' when bound to a non-relevant node. Enabled controls should be made available for user interaction; disabled controls (and any children), must be made unavailable, removed from the navigation order, and not allowed focus. Typically, disabled content is not presented, or is styled differently.

Elements other than controls may also use a Single Item Binding that selects a non-relevant node, but such elements are not made unavailable or non-operable because the binding is not a UI binding expression. For example, actions such as setvalue and message, or the submission element remain operable even if their Single Item Bindings select a non-relevant node, although their operation may be affected. For example, non-relevant nodes are by default excluded from the data of a submission, and event handlers for events targeted to a non-relevant control are disabled.

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.

5.3.6 The calculate Property

This property calculates a value for the associated node.

Computed Expression: Yes.

Legal Values: Any expression.

Default Value: none.

Inheritance Rules: does not inherit.

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. On evaluation, the calculate expression is converted to a string with the string conversion function as described in the expression module, and stored as the value content of the associated data node. The processing model describes when and how the calculation is performed.

<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.

5.3.7 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.

When evaluating to false, the associated data node is not valid (the converse is not necessarily true). The processing model specifies when and how the constraint is calculated as well as when validation is performed.

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.

<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"/>

5.3.8 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].

5.3.9 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"/>

5.4 Model Processing

XForms processing is based on responding to events that signal change of state:

  • Each model is initialized as a result of receiving the xforms-model-construct event from the system.
  • After all models have been initialized, an xforms-model-construct-done event is dispatched to each model. This results in the user interface being initialized.
  • After all xforms-model-construct-done events have been processed, an xforms-ready event is dispatched to each model element, signalling the start of user interface processing.

After that, processing is done as described in Processing.

5.4.1 Dependencies

As a result of bindings within a model, values can depend on each other in various ways.

If during processing values within an instance change, a recalculate is done, which calculates the new values of dependent items.

If during processing the structure of one or more instances change, due to the insertion or deletion of elements, a rebuild is done, where the dependencies are updated, followed by a recalculate.

In either case, after the recalculate, a revalidate is done, to check the validity of the new values, followed by a refresh, that updates the user interface.

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.

Given the following default instance:

<instance>
   <data xmlns="">
      <a attr="X">
         <b attr="Y">
            <c/>
         </b>
         <d/>
      </a>
      <a attr="Z">
         <b attr="Z">
            <c/>
         </b>
         <d/>
      </a>
   </data>
</instance>

and the following XPath expression:

a[@attr='X']/b[@attr='X']/c

Both nodes named a are referenced since both are matched by a NameTest. The attr attribute in each element a is referenced during the evaluation of the filter expression. The filter expression rejects the second element a, but that element is still considered to have been referenced because it was selected for further processing during the expression evaluation.

The element named b in the first element a is referenced, but element b in the second a is not referenced because the expression evaluation did not proceed beyond the filter expression that rejected the second a element.

While performing the NameTest for element b, observe that an XPath expression evaluator may visit all the children of the first element a in order to perform the NodeTest. However, a node is not referenced if it is only visited but fails the NodeTest. In this case, the NodeTest is a NameTest for b, which the element d fails. Therefore, d is not referenced.

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

Element c is not considered to be referenced by this expression given this data. Although a NameTest for c appears in the expression, the evaluation of the expression did not proceed to perform the NameTest due to the rejection of b by the filter expression.

Finally, note that an XPath expression can reference many nodes even if its final result is the empty sequence.

5.4.1.1 Dynamic Dependencies

The references of an expression may be altered by insertion of instance nodes since the new nodes may be referenced by the expression if it is re-evaluated. Similarly, the references of an expression may be altered by deletion of instance nodes that are being referenced by the expression.

An expression is dynamically dependent on an instance node if its set of references is altered by inserting, deleting or changing the value of the instance node.

An instance node is a dynamic dependency for an expression if the expression is dynamically dependent on the instance node. If an expression contains a dynamic dependency and the XForms Processor is maintaining dependency lists for the category of the expression, then changing the dynamic dependency implies a change to the dependency lists of instance nodes referenced by the expression.

The computational dependency data structure described in recalculate essentially stores the dependency lists of instance nodes corresponding to all the references made by computed expressions (see Appendix Recalculation Sequence Algorithm for details). The computational dependency data structure is not reconstructed in response to a dynamic dependency change. Instead, the form author may request a rebuild of the computational dependency data structures using the rebuild action. Additionally, the insert and delete actions set a rebuild flag so that computational dependency data structures will be rebuilt at the end of an action sequence.

Due to the rebuild flag setting on insert and delete, a form author can use many kinds of dynamic dependencies in model binding expressions and computed expressions without ever explicitly invoking the rebuild action. This includes the use of functions such as position(), last(), and count() on element and attribute nodes because the return values of the functions in these cases is fixed except when an insert or delete occurs. By comparison, functions such as id(), instance(), and index() can establish dynamic dependencies that can necessitate invoking a rebuild if they are used in model binding expressions or computed expressions because the results of the functions are affected by changing the values of instance nodes, not by inserting or deleting nodes.

Dynamic dependencies in model binding expressions and computed expressions will require manual rebuilding of dependencies.

Note:

If the index() function is being invoked from a model binding expression or computed expression, it will be necessary to invoke rebuild manually. If the repeat index change occurs due to an implicit behavior such as a change to the focused control, then the rebuild (along with recalculate, revalidate and refresh) can be invoked from a handler for DOMFocusIn attached to the repeat or each repeat object.

5.4.2 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 event is dispatched. If that event is not canceled, processing halts (this is the default action of the xforms-link-error event). If the event is canceled, processing continues as if the XML Schema had not been linked in the first place.

For each instance element, an XPath data model is constructed from it as described in The instance Element section. If there are no instance elements, the data model is not constructed in this phase, but during user interface construction (The xforms-model-construct-done Event).

If applicable, P3P initialization occurs. [P3P 1.0]

A rebuild, recalculate, and revalidate are then performed in sequence for this model. (A refresh is not performed since the user interface has not yet been initialized.)

5.4.3 Rebuild

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

Each bind in the model is applied. Then the computational dependency data structures are rebuilt, and a change list L is set to contain references to all instance nodes that have an associated computational expression so that a full recalculation is performed on the next recalculate.

5.4.4 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 event 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.

If a required, readonly, or relevant model item property changes as a result of a recalculate, then events must be marked for dispatch. Marking one in any pair unmarks the other:

  • xforms-required or xforms-optional for required;
  • xforms-readonly or xforms-readwrite for readonly;
  • xforms-enabled or xforms-disabled for relevant.

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.

5.4.5 Revalidate

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

An instance node is valid if and only if the following conditions hold:

  • the constraint model item property is true
  • the value is non-empty if the required model item property is true
  • the node satisfies all applicable types (including those associated by the type model item property, by an external or an inline XML Schema, or by xsi:type).

If the validity of a node changes, then either the xforms-valid or the xforms-invalid event must be marked for dispatch accordingly to bound controls. Marking one unmarks the other.

Note: Since model initialization excludes doing a refresh and discards event notification marks, controls bound to invalid nodes do not receive an initial xforms-invalid event.

5.4.6 Refresh

All UI Expressions are re-evaluated (implementations may optimize this operation but must behave as if all are refreshed).

If the value of an instance data node has changed (such as by user interaction, a setvalue action, or as a result of a recalculate), then the xforms-value-changed event must be marked for dispatch for the node, along with all of the appropriate model item property notification events (xforms-optional or xforms-required, xforms-readwrite or xforms-readonly, and xforms-enabled or xforms-disabled) that have also changed as a result.

The user interface is updated to reflect the state of the model, including:

  • current values
  • validity and the other model item properties (required, readonly and relevant).
  • the proper number of, and content for, repeat objects.

Marked notification events are dispatched to the controls bound to the nodes that originated the events. The notification events xforms-out-of-range or xforms-in-range must also be dispatched as appropriate. There is no defined ordering for the events.

5.4.7 Reset

All instances in the model are reset to what they were immediately after initialization, and a rebuild, recalculate, revalidate, and refresh are then performed in sequence for this model.

5.4.8 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 non-relevant; if the result is an atomic value, the control is 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.

If the name is not a valid QName, the xforms-binding-error event is dispatched to the control and the control is bound to the empty sequence.

 <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>

6 Expressions

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

  • 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 depending on 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.
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.

6.1 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.

An element inherits an 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 default context from the referenced model is used instead. If the element has a context attribute, it is evaluated in the resulting context. The final context is called the in-scope evaluation context.

If an element has a ref attribute, it is evaluated in the in-scope context. If the element has a bind attribute, the bind element referenced has its own context. If the ref or bind 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. The result gives the element evaluation context.

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.

Unless otherwise stated, all expressions in attributes on an element are evaluated in the element evaluation context.

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

For top-level elements, that have no ancestors, the inherited 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.

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 events xforms-binding-error, for a bind element, xforms-action-error for an Action, and xforms-expression-error otherwise, is dispatched.

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 context, and the dot selector "." returns its context item.

So the following would output 1 2:

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

6.2 Typed Values

When referencing a node, an expression might require the value of that node. In addition, some expression languages, such as XPath 2.0, support accessing the typed-value of a node in addition to the string-value of a node. The typed-value always consists of a sequence of atomic values.

When the expression language selected is XPath 2.0 or newer, and the associated type is integer or one of the built-in primitive datatypes listed in XForms Datatypes (either in the XForms namespace or the XML Schema namespace), the typed-value of nodes must be supplied to the expression language based on type information associated with the node, either by the type model item property or by xsi:type.

If the associated type is one of the XForms datatypes allowing empty content, the corresponding XML Schema datatype must be supplied to the expression engine by the implementation.

An implementation may provide additional datatypes.

If the type information is associated by an external or an inline XML Schema, the typed-value of nodes should be supplied to the expression language when possible, following the Typed Value Determination in [XDM]. If a node is invalid and the XML Schema validator cannot provide type information, or if the processor for the expression language does not support certain types provided by an XML Schema, the implementation is allowed to omit providing specific type information for the associated nodes.

Editorial note: Type from XML Schema 2013-09-24
Feedback is welcome on the approach proposed here with regard to XML Schema.
Editorial note: xs:untypedAtomic 2013-09-24
Does anything need to be said about providing xs:untypedAtomic to the expression?

For backwards compatibility, when the expression language selected is XPath 1.0, the typed-value of nodes must not be supplied.

This specification does not define whether the typed-value of nodes is supplied to the expression language or not when the expression language selected is neither XPath 1.0 nor XPath 2.0.

Note:

The typed-value must in particular be available to expressions running during the default processing of xforms-recalculate, even though revalidation via the default processing of xforms-revalidate might not have happened yet.

Because XForms has a mutable model and type information reflects the desired datatype of a node rather than a guaranteed datatype, the situation can arise that the typed-value of a given node cannot be obtained when requested by the expression. For example, if the string-value of the node is a blank string or the string acme, and the datatype is xs:decimal, it is not possible to create a value of type xs:decimal. When this situation arises, the evaluation of the expression must be interrupted.

If the evaluation of an expression is interrupted because of such a type error, the XForms Processor must take the following action:

  • if the expression is a calculate expression, the result of the expression is the empty sequence
  • if the expression is a constraint expression, the result of the expression is false()
  • if the expression is another xforms:bind computed expression, the result of the expression is not applied to the node
  • if the expression is any other type of expression, the xforms-expression-error event is raised.

The following XPath 2 example shows how type information can be used to simplify expressions by reducing the number of casts:

<model>
    <instance>
       <data xmlns="">
          <a/>
          <b/>
          <c/>
          <sum1/>
          <sum2/>
       </data>
    </instance>
    <bind ref="a | b | c | sum2" type="xs:decimal"/>
    <bind ref="sum1" type="xforms:decimal"/>
    <bind ref="sum1" calculate="sum((../a, ../b, ../c))"/>
    <bind ref="sum2" calculate="sum((../a, ../b, ../c)[string() castable as xs:decimal], 0.0)"/>
 </model>

 <input ref="a"/>
 <input ref="b"/>
 <input ref="c"/>
 <output ref="sum1" label="Sum only if all values are decimal:"/>
 <output ref="sum2" label="Sum all decimal values and ignore other values:"/>

Also note how, with XPath 2, it is possible to access the string value of a node with the standard string() function, and to test the type of the node before using it.

6.3 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 event must be dispatched to the model element. If that event is not canceled, processing halts (this is the default action of the xforms-compute-error event). 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 Event, xforms-binding-error Event, or xforms-action-error Event) 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>

6.4 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

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.
value
Author-optional expression.

The value of a variable 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.

<var name="message" value="instance('message')"/>
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.

6.4.1 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 upon xforms-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.

6.4.2 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 XPath 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 event is dispatched.

Note:

This is unlike XSLT, which discourages but allows shadowing.

<trigger label="Show">
  <action ev:event="DOMActivate">
    <var name="message" value="instance('message')"/>
    <message ref="$message"/>
  </action>
</trigger>
<var name="message" value="instance('message')"/>
<trigger label="Show">
  <message ev:event="DOMActivate" ref="$message"/>
</trigger>
<action iterate="items/item">
  <var name="current-item" value="."/>
  <insert context="$current-item" origin="xforms:element('label'), xforms:element('value')"/>
</action>
<var name="binding" value="quantity"/>
<input ref="$binding" label="Quantity"/>
<var name="items" value="items/item"/>
<select ref="my-item" label="Item">
  <itemset ref="$items" label="{name}" value="value"/>
</select>
<var name="message">Your document has been saved.</var>
<var
  name="first-name"
  model="my-model"
  context="instance('member')"
  value="first-name"/>
<var name="paging" value="instance('paging')"/>
<group>
  <var name="total"      value="$paging/@total"/>
  <var name="page-size"  value="$paging/@page-size"/>
  <var name="page-count" value="($total + $page-size - 1) idiv $page-size"/>
  <output value="$page-count" label="Number of pages"/>
</group>

6.5 The function Element

This element defines a custom function that can be called from any expression within the XForms document that is associated with the model in which the function is defined.

Common Attributes: Common

Special Attributes:

signature [not AVT]
The signature (name, parameters and return type) of the function.
override
Author-optional specifies if this function overrides previously declared functions. The default value is yes.
type
Author-optional specifies the implementation language of the function using a valid MIME type. When the attribute is omitted the expression language of the form is used. The supported languages depend on the XForms Processor. The function definition is ignored if the language is not supported by the XForms Processor or if the function element contains mixed content.

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 XPath 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).

6.5.1 Function signature syntax

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

CustomFunctionSignature  ::= FunctionName "(" ParamList? ")" ("as" SequenceType)?
FunctionName  ::= QNameButNoNCName
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

6.5.2 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.

6.5.3 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.

XPath expressions within the function body may refer to instance data through the instance() function.

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

6.5.4 The result element

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

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

Common Attributes: Common

Special Attributes:

value
Contains the expression which specifies the result of the function.

A static or dynamic XPath error occurring while evaluating the value attribute on the result element propagates to the expression calling the function.

7 Datatypes

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

7.1 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].

7.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. All of these types allow empty content.

7.2.1 Types Allowing Empty Content

Many default XML Schema types do not permit empty content, which would mean that XForms values that had not yet been filled in would be marked as invalid.

Therefore, the following XForms types are defined as having a lexical space identical to the corresponding XML Schema datatype, with the addition of the empty string. For consistency, XML Schema datatypes that do allow empty content have also been added.

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.

7.2.2 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.

7.2.3 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.

Note:

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

7.2.4 email type

This type represents an email address, as defined by [RFC 2822]. Internationalized email addresses are not restricted beyond the definition in the RFC. For simplicity, some extremely uncommon features of the RFC syntax are not allowed, such as "Obsolete Addressing" from section 4.4, square-bracketed "domain-literal"s, and insignificant whitespace and comments.

The type is defined as the following lexical space:

<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!#-'\*\+\-/=\?\^_`\{-~]+)*)?"/>
  </xs:restriction>
</xs:simpleType>
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.

7.2.5 card-number type

This type represents identity, debit and credit card numbers; it is a pattern restriction on xs:string to zero 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>

7.2.6 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.

7.3 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"/>

8 Controls

Controls allow interaction with instance data:

  • They are declared using elements and their related attributes.
  • They are bound to the underlying instance data using binding attributes.
  • They enable accessibility by taking a uniform approach to such features as labels, help text, navigation, and keyboard shortcuts. Internationalization issues are addressed by following the same design principles as in XHTML. All controls are suitable for styling as aural or visual media.
  • They encapsulate high-level semantics without sacrificing the ability to deliver real implementations. For instance, the select control enables the user to select items from a set. Such controls enable the expression of the intent of the control without prescribing a presentation of it — see [AUI97] for a definition of such high-level user interaction primitives.

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.

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.

8.1 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, Appearance, UI Common, Single Item Binding

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

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

Author-optional attribute to define an appearance hint. If absent, the user agent may freely choose any suitable rendering. The effect of this attribute is defined by each control that uses it.
inputmode
Author-optional attribute to give a hint about the sort of text that is expected by the control. See Input Modes for details.
incremental
Author-optional attribute that defines when instance data is updated by a control. Controls with bindings normally update the instance data when the control loses focus. When true, this attribute indicates that the control should update the instance data more often, thereby generating additional xforms-value-changed events. In incremental mode, an implementation may buffer sequences of changes happening in quick succession, and apply them all at once. The default value for this attribute is false. Although this attribute is available for all controls, in some cases there may be no perceivable difference between incremental and non-incremental mode.
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 specify values for labels, help, hint, and alert either via attributes, or via child elements. Unless otherwise stated, a control must have a label (either via an attribute or a child element). All the others are optional. If both an element and an attribute for the same thing are present, the attribute takes precedence. The effect of these attributes are described in the respective element descriptions.
xml:lang
Host languages should add this attribute to allow the specification of content languages.
class
Host languages should add this attribute, to hold a list of names that can be matched by CSS class selectors.

Further, 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
This author-optional attribute is a 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
This author-optional attribute defines a 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
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.

8.2 Common Support Elements

The child elements detailed below provide the ability to attach interaction text to many controls and other elements; all of them may either be specified 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.

The following table summarizes the common child elements for controls.

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

label

Common, Appearance, Single Item Binding (author-optional)

(PCDATA|(UI Content))*

help

Common, Appearance, Single Item Binding (author-optional)

(PCDATA|(UI Content))*

hint

Common, Appearance, Single Item Binding (author-optional)

(PCDATA|(UI Content))*

alert

Common, Appearance, Single Item Binding (author-optional)

(PCDATA|(UI Content))*

8.2.1 The label Element

This provides a descriptive label for the attached control.

Common Attributes: Common, Appearance, Single Item Binding (author-optional)

The label is obtained by evaluating the Single Item Binding if present, or otherwise from the inline text.

The label should be 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}"/>

8.2.2 The help Element

This author-optional information provides help information for a control.

Common Attributes: Common, Appearance, Linking, Single Item Binding (author-optional)

The help text is obtained by evaluating the Single Item Binding if present, or otherwise from the inline text.

Processors should choose an appropriate presentation for the help content, and should allow styling if the host language integration supports it.

If the host language integration supports Linking, the help link should be made available through an appropriate presentation mechanism. With appearance="minimal", the help link should be associated with the label.

With no host-language styling and no appearance specified, 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

8.2.3 The hint Element

This author-optional information provides hint information for a control.

Common Attributes: Common, Appearance, Single Item Binding (author-optional)

The hint text is obtained by evaluating the Single Item Binding if present, or otherwise from the inline text.

Processors should choose an appropriate presentation for the hint, and should allow styling if the host-language integration supports it. With no attribute appearance and no host-language styling, 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.

8.2.4 The alert Element

This author-optional information provides alert or error text for a control when its associated data is non-valid.

Common Attributes: Common, Appearance, Single Item Binding (author-optional)

The alert text is obtained by evaluating the Single Item Binding if present, or otherwise from the inline text.

When a control's associated data is invalid, the alert text must be made available to the user. Rendering of this element is implementation-defined, and there is no default level such as modal or ephemeral for the displayed message.

<instance>
   <data xmlns="">
      <number/>
   </data>
<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'

8.3 Implementation Requirements Common to All Controls

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

8.3.1 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 (see [XPath 1.0]).
  • All controls that read simpleContent instance data must do so as follows:
    • 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.
    • The XPath root node: an xforms-binding-error is dispatched to the control.
      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 non-relevant 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.

8.3.2 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 xforms-focus event.
  • Any control that is relevant, enabled, and not read-only is able to receive the focus.
  • 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.

8.3.3 Relevance

  • Controls are considered to be non-relevant if any of the following apply and relevant 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 non-relevant, it must receive the xforms-disabled event and any action handlers that are listening for events on the control must be disabled.
  • When a control becomes relevant, the action handlers that listen for events on the control must be re-enabled, the control updated to represent the current value(s) and model item properties of its bound instance data. The following events must be dispatched to the control: xforms-enabled, 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.

8.3.4 Rendering

  • All controls, including container controls, but excluding repeat items, should have an inline layout by default (e.g. for a host language that supports CSS, the default styling should be display:inline).
  • Repeat items should have a block layout by default (e.g. a CSS styling of display:block).
  • For controls that display a representation of the bound data, while this representation must directly correspond to the data, it is not required to match the lexical space value of the data, but should rather take into account the datatype of the value, appearance hints, and localization and internationalization issues such as representation of numbers and dates.
  • Relevant 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.
  • Relevant controls must distinguish rendering between valid and invalid states. This rendering should be user-stylable.
  • Relevant controls must indicate when the bound instance data contains a value or content that the control is not capable of rendering. This rendering should be user-stylable.
  • Rendering of 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.

9 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)

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*

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, Single Item Binding

EMPTY

mediatype (for upload)

Common, Single Item Binding

EMPTY

mediatype (for output)

Common, Single Item Binding, value (string Expression)

EMPTY

choices (for selection controls)

Common, label (xs:string)

label?, (List UI Common)+

item (for selection controls)

Common, UI Common, value (Expression)

(value | UI Common)*

value (for selection controls)

Common, Single Item Binding (author-optional), value (Expression)

PCDATA

itemset (for selection controls)

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

label, (value|copy), (UI Common)*

copy (for selection controls)

Common, Single Item Binding (author-optional)

EMPTY

9.1 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

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. 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).

9.2 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

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.

9.3 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

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.

Example:

<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.

9.4 The output Element

This control renders content based on instance data.

Common Attributes: Control Common, value

Most controls are required to have a label: on output it is optional; similarly most controls must have a single item binding: output must have a single item binding or a value attribute (or both).

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

Special Attributes:

mediatype
Author-optional string indicating the media type that should be used for rendering the output.

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

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.

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 media type changes.

Failure to render the content either initially or during subsequent re-rendering should result in a (non-fatal) xforms-output-error (see Section The xforms-refresh Event). 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. invalid or unsupported image format);
  • An unrecognized media type 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:"/>
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="xs:date"/>
...
<output ref="birthdate" label="Lexical:"/>
<output ref="birthdate" appearance="full" label="Full:"/>
<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 Minimal: 19/01/1998

9.4.1 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 media type to be used for output.

Common Attributes: Common, Single Item Binding, value

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"/>

9.5 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
Author-optional comma-separated list of suggested media types 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 media types, used to determine the possible sources of data to upload.

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...

9.5.1 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, Single Item Binding

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

Content: EMPTY

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>

9.5.2 The mediatype Element (for upload)

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

Common Attributes: Common, Single Item Binding

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

Content: EMPTY

9.6 The range Element

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

Common Attributes: Control Common, incremental

Special Attributes:

start
Author-optional attribute containing a 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
Author-optional attribute containing a 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
Author-optional attribute containing a 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.

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.

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

If the instance data value is outside the upper or lower bounds, this control must indicate an out-of-range condition.

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"/>

9.7 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

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

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.

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; after that it does nothing else. Event handlers in the body of the element can be used 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>

9.8 The submit Element

This control initiates a submission.

Common Attributes: Control Common

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

Special Attributes:

submission
Author-optional attribute containing a reference to a submission element. If this attribute is omitted, then the first submission in document order from the model associated with the in-scope evaluation context is used.

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 this control has no effect; otherwise the xforms-submit event 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 event.

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"/>

9.9 Selection Controls

9.9.1 The select Element

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

Common Attributes: Control Common, incremental

Special Attributes:

selection
Author-optional attribute indicating whether the selection is open or closed. Allowable values are "open" and "closed". Default is "closed".

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.

A selection control is "simple" or "complex": a simple selection only selects simpleContent values; a complex selection selects values consisting of complex types (with children nodes). If the control uses item elements to provide the list of values, or uses an itemset element with a value child or attribute, then it is a simple selection. If the control uses itemset with a copy child or attribute, then it is a complex selection.

A simple selection is 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 child or children of the select element are evaluated, each being a pair of a label and a value.

If one or more of the item values match the values of the instance data addressed by the binding attributes, all such item values are initially selected. If there is no match, no item values are initially selected.

If any of the instance values do not correspond to an item with a matching value:

  • for closed selections, the control must indicate an out-of-range condition. Whenever the control switches to or from being out-of-range, then xforms-out-of-range or xforms-in-range must be dispatched to the control.
  • for open selections, all such non-matching values must be retained.

The label for each pair must be made available to the user, with an indication of whether the related value is selected or not. Interaction with a label selects or deselects the related value. On selection, items receive the xforms-select event; on deselection, the xforms-deselect event. Any number of the values 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.

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 must remain deselected.

The selected values are stored in the location addressed by the binding attributes, for simple selections as a space separated list, for complex selections as copies of the subtrees of the selected values.

The content of the instance node bound to the selection control 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 is preserved. For 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.

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>

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 choices should be rendered at all times;
"compact": a fixed number of choices should be rendered, with scrolling facilities as needed;
"minimal": a minimum number of choices should be rendered, with a facility to temporarily render additional choices.

<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.

9.9.2 The select1 Element

This control is similar to the select control except that only a single value may be selected from the list of choices.

Common Attributes: Control Common, incremental

Special Attributes:

selection
Author-optional attribute indicating whether the selection is open or closed. Allowable values are "open" and "closed". Default is "closed".

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.

This control operates similarly to a select control except that interaction with a label of a non-selected value first deselects any value already selected, and then selects the new value.

The items from the child or children of the select1 element are evaluated, each being a pair of a label and a value.

If one of the item values matches the value of the instance data addressed by the binding attributes, that item value is initially selected. If there is no match, no item value is initially selected.

If the instance value is non-empty and does not correspond to an item with a matching value:

  • for closed selections the control must indicate an out-of-range condition. Whenever the control switches to or from being out-of-range, then xforms-out-of-range or xforms-in-range must be dispatched to the control.
  • for open selections, the non-matching value is retained.

The label for each pair must be made available to the user, with an indication of whether the related value is selected or not. Interaction with a label selects the related value after first deselecting any already-selected value. On selection, items receive the xforms-select event; on deselection, the xforms-deselect event.

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.

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.

The selected value is stored in the location addressed by the binding attributes, 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.

9.9.3 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

<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>

9.9.4 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, UI Common, value

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

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.

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

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

Common Attributes: Common, Single Item Binding (author-optional), value

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')"/>

9.9.5 The itemset Element

This element allows the specification of select and select1 controls, where the available choices are determined at run-time.

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

Special Attributes:

copy
Author-optional expression giving a value to be copied. Takes precedence over any copy child element.

The sequence that holds the available choices is specified via the Sequence Binding. Child elements/attributes label, value, and copy specify the calculated label and storage values.

For each item of the Sequence Binding, an associated item element is created.

XForms Actions appearing in the content of an itemset are created within each item element, and the in-scope evaluation context for these XForms Actions is based on the data item for which the item was generated as described in Section 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 ref 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 type="v"><description>Vanilla</description></flavor>
      <flavor type="s"><description>Strawberry</description></flavor>
      <flavor type="c"><description>Chocolate</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</description>
   </order>
</icecream>
9.9.5.1 The copy Element (for itemset)

This element is similar to the value element, except that it can only be used within itemset, and that it works with subtrees of instance data rather than simple values.

Common Attributes: Common, Single Item Binding (author-optional)

When a copy node is selected, the following rules apply:

  • The target node, selected by the binding attributes on the selection control, must be an element node, otherwise an xforms-binding-error event is dispatched to the selection element.
  • The element node associated with the item, selected by the binding attributes on copy, is deep copied as a child of the target node using an insert action.
  • A full computational dependency rebuild is done, followed by recalculate, revalidate, and refresh.

When a copy item is deselected, the following rules apply:

  • The target node, selected by the binding attributes on the selection control, must be an element node, otherwise an xforms-binding-error event is dispatched to the copy element.
  • The child element node associated with the item, selected by the binding attributes on copy, is deleted using a delete action.
  • A full computational dependency rebuild is done, followed by recalculate, revalidate, and refresh.

Note:

If the target node of the select or select1 is readonly, then the insertion or deletion associated with the copy operation is not performed.

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

10 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

(Controls|UI Common)*

switch

Common, Appearance, Single Item Binding (author-optional)

case+

case

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

(Controls|UI Common)*

toggle

Common, Events, Action Common, case (xs:IDREF)

case?
dialog Common, Appearance, UI Common, level?, hide(xs:boolean) (Controls|UI Common)*
show Common, Events, Action Common, dialog(xs:IDREF) EMPTY
hide Common, Events, Action Common, dialog(xs:IDREF) EMPTY

repeat

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

(Controls|Action)*

setindex

Common, Events, Action Common, repeat (xs:IDREF), index (number Expression)

EMPTY
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

10.1 The group Element

This control aggregates other controls into a single user interface component, and sets the context for the enclosed controls. Groups can be nested to create complex hierarchies. The author-optional label represents a label for the entire group.

Common Attributes: Common, Appearance, Single Item Binding (author-optional)

If a group element is bound to a node, 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 non-relevant, then so is 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>

10.2 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, Appearance, Single Item Binding (author-optional)

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 non-relevant, 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.

10.2.1 The case Element

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

Common Attributes: Common, UI Common

Special Attributes:

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

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 relevant (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 non-relevant.

10.3 The dialog Element

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

Common Attributes: Common, Appearance, UI Common

Special Attributes:

level
Author-optional attribute, containing a dialog level identifier, one of ("modeless"|"modal"|QNameButNotNCName). The default is "modal" if the attribute is not specified. This specification does not define behavior for QNameButNotNCName values.
hide
Author-optional, 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.

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 relevant, when the dialog is hidden the implicit group is non-relevant.

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

10.3.1 The show Element

This action shows a specified dialog.

Common Attributes: Common, Events, Action Common

Special Attributes:

dialog
Required reference to a dialog element.

A deferred update is done.

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.

10.3.2 The hide Element

This action hides a specified dialog.

Common Attributes: Common, Events, Action Common

Special Attributes:

dialog
Required reference to a dialog element.

A deferred update is done.

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.

10.3.3 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

10.3.4 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

10.3.5 The xforms-dialog-shown Event

Dispatched in response to a dialog being shown.

Target:dialog

Bubbles: Yes

Cancelable: No

Context Info: none

The default action for this event results in the following: None; notification event only.

10.3.6 The xforms-dialog-hidden Event

Dispatched in response to a dialog being hidden.

Target: dialog

Bubbles: Yes

Cancelable: No

Context Info: none

The default action for this event results in the following: None; notification event only.

10.4 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, Appearance, Sequence Binding

Special Attributes:

indexref
Author-optional Single Item Binding to simpleContent, with which the repeat index is synchronized.
startindex
Author-optional 1-based initial value of the repeat index. The default value is 1. This attribute is ignored if indexref is specified.
number
Author-optional hint of how many elements of the repeat collection to display.

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,
  • its position in the repeat collection called the repeat position, 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">
  <output ref="."/><html:br/>
</repeat>

is conceptually similar to

<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>

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.

10.4.1 Repeat Processing

10.4.1.1 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.
10.4.1.2 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.

10.4.1.3 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 repeat 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.

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.

10.4.1.4 Interaction and rendering

Repeat items should have a block layout by default (e.g. a CSS styling of display:block). This can be overridden 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 repeat 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 non-relevant.

10.4.1.5 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>
10.4.1.6 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>

10.4.2 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="..."/></td>
  </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>
      <tr>
         <th>Country</th>
         <th>Capital</th>
      </tr>
   </thead>
   <tbody xforms:repeat-ref="countries/country">
      <tr>
         <td><xforms:output ref="."/></td>
         <td><xforms:output ref="@capital"/></td>
      </tr>
   </tbody>
</table>

11 Submission

Submitting data happens as a response to the xforms-submit event being received by the submission element.

In brief: the data to be submitted is identified, checked for validity, 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 necessary.

11.1 The submission Element

The attributes of submission can be divided into three groups: those that describe what is to be submitted, those that describe how it is to be submitted, and those the describe what to do with the result.

Element Overview of Attributes and Their Content (after AVT evaluation) Overview of Content Model
submission

Common
ref (Single Item Binding)
bind (xs:IDREF) [not AVT]
relevant (xs:boolean)
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|QNameButNotNCName)
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)

replace ("all"|"instance"|"text"|"none" | QNameButNotNCName)
instance (xs:IDREF)
targetref (Single Item Binding)
target ("_self" | "_blank" | xs:string)

(resource [deprecated] | method [deprecated] | header)*, Action*

Below is a more detailed description of each attribute.

Common Attributes: Common

Special Attributes:

What to submit:

ref
Author-optional Single Item Binding defining the data to be submitted. The node and all its descendants are selected. The default value is "/".
bind
Author-optional reference to a bind element. This attribute takes precedence over the ref attribute.
relevant
Author-optional boolean indicating whether relevance pruning of the data is performed. The default value is "false" if the value of serialization is "none" and "true" otherwise.
validate
Author-optional boolean indicating whether data validation is performed. The default value 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]
Author-optional URI indicating the destination for the submission. Use resource for preference.
mode
Author-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
Author-optional string specifying the protocol method to be used to transmit the submission, with a default of "get". See Section Submission Options for information on how this attribute affects the default serialization of instance data and the HTTP method [RFC 2616].
serialization
Author-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 Options. 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.
Note: A serialization of "none" will also prevent relevance pruning and validation unless the relevant and/or validate attributes are set to "true".
mediatype
Author-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 2119]. 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
Author-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
Author-optional string specifying the separator character between name/value pairs in urlencoding, if the value of the serialization attribute 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
Author-optional string specifying the version of XML to be serialized. The default is "1.0".
indent
Author-optional boolean specifying whether the serializer should add extra white space nodes for readability. The default is "false".
omit-xml-declaration
Author-optional boolean specifying whether to omit the XML declaration on the serialized instance data. The default value is "false".
standalone
Author-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
Author-optional string specifying element names to be serialized with CDATA sections. The default is empty string.
includenamespaceprefixes
Author-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:

replace
Author-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
Author-optional string specifying the instance to replace when the replace attribute value is "instance". When the attribute is absent, then the default is the instance that contains the submission data. When the replace value is not "instance", this attribute is ignored.
targetref
Author-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
Author-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.

The table below provides an overview of the child elements of the XForms submission element, including their attributes and content models. Elements defined in the XForms Actions module are also allowed in the content model of submission.

Element Overview of Attributes and Their Content (after AVT evaluation) Overview of Content Model
resource (deprecated) value (string Expression) PCDATA
method (deprecated) value (string Expression) PCDATA
header ref (node-sequence Expression), nodeset (node-sequence Expression, deprecated), name (xs:string), value (string Expression) name, value+

Action

various various
<submission
   resource="http://example.com/search"/>

 <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}"
   replace="instance"
   instance="iresults"
   serialization="none"
   mode="synchronous"
   mediatype="application/json"/>

11.2 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, 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"/>
</div>

11.3 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, 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.

11.4 The header Element

The header element can be used to change headers, or add extra headers to a submission protocol.

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.

Common Attributes: Common, Sequence Binding, value

Special Attributes:

name
Author-optional string that overrides the name child element if present.
combine
Author-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: (name, value+) | (value+, name)

  • 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 there must be one or more value child elements, and one header is produced per value child 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
     combine="replace"
     name="Accept"
     value="'application/sparql-results+xml'"/>
 </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

11.4.1 The name Element

Specifies the name of a header entry to be provided to the submission protocol.

Common Attributes: Common, value

If the model attribute is present and does not identify the containing model, an xforms-binding-error is dispatched.

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"/

11.4.2 The value Element (for header)

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, value

If the model attribute is present and does not identify the containing model, an xforms-binding-error is dispatched.

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.

11.5 Submission Processing

For brevity in the following, the text "submission succeeds" means "submission processing concludes after dispatching xforms-submit-done with appropriate context information", and the text "submission fails with error-code" means "the submission processing concludes after dispatching xforms-submit-error 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.

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 an error-code of submission-in-progress.

11.5.1 Preparing the Data

The data model is updated based on its deferred update flags:

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.

The evaluated node and all nodes for which it is an ancestor are selected. If the attribute relevant is true, whether by default or declaration, then any selected node which is not relevant as defined in The relevant Property is deselected (pruned). If all instance nodes are deselected, then submission fails with no-relevant-data.

If the attribute validate is true, whether by default or declaration, then all selected instance data nodes are checked for validity as in model revalidate (no notification events are marked for dispatch due to this operation). If any instance data node is found to be invalid, submission fails with validation-error.

11.5.2 Submitting 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 action attribute if present, and otherwise from the first resource child element, if any; otherwise submission fails with resource-error.

The serialized data is obtained:

  • If the serialization attribute value is "none", then the empty string is used.
  • Otherwise, the event xforms-submit-serialize is dispatched; if the submission-body property of the event is changed from the initial value of empty string, then its content is used.
  • Otherwise, the selected instance data is serialized according to the rules stated in Serialization.

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. The exact rules of submission are based on the URI scheme and the submission method, as defined in Submission Options.

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.

11.5.3 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 body is not of a type accepted by the processor, as specified in Creating instance data from external resources, nothing in the document is replaced and submission fails with result-media-type, and an error-message of the unacceptable media type. 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 body is neither an XML media type (i.e. with a content type not matching any of the specifiers in [RFC 3023]) 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-media-type, and an error-message of the unacceptable media type. 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.

11.5.4 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 treated as text, regardless of its media type, 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.

If the submission has a mode of "asynchronous", then the text replacement action or the instance node replacement action is an outermost action handler, so a deferred update occurs at the end of the action. If the mode is "synchronous", then the text replacement action or the instance node replacement action is not outermost since it occurs during the default processing of xforms-submit, so the appropriate deferred update flags are set based on whether the action was a setvalue or whether it performed a series of insert and delete actions.

Note:

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 deferred update behavior ensures that the user interface is up to date with the latest calculated values before the xforms-submit-done event is dispatched. In a synchronous submission, the calculated values dependent on replaced text or data nodes can be made available to actions in the xforms-submit-done handler by first invoking the recalculate action. A sequence of synchronous submissions performed with successive send actions can avoid refreshing the user interface until after the completion of the last send action.

<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.

11.5.5 Submission Options

How instance data is submitted depends on two aspects: the submission method, which determines the default data serialization format, and the URI scheme in the submission resource which determines the submission protocol:

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" multipart/related HTTP POST or equivalent
http https mailto "form-data-post" multipart/form-data HTTP POST or equivalent
http https mailto "urlencoded-post" application/x-www-form-urlencoded HTTP POST or equivalent
(any)

Any other NCName

application/xml

As given by the Submission Method

(any)

QNameButNotNCName

implementation-defined implementation-defined

Processors must support HTTP/1.1 [RFC 2616], and HTTPS [RFC 2818]; "file:" should be supported, and "mailto:" may be supported.

Note: With the "http:" and "https:" schemes, authors are encouraged to follow the finding of the W3C Technical Architecture Group on when to use the GET method: [TAG Finding 7]

Note: Foreign-namespaced attribute values are allowed in the Submission Method, but no behavior is defined for them.

11.5.6 Submission Methods

11.5.6.1 The get Submission Method

This submit method represents HTTP GET or the equivalent concept. The serialized form data is delivered as part of the URI that is used during the submit process.

This method is not suitable for submission of data intended to change state or cause other actions at the server. See [RFC 2616] for recommended uses of HTTP GET.

The URI is constructed as follows:

  • If the submission resource URI does not already contain a ? (question mark) character, one is appended; otherwise, if the serialized form data is non-empty, a separator character from the attribute separator is appended.
  • The submission data, if any, is appended to the URI serialized as application/x-www-form-urlencoded.

No message body is sent with the request.

<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="file:data.xml"
  method="get"
  serialization="none"
  replace="instance"
  instance="data"/>

Replaces the instance 'data' with the content of the file data.xml. Serialization, and its associated validity and relevance processing, is not needed. See the corresponding example for saving a file in Section The put Submission Method. The user agent may restrict file access to a user-specific and domain-specific security zone in local storage.

11.5.6.2 The post, multipart-post, form-data-post, and urlencoded-post Submission Methods

These submit methods represent HTTP POST or the equivalent concept (such as a mail message). The serialized form data is delivered as the message body.

<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.

11.5.6.3 The put Submission Method

This submit method represents HTTP PUT or the equivalent concept (such as writing to a local file). The serialized form data is delivered as the message body.

<submission
  resource="file:data.xml"
  ref="instance('data')"
  method="put"
  validate="false"
  relevant="false"
  replace="none"/>

Saves the instance 'data' to the file data.xml without validation checking and relevance pruning. See the corresponding example for reading from a local file in Section The get Submission Method. The user agent may restrict file access to a user-specific and domain-specific security zone in local storage.

11.5.6.4 The delete Submission Method

This submit method represents HTTP DELETE or the equivalent concept (such as deleting a local file). The serialized form data is delivered in the same manner as the get submission method (see The get Submission Method).

11.5.7 Serialization

11.5.7.1 Serialization as 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.

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 serialization parameters 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>

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.

11.5.7.2 Serialization as 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--
11.5.7.3 Serialization as multipart/form-data

This format is for legacy compatibility to permit the use of XForms clients with [RFC 2388] servers. This method is suitable for the persistence of binary content. Contextual path information, attribute values, namespaces and namespace prefixes are not preserved. As a result, different elements might serialize to the same name.

Note:

Existing HTML user agents fail to encode special characters (such as double quotes) and non-ASCII characters in the Content-Disposition: form-data name and filename parameters. Since this serialization method is supported for legacy applications only, new applications should use application/xml or multipart/related.

This format follows the rules for multipart/form-data MIME data streams in [RFC 2388], with specific requirements of this serialization listed below:

  • Each element node is visited in document order, except non-relevant elements are skipped if the relevant setting of the submission is true.
  • 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 media type of the attachment if known, otherwise application/octet-stream. If a character set is applicable, the Content-Type may have a charset parameter.

Example:

<submission
  method="form-data-post"
  resource="http://example.com/photo"/>

Submits the instance data in multipart/form-data, along with the selected file as a part.

POST /photo HTTP/1.0
Host: example.com
Content-Type: multipart/form-data; boundary=AaB03x
Content-Length: xxx

--AaB03x
Content-Disposition: form-data; name="document"; filename="b.txt"
Content-Type: text/plain; charset=iso-8859-1
This is a file.
It has two lines.
--AaB03x
Content-Disposition: form-data; name="title"
A File
--AaB03x
Content-Disposition: form-data; name="summary"
This is my file
file test
--AaB03x--
11.5.7.4 Serialization as 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, except non-relevant elements if the relevant setting of submission is true. 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.

11.5.7.5 Serialization as JSON and 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.

11.6 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.

11.7 The xforms-submit-serialize Event

Dispatched at the beginning of submission serialization (see Submission Processing).

Target: submission Bubbles: Yes Cancelable: No

Context Info:

Property Type Value
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.

11.8 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:

Property Type Value
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/getRecord" method="post" 
            replace="instance" instance="record">
    <send ev:event="xforms-submit-done" submission="chargeForRecord"/>
</submission>
<submission id="chargeForRecord" resource="https://example.com/chargeForRecord" method="get"
            serialization="none" replace="none"/>

The default instance data is submitted as the search criteria for a desired record. Only upon successful completion of the submission is a second submission performed to charge the user's account for the record.

11.9 The xforms-submit-error Event

This notification event is dispatched on failure of a submission process.

Target: submission Bubbles: Yes Cancelable: No

Context Info:

Property Type Value
error-type string One of the following: submission-in-progress, no-data, no-relevant-data, validation-error, parse-error, resource-error, result-media-type, result-text-media-type, 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 media type as defined by [RFC 3023], the response body is parsed into an XML document and the root element of the document is returned. If the parse fails, or if the error response specifies a text media type (starting with text/), then the response body is returned as a string. Otherwise, an empty string is returned.

<submission resource="https://example.com/getRecord" method="post"
            replace="instance" instance="record">
  <message ev:event="xforms-submit-error">A submission error 
                   (<output value="event('error-type')"/>) occurred.</message>
</submission>

12 Processing

XForms processing is defined largely in terms of events, event handlers, and event responses: in general whenever there is a change of state, events are dispatched to parts of the document affected by the change. Event listeners are then able to respond as needed.

Events are classified in the following categories:

  • Initialization
  • Interaction
  • Notification
  • Error Conditions.

After the initialization events have occurred, 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.

12.1 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].

12.1.1 For Initialization

These may cause a number of xforms-link-error and xforms-compute-error.
These may cause a number of xforms-binding-error.

12.1.2 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.

12.1.3 For output Controls

  • The implementation of an output dispatches xforms-output-error if it 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).

12.1.4 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.

12.1.5 For trigger Controls

12.1.6 For submit Controls

12.1.7 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)

12.1.8 Sequence: Value Change

  1. xforms-recalculate
  2. xforms-revalidate
  3. xforms-refresh performs reevaluation of UI binding expressions then dispatches these events according to value changes, model item property changes and validity changes:
    • [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

      (The order in which these events are dispatched is not defined).
  4. Perform further deferred updates as necessary

12.1.9 Sequence: Activating a Trigger

  1. DOMActivate

12.1.10 Sequence: Submission

  1. xforms-submit
  2. xforms-submit-serialize
  3. xforms-submit-done or xforms-submit-error

12.2 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.

12.2.1 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.

12.2.2 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 produced a null search result.

12.3 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();
    };
 };

12.3.1 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 of a node whose parent is readonly, direct deletion 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.

12.3.2 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.

12.3.3 The recalculate() Method

This method performs a full recalculation of this Model. This method takes no parameters and raises no exceptions.

12.3.4 The revalidate() Method

This method performs a full revalidation of this Model. This method takes no parameters and raises no exceptions.

12.3.5 The refresh() Method

This method performs a full refresh of the user interface based on instance nodes within this Model. This method takes no parameters and raises no exceptions.

12.4 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".

13 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 listener 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 Not Bubbles Notification None model
xforms-model-destruct Not Bubbles Notification None model

Interaction Events

xforms-rebuild Cancelable Bubbles Effect None model rebuild
xforms-recalculate Cancelable Bubbles Effect None model recalculate
xforms-revalidate Cancelable Bubbles Effect None model revalidate
xforms-refresh Cancelable Bubbles Effect None model refresh
xforms-reset Cancelable Bubbles Effect None model reset
xforms-previous Cancelable Doesn't Effect None Core Controls
xforms-next Cancelable Doesn't Effect None Core Controls
xforms-focus Cancelable Doesn't Effect None Controls setfocus
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 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 Not Bubbles Notification Context instance
xforms-delete Not Bubbles Notification Context instance
xforms-value-changed Not Bubbles Notification None Core Controls
xforms-valid Not Bubbles Notification None Core Controls|group|switch
xforms-invalid Not Bubbles Notification None Core Controls|group|switch
xforms-readonly Not Bubbles Notification None Core Controls|group|switch
xforms-readwrite Not Bubbles Notification None Core Controls|group|switch
xforms-required Not Bubbles Notification None Core Controls|group|switch
xforms-optional Not Bubbles Notification None Core Controls|group|switch
xforms-enabled Not Bubbles Notification None Core Controls|group|switch
xforms-disabled Not Bubbles Notification None Core Controls|group|switch
DOMFocusIn Not Bubbles Notification None Controls
DOMFocusOut Not Bubbles Notification None Controls
xforms-select Not Bubbles Notification None item or case
xforms-deselect Not Bubbles Notification None item or case
xforms-in-range Not Bubbles Notification None Core Controls
xforms-out-of-range Not Bubbles Notification None Core Controls
xforms-scroll-first Not Bubbles Notification None repeat
xforms-scroll-last Not Bubbles Notification None repeat
xforms-submit-done Not Bubbles Notification Context submission
xforms-dialog-shown Not Bubbles Notification None dialog
xforms-dialog-hidden Not 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-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 Not Bubbles Notification Context output
xforms-submit-error Not Bubbles Notification Context submission

13.1 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.

13.1.1 The xforms-model-construct Event

Dispatched to each XForms model.

Target: model Bubbles: Yes Cancelable: No Context Info: None

Default action: a model initialization is done for the model.

13.1.2 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.

13.1.3 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

13.1.4 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

13.2 Interaction Events

13.2.1 The xforms-rebuild Event

Dispatched to recompute the computational dependencies within a Model.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

Default action: a rebuild is done for the model.

13.2.2 The xforms-recalculate Event

Dispatched to recalculate all calculations associated with a Model.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

Default action: a recalculate is done for the model.

13.2.3 The xforms-revalidate Event

Dispatched to revalidate a Model.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

The default action: a revalidate is done for the model.

13.2.4 The xforms-refresh Event

Dispatched to update all controls associated with a Model.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

Default action: a refresh is done for the model.

13.2.5 The xforms-reset Event

Dispatched to reset a model back to its original values.

Target: model Bubbles: Yes Cancelable: Yes Context Info: None

Default action: a reset is done for the model.

13.2.6 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

The default action for this event varies according to the control it is used on.

13.2.7 The xforms-next and xforms-previous Events

Dispatched to navigate to the next or previous Core Control.

Target: Core Controls Bubbles: No Cancelable: Yes Context Info: None

Default action:

The host language is responsible for defining overall navigation order. This action causes focus to be given to the next/previous control in that navigation order.

In the absence of any host-language-defined ordering, focus is given to the next/previous control (including container controls) in document order that is capable of receiving the focus, as if by a setfocus action.

Controls that are disabled, hidden, readonly, or not relevant do not participate as navigable controls.

The navigation sequence past the last control (or before the first) is undefined. Processors may cycle back to the first/last control, remove focus altogether, or other possibilities.

<repeat ref="entry">
   <input ref="." incremental="true" id="here" label="4 chars:">
       <dispatch
           ev:event="xforms-value-changed"
           name="xforms-next"
           targetid="here"
           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 will automatically be 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.

13.2.8 The xforms-focus Event

Dispatched to set focus to a control.

Target: Controls Bubbles: No Cancelable: Yes Context Info: None

Default action:

If the target control is able to accept focus, it is given 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.

13.2.9 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.

13.2.10 The xforms-submit Event

See chapter The xforms-submit Event.

13.2.11 The xforms-submit-serialize Event

See chapter The xforms-submit-serialize Event.

13.2.12 The xforms-dialog-show Event

See chapter The xforms-dialog-show Event.

13.2.13 The xforms-dialog-hide Event

See chapter The xforms-dialog-hide Event.

13.3 Notification Events

Notifications events have no default action, and are therefore not cancelable.

13.3.1 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:

Property Type Value
inserted-nodes node-sequence The instance data node or nodes inserted.
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.

13.3.2 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:

Property Type Value
deleted-nodes node-sequence The instance data node or nodes deleted. Note that these nodes are no longer referenced by their parents.
delete-location number The delete location as defined by the delete action, or NaN if there is no delete location.

13.3.3 The xforms-value-changed Event

This notification event is dispatched during the xforms-refresh event 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.).

13.3.4 The xforms-valid and xforms-invalid Events

These notification events are dispatched when an 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

These events are dispatched during the xforms-refresh event if the bound instance data node has been marked for dispatching the event by the xforms-revalidate event.

13.3.5 The xforms-readonly and xforms-readwrite Events

These notification events are dispatched when an 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

These events are dispatched during the xforms-refresh event if the bound instance data node has been marked for dispatching the event in the xforms-recalculate event or the xforms-refresh event.

13.3.6 The xforms-required and xforms-optional Events

These notification events are dispatched when an 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

These event are dispatched during the xforms-refresh event if the bound instance data node has been marked for dispatching the event in the xforms-recalculate event or the xforms-refresh event.

13.3.7 The xforms-enabled and xforms-disabled Events

These notification events are dispatched when an 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

These events are dispatched during the xforms-refresh event if the bound instance data node has been marked for dispatching the event in the xforms-recalculate event or the xforms-refresh event.

13.3.8 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

13.3.9 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

13.3.10 The xforms-in-range and xforms-out-of-range Events

These notification events are dispatched when a value has changed such that it can now be represented by the control/not represented by the control.

Target: Core Controls Bubbles: Yes Cancelable: No Context Info: None

13.3.11 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

13.3.12 The xforms-submit-done Event

See chapter The xforms-submit-done Event.

13.3.13 The xforms-dialog-shown Event

See chapter The xforms-dialog-shown Event.

13.3.14 The xforms-dialog-hidden Event

See chapter The xforms-dialog-hidden Event.

13.4 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 error events is to halt processing, but handlers for error events can use defaultAction="cancel" to implement custom error handling and stop the default action, allowing processing to continue.

<action ev:event="xforms-expression-error" ev:defaultAction="cancel">
  <!-- Custom error handling here -->
</action>

13.4.1 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

13.4.2 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 event is 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
  • dispatch, send, setfocus, setindex, and toggle when the target element is not found

13.4.3 The xforms-binding-error Event

Dispatched as an indication of any error with a binding not within an action handler, including:

  • 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

Target: any element that can contain a binding expression Bubbles: Yes Cancelable: Yes

Context Info:

Property Type Value
error-message string Optional implementation-dependent error message, or the empty sequence.

Default Action: Fatal error (halts processing).

Note:

Binding errors occurring within action handlers dispatch the xforms-action-error event instead.

13.4.4 The xforms-expression-error Event

Dispatched as an indication of any error occurring during evaluation of an expression not within an action handler, except for binding expressions, including for:

  • a bind computed expression
  • a value attribute on output and var

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:

Property Type Value
error-message string Optional implementation-dependent error message, or the empty sequence.

Default Action: Fatal error (halts processing).

Note:

Expression errors occurring within action handlers dispatch the xforms-action-error event instead.

13.4.5 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:

Property Type Value
error-type string One of the following: expression-error, binding-error, script-error, script-language-error, other-error.
error-message string Optional implementation-dependent error message, or the empty sequence.

Default Action: Fatal error (halts processing).

13.4.6 The xforms-compute-error Event

Dispatched as an indication of: an error occurring with computing expressions, including if:

  • an extension function is declared on the functions attribute but is not implemented by the XForms Processor
  • a circular dependency is detected during xforms-recalculate processing
  • a computed expression violates a Binding Expression Constraint during xforms-recalculate processing

Target: model

Bubbles: Yes

Cancelable: Yes

Context Info:

Property Type Value
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).

13.4.7 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:

Property Type Value
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.

13.4.8 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:

Property Type Value
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.

13.4.9 The xforms-output-error Event

Dispatched by the processor immediately after the failure of an output to render or update the rendition of content.

Target: output

Bubbles: Yes

Cancelable: No

Context Info: None.

Default Action: None; notification event only.

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.

13.4.10 The xforms-submit-error Event

See chapter The xforms-submit-error Event.

14 Actions

Actions allow change of state not based directly on user interaction. By listening to events on different elements, actions can be used to react to those events.

This chapter defines the controller layer of XForms, an XML Events-based [XML Events] common set of actions that can be invoked in response to events.

XForms Actions are declarative XML event handlers that capture high-level semantics. As a consequence, they significantly enhance the accessibility of XForms-based applications in comparison to previous Web technologies that relied exclusively on scripting.

The elements and attributes included in this module are:

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

action

Common, Events, Action Common, type (xs:string), src (xs:anyURI), charset (xs:string)

(Action|var)*

setvalue

Common, Events, Action Common, Single Item Binding, value (string Expression)

PCDATA

insert

Common, Events, Action Common, Sequence Binding, context (node Expression), at (number Expression), position ("before"|"after"), origin (node-sequence Expression)

EMPTY

delete

Common, Events, Action Common, Sequence Binding, context (node Expression), at (number Expression)

EMPTY

setindex

Common, Events, Action Common, repeat (xs:IDREF), index (number Expression)

EMPTY

toggle

Common, Events, Action Common, case (xs:IDREF)

case? [deprecated]

setfocus

Common, Events, Action Common, control (xs:IDREF)

control? [deprecated]

dispatch

Common, Events, Action Common, name (xs:NMTOKEN), targetid (xs:IDREF), delay (xs:nonNegativeInteger), bubbles (xs:boolean), cancelable (xs:boolean)

name? [deprecated], targetid? [deprecated], delay? [deprecated] [in any order]

rebuild

Common, Events, Action Common

EMPTY

recalculate

Common, Events, Action Common

EMPTY

revalidate

Common, Events, Action Common

EMPTY

refresh

Common, Events, Action Common

EMPTY

reset

Common, Events, Action Common

EMPTY

load

Common, Events, Action Common, Single Item Binding (author-optional), resource (xs:anyURI), show ("new" | "replace")

resource? [deprecated]

send

Common, Events, Action Common, submission (xs:IDREF)

EMPTY

message

Common, Events, Action Common, Single Item Binding (author-optional), level ("ephemeral" | "modeless" | "modal"|QNameButNotNCName)

(PCDATA|UI Inline)*

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|refresh|reset|
 load|send|message)*
<trigger 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.

14.1 Common Attributes for Actions

The following attributes are available to all Action elements.

Action Common

Element Attributes and Their Content (after AVT evaluation)

Action

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
Author-optional attribute defined in Section Conditional Execution of XForms Actions.
while
Author-optional attribute defined in Section The While Attribute.
iterate
Author-optional attribute defined 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].

14.2 Deferred Updates

Actions have a deferred effect on processing: instance data changes performed by actions do not result in immediate computation dependency rebuilding, recalculation, revalidation and control refreshing until the termination of the outermost action handler. Implementations are free to use any strategy to accomplish deferred updates, but the end result must be the same.

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.

Each model can be thought of as having a set of deferred update flags, initially cleared at the start of an outermost action handler, to indicate whether each of the actions rebuild, recalculate, revalidate, and refresh are required for that model upon termination of the outermost action handler.

Execution of an outermost action handler begins by setting the Processor into the state of executing an outermost action handler. The outermost action handler is then performed, which may include the execution of inner action handlers. Finally, the Processor is set into the state of not executing an outermost action handler and then the deferred update is performed for each model.

A deferred update for a model consists of examining each deferred update flag in the order of rebuild, recalculate, revalidate, and refresh, and for each that is set, clearing it and dispatching the appropriate event to the model (i.e. dispatch xforms-rebuild for a rebuild flag, and so on).

Note:

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

Actions that manipulate properties of the view layer begin by doing a deferred update so that the model and all data are up-to-date prior to performing the action. These are setfocus, toggle, and setindex.

Actions that directly invoke rebuild, recalculate, revalidate, or refresh always have an immediate effect, and clear the corresponding flag. These are: rebuild, recalculate, revalidate, and refresh. Similarly, if the default processing of any of the events xforms-rebuild, xforms-recalculate, xforms-revalidate, or xforms-refresh are performed, then the corresponding flag is cleared. The Actions that can dispatch these events are reset, and dispatch.

Actions that change the structure of instance data result in setting all flags. These are: insert, and delete.

Actions that change only the value of an instance node result in setting the flags for recalculate, revalidate, and refresh and making no change to the flag for rebuild. These are: setvalue, and setindex.

Finally, the submission process can affect deferred update behavior. See the xforms-submit event for details. Actions that are capable of initiating a submission are send, and dispatch.

14.3 The action Element

This is a container for other actions.

Common Attributes: Common, Events, Action Common

Special Attributes:

type
Author-optional string specifying the language of the script. It must be a valid MIME type.

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 error-type set to script-language-error 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 error-type set to 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>

14.3.1 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, value

Special Attributes:

name
Required attribute containing the name of the parameter to pass to the script.

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.

14.3.2 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.

<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>

14.4 The setvalue Element

This action sets the value of an instance data node.

Common Attributes: Common, Events, Action Common, Single Item Binding, value

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 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 occurs.

This action affects deferred updates by setting the deferred update flags for recalculate, revalidate and refresh.

Note:

Expression language modules are encouraged to add a context() function that returns the in-scope evaluation context item, which 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"/>

14.5 The insert Element

This action inserts items into a sequence.

Common Attributes: Common, Events, Action Common, Sequence Binding (author-optional)

Special Attributes:

origin
Author-optional expression giving a sequence of nodes to be cloned.
at
Author-optional number expression giving a position in the target sequence where items are to be inserted.
position
Author-optional selector that indicates where to put the inserted nodes relative to the insert position. Valid values are before and after, with after as the default.

Processing:

The target-sequence is determined by evaluating the Sequence Binding, if present, and otherwise from the in-scope evaluation context. The insert action has no effect if the target-sequence is empty.

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 origin-sequence is empty, the insert action has no effect.

The insert index is determined:

  • if the at attribute is not given, the size of the target-sequence is used; 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 target-sequence size, or less than 1, the insert action has no effect.

The insert location node is determined:

  • if the target-sequence is empty, the insert context node 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.

Each node in the origin-sequence is cloned in the order it appears in the sequence.

The target location is determined for each cloned node:

  • if the target-sequence is non-empty, then the insert location node will be the sibling of the cloned 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 insert location node will be the parent of the cloned 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 cloned node is an element, then the target location is the root element of the instance;
      • if the cloned node is not an element, then the target location is before the first child of the insert location node;
    • an element:
      • if the cloned node is an attribute, then the target location is the attribute list of the element;
      • if the cloned 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 cloned node, so:) the target location is undefined.

If the target location is undefined, or there is a node type conflict between the cloned node and the target location (for example, an attribute cannot be inserted as a sibling of an element), the insertion for that cloned node is ignored.

The cloned 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 cloned node is an element, then the instance root element is deleted before the cloned node is inserted at the target location;
  • if the cloned node is a duplicate of another attribute in its parent element, then either the duplicate attribute is first removed or the existing attribute value is updated;
  • otherwise the cloned node is inserted into its target location depending on node type.

Each cloned node that is inserted is added to an inserted-nodes list that is provided in the xforms-insert event context information. Each cloned 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 deferred update flags for rebuild, recalculate, revalidate and refresh are set.

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.
<instance>
  <data xmlns="">
    <list><a>1</a><a>2</a><a>3</a></list>
  </data>
</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>
  </data>
</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>
  <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>
    </data>
  </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.

14.6 The delete Element

This action deletes one or more nodes from instance data.

Common Attributes: Common, Events, Action Common, Sequence Binding

Special Attributes:

at
Author-optional number expression giving the position in the target sequence where an item is to be deleted.

Processing:

The target-sequence is determined by evaluating the Sequence Binding, if present, and otherwise from the in-scope evaluation context. The insert 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 node in the target-sequence is treated, otherwise only the item at the delete index in the target-sequence is treated.

Nodes are treated as follows:

  • if the node is a readonly node, a root node, the root document element of an instance, or an atomic value, it is ignored;
  • 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.

The deferred update flags for rebuild, recalculate, revalidate and refresh are set.

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 by the XPath processor 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 (if you are using XPath as an expression language the parent axes of the delete node will return the empty sequence)

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.

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.

See Appendix Patterns for Data Mutations for numerous further usage patterns for setvalue, insert and delete.

14.7 The setindex Element

This action sets the repeat index of a repeat control.

Common Attributes: Common, Events, 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.

This Action begins by doing a deferred update.

The element referred to by the repeat attribute is identified. If no such repeat element exists, this action has no effect.

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.

Note:

This action affects deferred updates by performing deferred update in its initialization and by setting the deferred update flags for recalculate, revalidate and refresh (because the implicit instance node for the repeat index is modified).

<setindex repeat="R" index="1"/>
<setindex repeat="R" index="index('R')+1"/>

14.8 The toggle Element

This action selects one possible case from an exclusive list of alternatives in a switch element.

Common Attributes: Common, Events, Action Common

Special Attributes:

case
Author-optional reference to the ID of a case element child of a switch element.

A deferred update is done.

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 the toggle action has no effect.

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.

Note:

This action affects deferred updates. If this action has an effect, then a deferred update is performed on its initialization. Also, if this action performs a setvalue, then this action sets the deferred update flags for recalculate, revalidate and refresh.

<toggle case="home"/>
<toggle case="{state}"/>

14.8.1 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, 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>

14.9 The setfocus Element

This action gives input focus to a control.

Common Attributes: Common, Events, Action Common

Special Attribute:

control
Author-optional reference to a control.

The control to which focus should be given is identified by the control element, or otherwise the control attribute. If no such control is identified, then this action has no effect.

A deferred update is done.

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}"/>

14.9.1 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, 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>

14.10 The dispatch Element

This action dispatches an event to an element.

Common Attributes: Common, Events, Action Common

Special Attributes:

name
Author-optional string giving the name of the event to dispatch.
targetid
Author-optional IDREF identifying the target element.
delay
Author-optional number giving the minimum number of milliseconds to delay dispatching the event. The default is 0.
bubbles
Author-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
Author-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.

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.

The name of the event to be dispatched is given by the name attribute or otherwise by the name child element. If the event name is not specified or an empty string, this action has no effect.

The element to which the event is to be dispatched is identified by the targetid attribute or otherwise by the targetid child element. If no element is so identified, this action has no effect.

The event delay, in milliseconds, is obtained from the delay attribute or otherwise from the delay child element, or is otherwise zero.

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.

If the delay is zero, or does not conform to xs:nonNegativeInteger, then the event is dispatched immediately; otherwise, as long as 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.

14.10.1 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, 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>

14.10.2 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, 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>

14.10.3 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, 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>

14.10.4 The property Element (for dispatch)

This element adds context information to an event to be dispatched.

Common Attributes: Common, value

Special Attributes:

name
The name of the context information to pass.

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>

14.11 The rebuild Element

This action causes an rebuild on a model.

Common Attributes: Common, Events, Action Common

A rebuild is done on the model associated with the element:

  • if the element has a model attribute, that model;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.

This action bypasses the normal event flow, i.e. the behavior occurs without dispatching the xforms-rebuild event. See The xforms-rebuild Event for details.

Note:

This action affects deferred updates.

14.12 The recalculate Element

This action causes a recalculate of a model.

Common Attributes: Common, Events, Action Common

A recalculate is done on the model associated with the element:

  • if the element has a model attribute, that model;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.

This action bypasses the normal event flow, i.e. the behavior occurs without dispatching the xforms-recalculate event. See The xforms-recalculate Event for details.

Note:

This action affects deferred updates.

14.13 The revalidate Element

This action causes a revalidate on a model.

Common Attributes: Common, Events, Action Common

A revalidate is done on the model associated with the element:

  • if the element has a model attribute, that model;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.

This action bypasses the normal event flow, i.e. the behavior occurs without dispatching the xforms-revalidate event. See The xforms-revalidate Event for details.

Note:

This action affects deferred updates.

14.14 The refresh Element

This action causes a refresh on a model.

Common Attributes: Common, Events, Action Common

A refresh is done on the model associated with the element:

  • if the element has a model attribute, that model;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.

This action bypasses the normal event flow, i.e. the behavior occurs without dispatching the xforms-refresh event. See The xforms-refresh Event for details.

Note:

This action affects deferred updates.

14.15 The reset Element

This action causes a model to reset its instances to their initial values.

Common Attributes: Common, Events, Action Common

An xforms-reset event is dispatched to the model associated with the reset element:

  • if the element has a model attribute, that model;
  • otherwise, the model identified by the model attribute of the closest ancestor element, if any;
  • otherwise, the first model.

Processing of the xforms-reset event is defined in the processing model — see The xforms-reset Event.

Note:

This action affects deferred updates.

<trigger label="Reset">
  <reset model="m" ev:event="DOMActivate"/>
</trigger>

14.16 The load Element

This action traverses a link, giving a similar effect to clicking on an a element in HTML.

Common Attributes: Common, Events, Action Common, Single Item Binding (author-optional)

Special Attributes:

resource
Author-optional URI of a resource to load.
target
Author-optional presentation context 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]
Author-optional link behavior specifier. The allowed values are "replace", and "new".

A URI is obtained from the Single Item Binding if present, otherwise from the resource child element if present, otherwise from the resource attribute.

This 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 context 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. If traversal fails, then an implementation-specific means of conveying the link traversal failure occurs. Otherwise, processing of the resource reached by traversing the link depends on the obtained context:

_self or replace
The document is loaded into the current presentation context. XForms processing is ended, exactly as if the user had manually requested navigating to a new document.
_blank or new
The document is loaded into a new presentation context, 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.

<load ref="../document" target="_blank"/>
<load resource="http://example.com/index.html"/>

14.16.1 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, 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>

14.17 The send Element

This action initiates submit processing by dispatching an xforms-submit event.

Common Attributes: Common, Events, Action Common

Special Attributes:

submission
Author-optional IDREF of a submission element.

If the submission attribute is given but does not identify a submission element, then the send action has no effect.

If the attribute is omitted, then the first submission in document order from the model associated with the in-scope evaluation context is used.

Processing of the xforms-submit event is defined in the processing model — see The xforms-submit Event.

<send submission="update"/>
<send/>

14.18 The message Element

This action presents a message to the user.

Common Attributes: Common, Events, Action Common, Single Item Binding, value (all author-optional)

Special Attributes:

level
Author-optional message-level identifier, one of ("ephemeral"|"modeless"|"modal"|QNameButNotNCName). The default is "modal". There is no defined behavior for QNameButNotNCName values.

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.

Note: Due to deferred updates, 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 a recalculate action should be done before the message action. Moreover, if the computational dependencies involve nodes that were inserted or deleted, then a rebuild action should be done prior to the recalculate.

<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 the xforms-refresh event processing:

<input ref="birthday" label="Enter birthday:">
  <message ev:event="xforms-invalid">
      <output ref="."/> isn't a valid date
  </message>
</input>

14.18.1 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.

14.18.2 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?'

14.18.3 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!'

14.19 Conditional Execution of XForms Actions

An if attribute can be added to any Action. It contains an expression that is evaluated using the in-scope evaluation context before the action is executed. The result of the expression is converted to a boolean as described in the expression module. 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>

14.20 The while attribute

The while attribute can be added to any XForms action. It contains an expression that is evaluated using the in-scope evaluation context before the action is executed. The result of the expression is converted to a boolean as described in the expression module. If the converted result of the expression is true, then the XForms action is performed and then the expression is re-evaluated. The XForms action is executed repeatedly until the converted result of the expression evaluates to false.

If this attribute is applied to an XForms action element, then the sequence of XForms actions in its content are executed repeatedly once for each time the immediately preceding evaluation of the expression yields a result of true.

When XForms actions are iteratively executed, they are still subject to the normal action processing rules such as deferred update and applicability of conditional and iterative attributes.

An XForms action may be executed zero times due to this attribute. Furthermore, if an action bears this attribute and the if attribute, then the expressions of both attributes must evaluate to true before each iterative execution of the action.

Note: In actions insert and delete, the attribute context is evaluated before the while attribute. Therefore, context is re-evaluated before each iteration of the actions controlled by the while attribute.

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>

14.21 The iterate attribute

The iterate attribute can be added to any Action. It contains an expression that is evaluated once using the in-scope evaluation context before the action is executed, which will result in a sequence of items. The action will be executed with each item in the sequence as its context. This context replaces the default in-scope evaluation context.

 <delete ref="." at="1" iterate="node[@selected='true']"/>
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 in-scope 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.

14.22 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.

15 Conformance

15.1 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.

15.2 Conforming XForms Generators

XForms generators should generate conforming XForms documents.

15.3 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:

15.4 Conformance Levels

There are two levels of conformance: "model", and "full".

15.4.1 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 attributes, content and other aspects of bind elements, except p3ptype which is optional;
  • 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, rebuild, recalculate, revalidate, 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;

15.4.2 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 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 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.

16 Glossary Of Terms

Binding
[Definition: A "binding" connects a control or a model item property to an item (either a node or an atomic value (such as an integer, date, or string)) by using a binding expression as a locator.]
Binding expression
[Definition: An expression used in a binding. The language used for the expression is defined by the expression module]
Compound Document
A [CDRF 1.0] Compound Document is a document that combines multiple document formats either by reference, by inclusion or both.
Computed expression
[Definition: An expression used by model item properties such as relevant and calculate to include dynamic functionality.]
Containing document
[Definition: A specific document, for example an XHTML document, in which one or more <model> elements are found.]
Control
[Definition: A point of user interaction (a core control) or a container for other controls (a container control).]
Datatype
[Definition: From XML Schema [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.]
Expression module
[Definition: A separate specification that defines an expression language that can be used for addressing instance data nodes in binding expressions, to express constraints, and to specify calculations.]
Facet
[Definition: From XML Schema [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
[Definition: When a Single Item Binding selects a sequence of size > 1, the first item in the sequence is used.]
Host language
[Definition: An XML vocabulary, such as XHTML, into which XForms is embedded.]
Instance data
[Definition: An internal representation of the values and states of data being processed.]
Instance data node
[Definition: An [XPath 1.0] node from the instance data.]
Item
[Definition: An item is either a node or an atomic value (such as an integer, date, or string).]
Lax schema processing
[Definition: From XML Schema [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
[Definition: From XML Schema [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
[Definition: 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
[Definition: An XForms-specific annotation to an instance data node.]
Node
[Definition: The definition as used in the XPath Data Model.]
Non-relevant Control
[Definition: A control satisfying at least one of the non-relevance conditions.]
QNameButNotNCName
[Definition: A QName that is not an NCName. In 2006, the W3C named this a PrefixedName. ]
Relevant Control
[Definition: A control satisfying none of the non-relevance conditions.]
Schema constraint
[Definition: A restriction, applied to instance data, based on XML Schema datatypes.]
Strict schema processing
[Definition: From XML Schema [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.]
UI Binding Expression
[Definition: An expression used in binding a control to the instance.]
Valid node
[Definition: An instance data node whose constraint model item property is true, is non-empty if the required model item property is true, and which satisfies all applicable XML Schema definitions (including those associated by the type model item property, by xsi:type or by an external or inline schema).]
Value space
[Definition: From XML Schema [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
[Definition: A list ([XML Schema part 2]) with an atomic datatype ([XML Schema part 2]) of versionNumber.]
versionNumber
[Definition: 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
[Definition: The non-visible definition of an XML form as specified by XForms. The XForms Model defines the individual model items and constraints and other run-time aspects of XForms.]
Processor
[Definition: A software application or program that implements and conforms to the XForms specification.]

17 References

17.1 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.
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 2822
RFC 2822: Internet Message Format, P. Resnick, 2001. Available at: http://www.ietf.org/rfc/rfc2822.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.
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/.
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/.

17.2 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.
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/.

18 Integration with SOAP

This section describes the integration of XForms submission with [SOAP 1.1] and [SOAP 1.2]

18.1 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).

18.2 Indicating a SOAP submission

For a SOAP submission, the mediatype attribute of the submission must be set to the MIME type of application/soap+xml. The form author may append charset and action MIME parameters.

Note:

The action MIME parameter has no effect unless the submission method is "post" because the GET method implies no SOAP processing by the receiving SOAP node.

Note:

SOAP 1.1 does not support the HTTP GET operation.

18.3 SOAP HTTP Binding

The method attribute of the submission must be set to get or post in order to access the SOAP HTTP binding.

If method="get", then the SOAP response message exchange pattern is used. The HTTP headers must contain the Accept parameter with a value conforming to the following properties:

  • must begin with application/soap+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>

18.4 Handling the SOAP Response

The XForms Processor must handle client authorization and redirection.

SOAP faults (400 and 500 level errors) are handled in the same manner as underlying HTTP errors, which is to say that an xforms-submit-error event is dispatched.

On successful completion, the results are consumed according to the XForms submission process, culminating in an xforms-submit-done event. The form author may capture this event and copy data from the target instance that receives the returned SOAP envelope to other instances that are designed to carry only data.


19 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.

19.1 Prepend Element Copy

Pattern: <insert context="parent of new element" origin="element to copy"/>

Note:

The context attribute is used so that this pattern will work whether or not the parent element is empty.

Operation: Prepend a new, empty person element into a list of people

<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>

19.2 Append Element Copy

Pattern: <insert context="parent of new element" ref="*" origin="element to copy"/>

Note:

The context attribute is used so that this pattern will work whether or not the parent element is empty.

Operation: Append a new, empty person element into a list of people

<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>

19.3 Duplicate Element

Pattern: <insert ref="exact element to duplicate"/>

Note:

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.

Operation: Duplicate the selected element and place it as a following sibling

<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>

19.4 Set Attribute

Pattern: <insert context="container element receiving attribute" origin="attribute to copy"/>

Note:

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.

Operation: Create or replace an attribute with a copy of a given attribute

<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>

19.5 Remove Element

Pattern: <delete ref="exact element to remove"/>

Note:

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.

Operation: Remove item element in case it exists

<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>

19.6 Remove Attribute

Pattern: <delete ref="exact attribute to remove"/>

Note:

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.

Operation: Remove rating attribute in case it exists

<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>

19.7 Remove Sequence

Pattern: <delete ref="sequence to remove"/>

Note:

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.

Operation: Remove track sequence in case it exists

<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>

19.8 Copy Sequence

Pattern: <insert context="parent of new sequence" ref="*" origin="sequence to copy"/>

Note:

The context attribute is used so that this pattern will work whether or not the parent element is empty.

Operation: Append a person sequence into a list of people

<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>

19.9 Copy Attribute List

Pattern: <insert context="exact element receiving attribute list" origin="attribute list to copy"/>

Operation: Copy attribute list from one item to another

<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>

19.10 Replace Element

Pattern: <insert ref="exact element to replace" origin="element to copy"/> <delete ref="exact element to replace"/>

Note:

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, both insert and delete operation will have no effect.

Operation: Replace a person element by copying a new one and removing the old one

<insert ref="person[1]" origin="instance('prototypes')/person"/>
<delete ref="person[1]"/>

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>

19.11 Replace Attribute

Pattern: <setvalue ref="exact attribute to replace" value="attribute to copy"/>

Note:

If the attribute does not exist, the operation will have no effect.

Operation: Replace an attribute with the copy of a given attribute

<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>

19.12 Replace Instance with Insert

Pattern: <insert ref="root node of instance to replace" origin="element to copy"/>

Note:

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.

Operation: Replace instance root node with an empty shoppingcart element

<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>

19.13 Move Element

Pattern: <insert context="new parent of element" ref="*" origin="exact element to move"/> <delete ref="exact element to move"/>

Note:

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.

Operation: Copy an existing element to a new parent and remove the original

<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>

19.14 Move Attribute

Pattern: <insert context="exact element receiving attribute" origin="exact attribute to move"/> <delete ref="exact attribute to move"/>

Note:

If the attribute to be moved does not exist, both insert and delete operation will have no effect.

Operation: Copy an existing attribute to a new element and remove the original

<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>

19.15 Insert Element into Non-Contiguous, Heterogeneous Sequence

Pattern: <insert ref="non-contiguous, heterogeneous sequence" origin="element to copy" at="insert location"/>

Note:

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.

Operation: Copy an existing element into a non-contiguous, heterogeneous sequence at a specified position

<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>

19.16 Move Elements Up and Down in a List

This pattern allows a user to reorder elements in a list by moving them up and down, for instance to sort a list into order of preference.

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


20 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].

20.1 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.

20.2 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.

20.3 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.

20.4 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.

21 Privacy Considerations (Non-Normative)

21.1 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.

22 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.

22.1 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 later 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.

22.2 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.

22.3 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.

22.3.1 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

22.3.2 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)

22.4 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.

22.5 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"/>

23 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.

23.1 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.

24 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.

24.1 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 Defined in: Relationship to XForms
:enabled & :disabled [CSS3]

Selects any control that is relevant or non-relevant (respectively).

:required & :optional TBD Selects any core control bound to a node with the model item property required evaluating to true or false (respectively).
:valid & :invalid TBD Selects any core control bound to a node that is currently valid or invalid (respectively), as defined by XForms.
:read-only & :read-write TBD 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 TBD 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 TBD 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.

24.2 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 Defined in: Relationship to XForms
::value TBD 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 TBD Represents the identity of the selected case of a switch.
::repeat-item TBD 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 TBD 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.

24.3 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');

All controls, but not repeat items, should have an inline layout by default. Repeat items should have a block layout.

 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|group:enabled, xf|switch:enabled { display: inline; }
 xf|repeat:enabled { display: inline; }
 ::repeat-item:enabled { display:block; }

Non-relevant 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 readonly control should render in a way which indicates that entering or changing the value is not allowed. For example:

xf|input:enabled:readonly::value
{
  display: inline; background-color: #888888
}

Except as noted, relevant 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
}

Relevant 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;
}

Relevant 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;
}

25 Complete XForms Examples (Non-Normative)

This section presents complete XForms examples. These and additional examples are maintained at http://www.w3.org/MarkUp/Forms/2002/Examples.

25.1 XForms in XHTML

<html xmlns="http://www.w3.org/1999/xhtml" xmlns:ev="http://www.w3.org/2001/xml-events" xmlns:my="http://commerce.example.com/payment" xml:lang="en">
  <head>
    <title>XForms in XHTML</title>
    <model xmlns="http://www.w3.org/2002/xforms" schema="payschema.xsd">
      <instance>
        <my:payment as="credit">
          <my:cc/>
          <my:exp/>
        </my:payment>
      </instance>
      <submission resource="http://www.example.com/buy.rb" method="post" id="s00"/>
      <bind ref="my:cc" relevant="../@as='credit'" required="true()"/>
      <bind ref="my:exp" 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" value="'credit'"/>
      </select1>

      <input ref="my:cc" label="Credit Card Number">
        <alert>Please specify a valid credit card number
          (use spaces or hyphens between digit groups)</alert>
      </input>

      <input ref="my:exp" label="Expiration Date"/>

      <submit submission="s00" label="Buy"/>
    </group>
    ...
  </body>
 </html>

Schema file payschema.xsd:

 <xs:schema xmlns:my="http://commerce.example.com/payment" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://commerce.example.com/payment" elementFormDefault="qualified">

  <xs:element name="payment">
    <xs:complexType>
      <xs:sequence minOccurs="0" maxOccurs="unbounded">
        <xs:choice>
          <xs:element ref="my:cc"/>
          <xs:element ref="my:exp"/>
        </xs:choice>
      </xs:sequence>
      <xs:attribute name="as" type="my:paymentAs"/>
    </xs:complexType>
  </xs:element>
  <xs:element name="cc" type="my:cc"/>
  <xs:element name="exp" type="xs:gYearMonth"/>

  <xs:simpleType name="cc">
    <xs:restriction base="xs:string">
      <xs:minLength value="12"/>
      <xs:maxLength value="19"/>
      <xs:pattern value="[0-9]+"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="paymentAs">
    <xs:restriction base="xs:string">
      <xs:enumeration value="cash"/>
      <xs:enumeration value="credit"/>
    </xs:restriction>
  </xs:simpleType>
 </xs:schema>

25.2 Editing Hierarchical Bookmarks Using XForms

<html xmlns="http://www.w3.org/2002/06/xhtml2" xmlns:xforms="http://www.w3.org/2002/xforms" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:my="http://commerce.example.com/payment" xmlns:ev="http://www.w3.org/2001/xml-events" xml:lang="en">
  <head>
    <style type="text/css">
      xforms|input.editField {
       font-weight:bold; font-size:20px; width:500px
      }
      xforms|label.sectionLabel {
        font-weight:bold; color:white; background-color:blue
      }
      xforms|submit {
        font-family: Arial; font-size: 20px; font-style: bold; color: red
      }
    </style>
    <title>Editing Hierarchical Bookmarks</title>
    <model id="bookmarks" version="2.0" xmlns="http://www.w3.org/2002/xforms">
      <instance resource="bookmarks.xml"/>
      <submission id="s01" method="post" resource="http://examples.com/"/>
    </model>
  </head>
  <body>
    <group xmlns="http://www.w3.org/2002/xforms">
      <repeat ref="section" id="repeatSections">
        <input ref="@name" class="editField">
          <label class="sectionLabel">Section</label>
        </input>
        <!-- BOOKMARK REPEAT START -->
        <repeat ref="bookmark" id="repeatBookmarks">
          <input ref="@name">
            <label>Bookmark name</label>
          </input>
          <input ref="@href">
            <label>URL</label>
          </input>
        </repeat>
      </repeat>
      <p>
        <!-- INSERT BOOKMARK BUTTON -->
        <trigger id="insertbutton">
          <label>Insert bookmark</label>
          <insert ref="section[index('repeatSections')]/bookmark" at="index('repeatBookmarks')" position="after" ev:event="DOMActivate"/>
        </trigger>
        <!-- DELETE BOOKMARK BUTTON -->
        <trigger id="delete">
          <label>Delete bookmark</label>
          <delete ref="section[index('repeatSections')]/bookmark" at="index('repeatBookmarks')" ev:event="DOMActivate"/>
        </trigger>
      </p>
      <p>
        <!-- INSERT SECTION BUTTON -->
        <trigger id="insertsectionbutton">
          <label>Insert section</label>
          <insert ref="section" at="index('repeatSections')" position="after" ev:event="DOMActivate"/>
        </trigger>
        <!-- DELETE SECTION BUTTON -->
        <trigger id="deletesectionbutton">
          <label>Delete section</label>
          <delete ref="section" at="index('repeatSections')" ev:event="DOMActivate"/>
        </trigger>
      </p>
      <!-- SUBMIT BUTTON -->
      <submit submission="s01">
        <label>Save</label>
        <hint>Click to submit</hint>
      </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:///C/source/xmlevents.xml" name="XML events"/>
    <bookmark href="file:///C/source/model3.xml" name="model3"/>
    <bookmark href="file:///C/source/repeat.fo" name="repeat"/>
  </section>
 </bookmarks>

25.3 Survey Using XForms and SVG

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 integrating XForms and SVG which might not be compatible with the example below.

Note that the example below does not use SVG's switch and requiredExtensions features, which are commonly used in conjunction with foreignObject.

<svg xmlns="http://www.w3.org/2000/svg"
      xmlns:svg="http://www.w3.org/2000/svg"
      xmlns:xlink="http://www.w3.org/1999/xlink"
      xmlns:s="http://example.com/survey"
      width="700px" height="600px" viewBox="0 0 700 600">
   <defs>
     <polygon id="bullet" points="-30,-30, -10,-10, -20,10" fill="#007138"/>
     <model id="form1" schema="surveyschema.xsd" xmlns="http://www.w3.org/2002/xforms">
       <instance id="instance1">
         <survey xmlns="http://example.com/survey">
           <drink>none</drink>
           <espressoPrefs>
             <numberPerWeek>0</numberPerWeek>
             <sugar>0</sugar>
             <lemon>Always</lemon>
           </espressoPrefs>
         </survey>
       </instance>
       <submission id="submit1" method="post" resource="http://www.example.org/surveyhandler"/>
     </model>
   </defs>
   <title>Espresso survey</title>
   <desc>Sample SVG and XForms - espresso customer survey</desc>
   <g>
     <text x="50" y="70" font-size="40" font-family="Arial Black, sans-serif" font-weight="900">Customer Survey: Espresso</text>
     <g font-family="Arial, Helvetica, sans-serif" font-size="18">
       <foreignObject x="80" y="150" width="250" height="40">
         <group xmlns="http://www.w3.org/2002/xforms">
           <select1 appearance="minimal" model="form1" ref="s:drink">
             <label>
               <svg:g transform="translate(80, 140)">
                 <svg:use xlink:href="#bullet"/>
                 <svg:text>Your usual coffee drink is:</svg:text>
               </svg:g>
             </label>
             <item>
               <label>Rich, dark espresso</label>
               <value>espresso</value>
             </item>
             <item>
               <label>Creamy cappuccino</label>
               <value>cappuccino</value>
             </item>
             <item>
               <label>Long, milky latte</label>
               <value>latte</value>
             </item>
             <item>
               <label>Don't like coffee!</label>
               <value>none</value>
             </item>
           </select1>
         </group>
       </foreignObject>
       <foreignObject x="80" y="240" width="250" height="40">
         <group xmlns="http://www.w3.org/2002/xforms">
           <range model="form1" start="0" end="30" step="5" ref="s:espressoPrefs/s:numberPerWeek">
             <label>
               <svg:g transform="translate(80, 230)">
                 <svg:use xlink:href="#bullet"/>
                 <svg:text>Shots of espresso per week:</svg:text>
               </svg:g>
             </label>
           </range>
         </group>
       </foreignObject>
       <foreignObject x="80" y="350" width="250" height="40">
         <group xmlns:xforms="http://www.w3.org/2002/xforms">
           <select model="form1" ref="s:espressoPrefs/s:sugar">
             <label>
               <svg:g transform="translate(80, 340)">
                 <svg:use xlink:href="#bullet"/>
                 <svg:text>Sugar?</svg:text>
               </svg:g>
             </label>
             <item>
               <label>Yes</label>
               <value>X</value>
             </item>
           </select>
         </group>
       </foreignObject>
       <foreignObject x="80" y="420" width="250" height="90">
         <group xmlns="http://www.w3.org/2002/xforms">
           <select1 appearance="full" model="form1" ref="s:espressoPrefs/s:lemon">
             <label>
               <svg:g transform="translate(80, 410)">
                 <svg:use xlink:href="#bullet"/>
                 <svg:text>Lemon?</svg:text>
               </svg:g>
             </label>
             <item>
               <label>Required for the full experience</label>
               <value>Always</value>
             </item>
             <item>
               <label>Whatever</label>
               <value>Indifferent</value>
             </item>
             <item>
               <label>Keep that citrus to yourself</label>
               <value>Never</value>
             </item>
           </select1>
         </group>
       </foreignObject>
     </g>
     <use xlink:href="#bullet" x="101" y="64" transform="scale(7,3)"/>
     <foreignObject y="150" x="500" height="60" width="100">
       <submit model="form1" xmlns="http://www.w3.org/2002/xforms">
         <label>Send survey</label>
       </submit>
     </foreignObject>
     <!--- keep the graphics data out of this example listing -->
     <image xlink:href="espresso.svg" x="400" y="230" width="280" height="270"/>
   </g>
 </svg>


26 Acknowledgements (Non-Normative)

This document was produced with the participation of Forms Working Group participants, including:

  • John M. Boyer, IBM (Editor, Chair until March 2010)
  • Erik Bruchez, Orbeon
  • Kurt Cagle, Invited expert
  • Alain Couthures, Invited expert
  • Philip Fennell, MarkLogic
  • Leigh L. Klotz, Jr., Xerox Corporation (Editor until March 2012, Co-chair until March 2012)
  • 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. (Editor)
  • Alessandro Vernet, Orbeon
  • Charles Wiecha, IBM

27 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>