Conditional Image Swapping in a Data View

One of the cooler uses for Conditional Formatting is to to dynamically swap between a set of icons/images, e.g. imagine a scenario where you want a red, yellow or green light based on how a sales department is tracking to budget. Although it's possible to build this kinda of view with the Conditional Formatting feature, it's a bit of a pain since you not only need to define the conditional to "show content", but also all the conditions when not to show the content. If you are swapping 3 or less images, you can get buy. However, since the number of total conditions grows exponentially with each image, it soon becomes untenable. Fortunately, the Data View is built on XSLT, which has a command exactly for this specific problem, and though we don't have UI to automatically create the right XSLT, it super easy to go into code view and made the change yourself.

Quick Example: Imagine you have a Data View of products, where each product comes from a different county. The default view works, but it's a little on the boring side. It's also difficult to scan and quickly see which products come from which country.

A nice little improvement would be to show the country flag instead of the name of the country.

The first step to building this view is to drag one of the flag images into your view and use "Show Content" Conditional Formatting to only show the flag when it matches the country of origin. In this case, I'll start with the Canadian products.

Next, you need to jump to code view and search for the XSLT that defines this conditional formatting: <xsl:if test="@country = 'Canada'">.

Instead of using <xsl:if>, XSLT supports a tag called <xsl:choose>, which is exactly for the scenario of choosing among multiple options. <xsl:choose> is analogous to the C# Switch construct. To use <xsl:choose>, first wrap the existing <xsl:if> block with an <xsl:choose> tag. Next, change the word if to when,, as shown here:

The last thing to do is add one <xsl:when> block for each of the possible images, like so:

That's it. When you switch back to design view, you should see the following:

Note: you can also finish your choose block with an <xsl:otherwise> block to define an "else" condition, i.e. when no condition matches.