Specifying Relevance Rules

Mark Birbeck's picture

We saw earlier how we can use simple rules to indicate that some data values are required, which allowed us to prevent submission unless the values were present:

    <xf:model>
      .
      .
      .
      <xf:bind nodeset="url" required="true()" />
      <xf:bind nodeset="description" required="true()" />
    </xf:model>

A similar technique is used to say when a form control is relevant or not. For example, if the user indicates that they only want to buy a single train ticket, a rule can be set that stops the return date control from being shown.

To make the relevance of the description field dependent on the presence of a value in the URL item, add the following rule to the bind statements:

      <xf:bind nodeset="url" required="true()" />
      <xf:bind nodeset="description" required="true()" relevant="../url != ''" />
    </xf:model>

This simply says that the item description is only relevant if some data has been entered in the item url--i.e., url is not equal to the empty string.

Note the "../" in front of the reference to url; just as it does when changing directories on your disk-drive, ".." means 'go up a level'. We need to do this because the expressions used in @relevant and @required are calculated relative to the value inside @nodeset; since url sits on the same level as description, then to get to it we must go 'up' from description and then come back down again to get to url.

(We'll go into expressions in more detail in a later tutorial, but the long and the short of it is that if we just used the expression url without "../" then we would be making a reference to some data that was underneath the item description, rather than to data at the same level.)

The rule for extended is slightly longer, since we'll make that depend on both the url and description items having data:

      <xf:bind nodeset="url" required="true()" />
      <xf:bind nodeset="description" required="true()" relevant="../url != ''" />
      <xf:bind nodeset="extended" relevant="../url != '' and ../description != ''" />
    </xf:model>

XForms also allows us to tell our submit button to adopt the relevance properties of some named item. This is useful, since without this we wouldn't be able to show and hide buttons in the same way that we do other controls.

The rule we just created for extended--showing and hiding based on whether url and description have data in them--is ideal for the button that sends the data to del.icio.us, and we can use it as follows:

    <xf:submit submission="sub-add-link" ref="extended">
      <xf:label>Search</xf:label>
    </xf:submit>

Now the button will receive all of the same 'special' properties that the Extended control gets.