LaceySnr.com - Salesforce Development Posts by Matt Lacey

Curious Logic — A VisualForce Function Oddity

Posted: 2011-11-30

Today's quirk is something I've stumbled into a few times, and although I recognise it as soon as I see it these days, it still puts a smile on my face.

There's a few VisualForce functions, which on the face of it, return a boolean value: one of these happens to be CONTAINS(), and it's explained in the documentation to do just that:


See? Right there: returns TRUE if the first argument contains the second argument. If not, returns FALSE.

I've quoted that in addition to the screenshot just to make sure it's nice and clear. So, what is the point that I have as of yet failed to get to? Well here it is: If you simply use this function inside of a rendered="" attribute, it won't work. Example:

<apex:variable var="v" value="" rendered="{!CONTAINS(myStrVar, 'boris')}">
  Hello, World!
</apex:variable>

Regardless of the contents of myStrVar, the text "Hello, World!" will always find it's way onto the screen. There is a simple fix for this, and it is this that I find most amusing, because all you have to do is wrap it in an IF() function, returning either true or false as shown below.

<apex:variable var="v" value="" rendered="{!IF(CONTAINS(myStrVar, 'boris'), true, false)}">
  Hello, World!
</apex:variable>

Written like this, the code will work as expected. I'm sure there must be a reason for this behaviour, and I'm sure someone would love to explain it with a serious face, but frankly I'd prefer not to know the details and just keep the switch in the "more magic" position.