Red Argyle Logo

Patterns
The Salesforce Blog with Tailored Goodness

Defaulting Attribute Values in a Visualforce Component without a Controller

I made a minor discovery on my flight to Dreamforce. In my effort to write as little Apex code as possible, I found a handy approach to defaulting the attributes in a Visualforce Component without having to resort to using a controller.

Here’s a (kinda useless) component to help explain:
<apex:component>
<apex:attribute name="favoriteColor" type="String" description="What... is your favorite color?"default="Red" />
<apex:variable var="v_favoriteColor" value="{!IF(NOT(ISNULL(favoriteColor)), favoriteColor, 'No - Blue - ahh!')}" />
</apex:component>

First, I defined an attribute called favoriteColor. I specified the default value as “Red”, but as any scorned VF component developer has learned, this value doesn’t actually assign a default value, it just indicates what the value will be. In the past, this is where the Apex controller on the component had to come in to default the value as I prescribed in the attribute definition.

The <apex:variable /> definition is where we default the value. We use a IF-NOT-ISNULL formula combo to check if a value has been assigned to our attribute when implemented in a VF page, and if not, we default the value as our “else” case in the formula.

Yahoo! No controller equals fewer lines of code coverage needed.

Note that the “var” property of the variable definition is unique to the “name” property of the attribute definition. I had these set to the same value initially, which led to some headscratching results. Moral of the story: keep the names unique.