Oct 3 2008

Flex tip: conditions like ‘&&’ in MXML

Consider the following little MXML snippet:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
        <mx:VBox x="0" y="0" height="100%" width="100%">
                <mx:CheckBox label="Checkbox 1" id="check1"/>
                <mx:CheckBox label="Checkbox 2" id="check2"/>
                <mx:Label text="{check1.selected && check2.selected?
                        'Both checked':
                        'Not both checked'}"/>
        </mx:VBox>
</mx:Application>

We want to show the string “Both checked” in the label, if both of the checkboxes are checked, otherwise the label should show “Not both checked”. When you use the above code in Flex, it will show you the error: “The entity name must immediately follow the ‘&’ in the entity reference.”. It is complaining about the line where the “&&” appears.

MXML files are treated as XML files and as such the parser expects to see a symbol name after the “&” character. Hence the error message.

With this in mind, we can convince Flex Builder and the mxml-compiler to still use “&&” as a condition, by properly escaping them, as in:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
        <mx:VBox x="0" y="0" height="100%" width="100%">
                <mx:CheckBox label="Checkbox 1" id="check1"/>
                <mx:CheckBox label="Checkbox 2" id="check2"/>
                <mx:Label text="{check1.selected &amp;&amp; check2.selected?
                        'Both checked':
                        'Not both checked'}"/>
        </mx:VBox>
</mx:Application>

The above may look weird in the editor, but it compiles cleanly and does what one would expect.

The same applies to other operators: “< " should be written as "&lt;" and ">” should be written as “&gt;”.

20 Responses to “Flex tip: conditions like ‘&&’ in MXML”

Leave a Reply