XForms/Sorting using XSLT

From Wikibooks, open books for an open world
Jump to navigation Jump to search

Motivation[edit | edit source]

One problem that keeps popping up when creating forms with XForms is the lack of sorting. This is an example for how it is possible to sort an instance using a XSLT stylesheet in Firefox.

Firefox XForms Example[edit | edit source]

The following model contains two instances. The first instance is the one we will sort and the second instance contains the XSLT stylesheet we will use to perform the sort.

  <xf:instance id="default-instance">
    <data xmlns="">

  <xf:instance id="stylesheet">
      <xsl:template match="/">
          <xsl:apply-templates select="data/item">
            <xsl:sort type="string" select="name"/>
      <xsl:template match="*|@*|text()">
          <xsl:apply-templates select="*|text()|@*"/>

To perform the sort we will use the following JavaScript which will load the second instance into the Firefox stylesheet engine, then take the first instance make the transformation which will produce the sorted instance. Then the transformed instance is inserted into the model and a rebuild, recalculate, revalidate and refresh is performed.

function sort_instance(id) {
  // We get the instance element
  var instanceElement = document.getElementById(id);
  if (instanceElement!=null) {

   // XForms exposes the retrival of the instance document from the model element which *should*
   // be the parent for the instance element.
   var instance = instanceElement.parentNode.getInstanceDocument(id);

   if (instance!=null) {
      // Now creating the stylesheet, for this example the stylesheet document is also an instance
      // by it can be loaded from many difference sources
      var xslDom = instanceElement.parentNode.getInstanceDocument('stylesheet');

      // create an XSLTProcessor and attach the stylesheet
      var processor = new XSLTProcessor()

      // now we do the sorting transformation
      var resultDom = processor.transformToDocument(instance, instance);

      // we then move the result info the instance dom

      // and performs the updates for XForms

Discussion[edit | edit source]

The idea of having the stylesheet in an instance makes it possible to change the behavior of the sorting by binding controls to it and change stuff like XPath expressions and other XSLT syntax.

References[edit | edit source]

This example is based upon the sample on [[1]http://landwehr.dk/blog/]

Next Page: Mobile XForms | Previous Page: Google Maps
Home: XForms