Using Group to Set Evaluation Context

Mark Birbeck's picture

Next we'll move the error message and repeat into the "Done" case. However, as we do we'll make a slight modification; you probably noticed that the XPath expressions in output and repeat both begin with a call to the instance function:

<xf:output ref="instance('inst-rs')/err/@msg">
  <xf:label>Error:</xf:label>
</xf:output>
<xf:repeat nodeset="instance('inst-rs')/photos/photo">
  ...
</xf:repeat>

You may have wondered if it was possible to factor this out, and set a common context for both expressions, and it is.

Although groups can be used simply to establish a common area for a set of controls, another use for them is to set an evaluation context for a whole set of XPath expressions. This makes them not only easier to type but also to maintain, since if the data source changes it is easier to move controls around if their expressions are shorter.

For example, if you had an address item that had further items nested underneath, for street, city, country, and so on, you could set the context to be the address item, and then the expressions for each of the contained controls would be shorter.

To illustrate this, as we move the controls into the "Done" case we'll add a group to set context:

        <xf:case id="case-done">
          <xf:group ref="instance('inst-rs')">
            <xf:output ref="err/@msg">
              <xf:label>Error:</xf:label>
            </xf:output>
            <xf:repeat nodeset="photos/photo">
              <xf:output
               value="concat('
                &lt;img src=&#34;http://static.flickr.com/',
                @server, '/',
                @id, '_',
                @secret, '_s.jpg&#34; /&gt;'
               )"
               class="image"
              />
            </xf:repeat>
          </xf:group>
        </xf:case>

Setting the context won't have any effect on the way the form works, but moving everything into the "Done" case has; if you reload your saved form and click on "Find", any previous search results will be hidden, replaced by the 'in progress' animation, and once the search is complete, the "Done" state will be toggled in (showing either the images or an error message).