In the previous article, I showed you how to manage user input in the XForms model. I discussed the process of submitting an XForm and – more importantly - validating user input prior to submission using built-in XML Schema support. In this concluding article, find out how to use the <xforms:bind> element to perform calculations on form input values, integrate XPath expressions into your XForms model and get a crash course in the XForms event model.
You've already seen how various XML technologies integrate seamlessly with each other when it comes to XForms. In fact, in the last part of this tutorial, I showed you how to re-use an XML Schema datatype definition in an XForms model, and how to use XPath expressions to reference and bind instance data with the XForms user interface. But why stop there? You can also use logical, comparison and arithmetic operators and functions with XPath expressions, in order to perform calculations using the instance data in an XForms model.
In order to do this, you need to first understand the <xforms:bind> element, which makes it possible to bind instance data elements to specific properties and constraints. The <xforms:bind> element comes with a number of additional attributes, which can be used to specify whether a particular element of the instance data is required, read-only, constrained to specific values or compliant with a specific type.
Consider the following example, which demonstrates:
<!-- form model --> <xforms:model id=account> <xforms:instance> <ACCOUNT> <NAME /> <NUMBER /> </ACCOUNT> </xforms:instance> <xforms:bind id=accountNumberRequired required="true()" nodeset="/account/number"> </xforms:bind> </xforms:model>
In this case, the bind definition states that the account number is required in order for the form to be submitted. This is a very fundamental example of input validation. With normal HTML forms, you'd need to write client-side and server-side code to manage this requirement; with XForms, it comes built-in!
In case you were wondering where this bind definition gets used, the XForms specification states that user interface elements can then be linked to the definition, simply by adding a "bind" attribute to the interface control (instead of the traditional "ref" attribute). Here's an example:
<!-- define the form interface --> <xforms:input bind="accountNumberRequired"> <xforms:label>Account number</xforms:label> </xforms:input>