XForms patterns

This section looks at common patterns that occur when programming with XForms. By documenting patterns for reuse we can speed up the development process and reduce errors.

Initialising a document on first use of a form

Use case

A model has some instance data which is loaded from a particular URL, and which the user can edit during the course of using the form. However, when the form is first used, an attempt to load this data will fail since the document won't yet exist. In this situation we would like to use some inline instance data to initialise the document.

Description

Two submissions are created in the model, one that performs a get and the other a put, and both using the same document URL for their @action value. The put submission can be used at any time to save the instance data, such as after the data has changed, or periodically to ensure no data is lost.

When the model is first loaded (i.e., on notification of xforms-ready), the get submission is attempted. If it is successful then it means that there was already existing data available, and a load event is dispatched to the model.

If the get submission fails it means that this is the first time that the form has been run, and so the put submission is used. Since this submission simply saves the contents of the instance then it will have the effect of saving the initialising data.

Example Useage

<xf:model id="mdl-config">
  <xf:instance id="inst-config">
    <instanceData xmlns="">
      <favourites />
      <settings />
    </instanceData>
  </xf:instance>

  <xf:submission
   id="sub-get-inst-config"
   method="get"
   ref="instance('inst-config')/ANodeThatDoesNotExist"
   action="my-data.xml"
   replace="instance" instance="inst-config"
  >
    <xf:action ev:event="xforms-submit-error">
      <xf:send submission="sub-put-inst-config" />
    </xf:action>
  </xf:submission>

  <xf:submission
   id="sub-put-inst-config"
   method="put"
   ref="instance('inst-config')"
   action="my-data.xml"
   replace="none"
  />

  <xf:action ev:event="xforms-ready">
    <xf:send submission="sub-get-inst-config" />
  </xf:action>
</xf:model>

Template

The proposed template to make use of this pattern is to use a combination of @src and inline instance data:

<xf:model id="mdl-config">
  <xf:instance id="inst-config" src="my-data.xml">
    <instanceData xmlns="">
      <favourites />
      <settings />
    </instanceData>
  </xf:instance>
</xf:model>