Wednesday, May 2, 2012

How XForms controls bind to data

Photo by Philippa Willitts
Take the most basic HTML input field:
<input name="nickname">
Then, compare to the equivalent XForms:
<xforms:input ref="nickname">
Both look pretty much the same, right? Well yes, but only on the surface!

In HTML, you just specify a name, which is later used by form submission (or to query form fields). In XForms, on the other hand, the ref attribute holds an XPath expression pointing to zero, one or more XML element or attribute nodes.

Often, XPath binding expressions are very simple and look just like a plain name, like above, where the expression in fact says "under the curent XPath context, point to the XML element called nickname".

Where are those XML elements defined? In XML documents (called instances in XForms) defined in the XForms model. For example:
Because the expressions are XPath, they can be more fancy when needed. In fact they allow you to point to any node in an instance. Consider the more complex:
<xforms:instance id="zoo">
        <animal tag="42">
        </animal >
        <animal tag="43">
        </animal >
Here we point to a very specific nickname element:
<xforms:input ref="instance('zoo')/animal[@tag = '42']/nickname">
Now once your control points to a node, what does it do? It is pretty simple:
  1. When the user enters data into the field, the data is written to the XML document.
  2. If the data changes in the XML document, the control is updated with that data.
It's a nice example of the MVC pattern, where the model is made of hierarchical XML documents, the view is made of controls, and where data flows in both directions between model and view.

In a subsequent post we cover in more details what kind of things you can bind controls to!

No comments:

Post a Comment