Quick "enabled=" Flex Trick

When you want to disable a control based on a bindable variable in your application you usually use this method:

[Bindable]
private var active:Boolean = true;

<mx:Button label=”MyButton” enabled=”{active}” />

But what happens if you want to use two variables in the enabled field and both must be true in order for the control to be enabled?  Logically you would probably do this:

[Bindable]
private var active1:Boolean = true;

[Bindable]
private var active2:Boolean = true;

<mx:Button label=”MyButton” enabled=”{active1 &&  active2}” />

However, that produces this error “The entity name must immediately follow the ‘&’ in the entity reference.”    This is kind of odd because you can use the || operator in the same instance without any errors:

<mx:Button label=”MyButton” enabled=”{active1 || active2}” />

You could solve this two ways, the first is to create a function call within the enabled filed that passes the variables to the function and returns a Boolean value.  However, Lar gave me a good suggestion for doing it within the enabled field:

[Bindable]
private var active1:Boolean = true;

[Bindable]
private var active2:Boolean = true;

<mx:Button label=”MyButton” enabled=”{(active1) ? (active2):false}” />

This evaluates both variables and also allows you to expand it out so you can keep evaluating a number of variables in the same line.   I think this is a good work around.   I think that using the && operator should just work, or at least work if you wrap it within () inside the enabled field, but the issue seems to be related to a type of XML validation error. This makes since because MXML is really XML in a way.   The && works fine within functions because this is handled within the <mx:Script> tag.    You can actually change the && to &amp;&amp; and it will work as well:

<mx:Button label=”MyButton” enabled=”{(active1) &amp;&amp; (active2)}” />

I couldn’t find any specific Flex information on this error, so if anyone has any other insight, pass it on.

13 Comments

  1. I use De Morgan’s law to solve this. So for example:

    enabled=”{!((!active1) || (!active2))}”

    I admit the readability isn’t great, but it amuses me to no end.

  2. That’s tight shit right there. I like it. I understand why it doesn’t accept && but I still think it should accept it, that or not accept ||. At least to be consistent…

  3. I’ve had && work in some MXML and not in others. Can’t nail it down to anything except strict XML parsing. I like your solution though.

Comments are closed.