#define for Visualforce - One way to help debug pages
Coming from a C background (it's still my favourite language for coding in) I'm used to the idea of having #define
statements at the top of my source files so that I can quickly switch on and off different areas of functionality quickly and easily; for those unfamiliar with C and it's derivatives they essentially work like constant variables but actually modify the code before compilation (by the C preprocessor). For example I might have
#define DEBUG_TEST (1)
at the top, then around multiple blocks of code I want to toggle I use something like the following (In C, 0 is false and any other value equates to true):
if (DEBUG_TEST){ // code to enable or disable}
So I can toggle multiple pieces of code simply by changing the (1) for a (0). I wanted to make use of this idea in a Visualforce page recently, allowing me to toggle the rendering and disabling of various components with just one change at the top. I figured <apex:variable>
would come in handy and just wrapped my page as so:
<apex:variable var="debug" value="true:"><!-- page stuff--></apex:variable>
However, when I tried to use this value in a statement it told me that it was a text value and thus couldn't be used in a boolean operation (I was trying to do disabled="{!debug}"
), I had a go at doing value="{!true}"
but that also didn't work, so the solution I came up with?
<apex:variable var="debug" value="{!IF(true, true, false)}">
This works like a charm and now I can simply toggle the first true
to switch on/off a whole bunch of functionality in the page—there might be a more direct way of setting a variable to true
or false
but this was the first one I found that worked and so my investigations stopped there!