XForms Custom Controls

Since Firefox 4, XBL and XUL are disabled by default for all pages not loaded from a chrome:// URL. This also includes content loaded from file:// URLs. It is possible to re-enable this by following the steps on Using Remote XUL. This is required for all examples here to run!

Purpose

You are in the right place if you would like to create your own custom renderings of the XForms controls like input, output, trigger, etc. We will also show you how to create custom controls that work with the XForms model and are automatically updated just like XForms controls. The purpose of this article is to give you enough background information so that you'll be able to get a good start. To really grasp the following information, a good understanding of XForms, XBL, JavaScript and CSS is needed. XPCOM knowledge will certainly not hurt. But even if you are only comfortable with a couple of these technologies, we hope that the possibilities outlined below will inspire you to learn more where you need to.

Implementation Status

The framework we use in the Mozilla XForms processor is very much a "work in progress". Please keep in mind that just about everything we mention here may change to some degree as we continue to work on it. Work has just started in the W3C XForms Working Group to investigate the custom control issue, so eventually (hopefully?) there will be an "official" and common way to customize your form's user interface across all XForms processors.

Why Do You Need This

You will probably find that your need for customization will fall into one of the following categories:

  • custom presentation - XForms controls as rendered by the Mozilla XForms processor do not provide the right look and feel for you.
  • custom data types - existing XForms controls are not able to work properly with your data type
  • advanced XForms controls - you need your controls to be able to do more things than traditional XForms controls can do
  • new host language - you'd like to support XForms in host languages other than XHTML or XUL

Custom Presentation

The Mozilla XForms extension cannot anticipate all of the possible use cases that will evolve in web applications and web pages as XForms matures and the user base grows. And with these new uses, more and more flexibility will be desired from the controls. Introducing custom controls into your environment may be just the solution you are looking for. For example, you might want to render images that are held inside an instance document or you would like to show a disabled trigger when its bound node becomes irrelevant rather than having it not display (the current default behavior).

Every XForms control's presentation has its own XBL binding. In many cases different values provided for the appearance or mediatype attributes will determine which XBL binding will be used for a particular XForms control on the form. As mentioned in the spec, the appearance attribute can be used to influence the look and feel of a control even when all other conditions remain constant. For example, in the Mozilla XForms extension we will render a combobox widget when appearance='minimal' on a select1 control. Should the form author instead choose to use appearance='compact' on this control, we would render a listbox widget. Here is a snippet from our .css file to show the type of CSS rule we would use to make such a determination.

xf|select1[appearance="compact"] {
  -moz-binding: url('chrome://xforms/content/select-xhtml.xml#xformswidget-select1-compact');
}

The mediatype attribute can be used by the form author to align the type of presentation with the type of data that the bound instance node contains. For example, if mediatype='image/*' then the user should see the image that the bytes represent rather than just the byte sequence.

xf|output[mediatype^="image"] {
  -moz-binding: url('chrome://xforms/content/xforms-xhtml.xml#xformswidget-output-mediatype-anyURI');
}

Custom Data Types

If you define a new schema data type or you use a built-in data type and find the current XForms control for this type to be insufficient, then you should write a new custom control. For example, if you have an instance node of type xsd:date and you'd like to see the date displayed in a local format.

In Mozilla, every bound XForms control has a typelist attribute of mozType namespace that contains the inheritance chain of data types that we detected. The mozType namespace is introduced by Mozilla XForms implementation and its URI is http://www.mozilla.org/projects/xforms/2005/type. For example, if a control is bound to a node of type xsd:integer then the typelist attribute will be "http://www.w3.org/2001/XMLSchema#integer http://www.w3.org/2001/XMLSchema#decimal". This is because xsd:integer is inherited from the xsd:decimal data type. We recommend that you use this attribute to create the CSS binding rule for your custom control. This will allow you to bind your custom control for the data type that you are targeting AND any type derived from that target type. So if you want an input bound to an instance node of type integer (and all types derived from integer), you would use:

@namespace xf url(http://www.w3.org/2002/xforms);
@namespace mozType url(http://www.mozilla.org/projects/xforms/2005/type);

xf|input[mozType|typelist~="http://www.w3.org/2001/XMLSchema#integer"] {
  -moz-binding: url('chrome://xforms/content/input-xhtml.xml#xformswidget-input-integer');
}

Advanced XForms Controls

There may be times where you need a control that is very specific to your task, but you also want it to work with XForms models and instance nodes just like a regular XForms control. The XForms specification provides for a nice way to do this using XForms binding attributes (like ref, or nodeset) on your custom control element. However, the Mozilla XForms implementation currently doesn't support this approach. But there is a way for you to achieve the same result. You can put the XForms controls inside your XBL binding. Note you should take care to make sure that the embedded XForms controls are able to work with the data type of the instance node that your control is bound to. To give you an idea of what we are talking about, it could look something like this:

<content>
  <xf:input xbl:inherits="ref=ref1" anonid="ref1"/>
  <xf:input xbl:inherits="ref=ref2" anonid="ref2"/>
</content>

<implementation>
  <method name="refresh">
    <body>
      // Here we should refresh custom control.
    </body>
  </method>

  <constructor>
    // We should redirect calls of input's 'refresh' method to custom control 'refresh' method.
    var control = this;
    var refreshStub = function() {
      control.refresh();
    }

    this.ref1.refresh = refreshStub;
    this.ref2.refresh = refreshStub;
  </constructor>

  <property name="ref1" readonly="true"
            onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref1');"/>
  <property name="ref2" readonly="true"
            onget="return this.ownerDocument.getAnonymousElementByAttribute(this, 'anonid', 'ref2');"/>
</implementation>

New Host Language

The Mozilla XForms implementation currently only supports XForms hosted in XHTML or XUL documents. If you need to have XForms in other kinds of documents like SVG, MathML or some other tag language that Mozilla supports, then you'll need to implement XForms controls for your desired document format. The XForms implementation has base XBL bindings for every XForms control. You can write implementation bindings that will inherit from these base bindings. For example, every output control implementation extends the base binding xforms.xml#xformswidget-output-base. The XHTML-specific pieces of our implementation of output is kept in the xforms-xhtml.xml#xformswidget-output binding. If you would like to do this kind of heroic work then please contact the Mozilla XForms developers before you start. Hopefully we can help you avoid a lot of frustration and despair :).

Overview

The Mozilla XForms controls are largely implemented using XBL and the bindings are applied to the individual xforms control tags via CSS. So you can always refer to our source code to get some great examples of how XForms controls can be written. This will also allow you to be up to date with our current approaches (often the result of hard-learned lessons) and that will hopefully help you to more easily write your own controls. To get started, you really only need to know the language where you'd like to use XForms (like XHTML or XUL), some XBL and JavaScript, and the XPCOM interfaces we are exposing for your use.

Details

Interfaces

This section describes interfaces you need to know. There are two main groups of interfaces -> callback interfaces that must be implemented by the custom controls and the interfaces that custom controls can use to access the Mozilla XForms engine.

nsIXFormsUIWidget

Every custom control should implement the nsIXFormsUIWidget interface. This interface is used by the XForms engine to interact with the underlying control. For example, when the control needs to be updated according to the rules of XForms, the refresh method will be called by the processor. Below is the structure of the interface. As always, please refer directly to the source code to be sure that you are using the latest, up-to-date version: extensions/xforms/nsIXFormsUIWidget.idl.

interface nsIXFormsUIWidget : nsIDOMElement
{
  /**
   * Is called when control should be updated to reflect the value of the bound node.
   */
  void refresh();

  /**
   * Is called when focus is advanced to the XForms element.
   */
  boolean focus();

  /**
   * Is called when control should be disabled.
   * This really only applies to the submit element.
   */
  void disable(in boolean disable);

  /**
   * Is called to get current value of control.
   */
  string getCurrentValue();
}

Notes:

  • getCurrentValue() should return the current value of the control as seen by a user. The current value of a control could differ from the value of the bound node in cases where @incremental='false'.
  • disable() is called by the XForms processor to indicate to a submit element that it needs to disable/enable due to the beginning/ending of the submission process. Currently it has no meaning outside of this context.
  • focus() is used by the processor to tell the control that it is getting focus through one of a variety of ways (i.e. through xf:setfocus action) and that the control needs to ensure that the proper widget is given focus.

With rare exception, your control should only need to implement the nsIXFormsUIWidget interface. But certain XForms controls need to implement additional interfaces. Such elements include upload and case.

nsIXFormsAccessors

The nsIXFormsAccessors interface allows access to the value and the state of the instance node that the control is bound to (see extensions/xforms/nsIXFormsAccessors.idl). Currently interface is:

interface nsIXFormsAccessors : nsISupports
{
  /**
   * Return value of instance node.
   */
  DOMString getValue();

  /**
   * Set value of instance node.
   */
  void setValue(in DOMString value);

  /**
   * Return true if the instance node is readonly as determined by the MDG.
   */
  boolean isReadonly();

  /**
   * Return true if the instance node is relevant as determined by the MDG.
   */
  boolean isRelevant();

  /**
   * Return true if the instance node is required as determined by the MDG.
   */
  boolean isRequired();

  /**
   * Return true if instance node is valid as determined by the MDG.
   */
  boolean isValid();

  /**
   * Return true if the control is bound to an instance node.
   */
  boolean hasBoundNode();

  /**
   * Return the bound instance node.
   */
  nsIDOMNode getBoundNode();

  /**
   * Set the content of the instance node.  If aForceUpdate is true then the
   * XForms model will rebuild/recalculate/revalidate/refresh.
   */
  void setContent(in nsIDOMNode aNode, in boolean aForceUpdate);
}

note: setContent() can be used to set place complexContent (mixture of text and element nodes) under the control's bound node. Please see the comments in the source .idl file for more information on using this method.

XBL Bindings

Most XForms control elements have at least two bindings applied to themselves. One is the base binding that implements the core behavior of the XForms control. The other is the implementation binding that adds the host-language specific representation of the XForms control. An example of the latter is the binding that uses a html:input as the anonymous content of an xforms:input element when this element is hosted in a XHTML document.

Our XForms extension uses the following format for file names. The name of the file where base bindings for a control are placed is controlfile.xml. controlfile-xhtml.xml contains the XHTML implementation bindings for the control and controlfile-xul.xml contains the implementation bindings for when this control is hosted in a XUL document. The following list shows where the base bindings for our XForms controls are defined:

  • xforms.xml - contains the base bindings for output, label, trigger, submit, case, message, hint, help, alert, upload and repeat XForms controls.
  • input.xml - contains the base bindings for input, secret and textarea XForms controls.
  • select.xml - contains the base bindings for select and select1 XForms controls (except minimal/default select1 that is hosted in select1.xml file)
  • range.xml - contains the base bindings for the range XForms control.

xforms.xml also defines the few base bindings that are common for all XForms controls. These are:

  • xformswidget-general - defines utility properties and methods common for all XForms controls
  • xformswidget-accessors - defines the methods that are allow the bindings to work with bound instance nodes and the XForms element itself.
  • xformswidget-base - implements nsIXFormsUIWidgets interfaces.

You are free to choose what type of binding you will extend to provide the foundation for your custom control. This will very likely be one of the implementation bindings or one of the base bindings.

Example

A collection of custom control examples can be found on XForms:Custom Controls Examples, and you can also see the blog post "Understanding XForms: Customization".

Here is a complete example that defines a new output control that loads its value as an image. It is bound to <xf:output mediatype="image/*"/> mimicking the current XForms 1.1 draft:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:xf="http://www.w3.org/2002/xforms">
  <head>
    <title>Custom Image Control Sample</title>

    <bindings id="xformsBindings"
	      xmlns="http://www.mozilla.org/xbl"
	      xmlns:html="http://www.w3.org/1999/xhtml">

      <binding id="output-image"
	       extends="chrome://xforms/content/xforms.xml#xformswidget-base">
	<content>
	  <html:div>
	    <html:img anonid="content"/>
	  </html:div>
	</content>

	<implementation implements="nsIXFormsUIWidget">
	  <method name="refresh">
	    <body>
              <!--
                set the src attribute on the html:img to be the simpleContent
                of the instance node bound to this control
              -->
	      var img = document.getAnonymousElementByAttribute(this, "anonid", "content");
	      img.setAttribute("src", this.stringValue);
	      return true;
	    </body>
	  </method>
	</implementation>
      </binding>
    </bindings>

    <xf:model>
      <xf:instance xmlns="">
	<data>
	  <curimg></curimg>
	  <img label="Firefox">http://www.mozilla.com/images/firefox-logo-64x64.png</img>
	  <img label="Thunderbird">http://www.mozilla.com/images/thunderbird-logo-64x64.png</img>
	  <img label="Bugzilla">http://www.mozilla.org/images/p-bugz.gif</img>
	  <img label="Mozilla">http://www.mozilla.org/images/mozhead-80x64.gif</img>
	</data>
      </xf:instance>
    </xf:model>

    <style type="text/css">
      @namespace xf url(http://www.w3.org/2002/xforms);

      xf|output[mediatype="image/*"] {
        -moz-binding: url('#output-image');
      }
    </style>
  </head>
  <body>
    <h1>Custom Control Sample</h1>

    <xf:select1 ref="curimg">
      <xf:label>Select image to display: </xf:label>
      <xf:itemset nodeset="../img">
	<xf:label ref="@label"/>
	<xf:value ref="."/>
      </xf:itemset>
    </xf:select1>

    <xf:output ref="curimg" mediatype="image/*"/>

  </body>
</html>