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 && 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 "<" and ">” should be written as “>”.
February 22nd, 2009 at 11:34 pm
Thanks a lot. We wanted to use && in our proj for enabling some components. This article really helped us … Thanks a lot again
April 15th, 2009 at 12:08 am
Wrong!
check1.selected && check2.selected
==>> check1.selected&&check2.selected
April 15th, 2009 at 4:18 am
wuxi – mind to explain? What’s wrong with the spaces? Both statements are identical.
December 7th, 2009 at 5:13 am
Thanks a ton! i was scratching my head over this
March 3rd, 2010 at 8:37 am
Perfect…just the solution I was looking for.
October 15th, 2010 at 4:57 am
Oops.. You have reduced the head ache. .
Great.. really helps..
January 2nd, 2011 at 3:47 pm
thanks
March 31st, 2011 at 1:33 pm
Thanks buddy.
April 13th, 2011 at 3:53 am
Thanks
April 25th, 2011 at 12:57 pm
Can we use && or in this case &&
more then once. example if we have multiple conditions to be checked and every one has to be return true.
April 25th, 2011 at 1:06 pm
Yes – just try it …
May 30th, 2011 at 10:45 am
Thanks man
June 21st, 2011 at 11:37 am
This is really weird!!!!!!!