Visualforce Development Cookbook
上QQ阅读APP看书,第一时间看更新

Data-driven styling

A useful technique when creating a custom user interface with Visualforce is to conditionally style important pieces of information to draw the user's attention to them as soon as a page is rendered.

Most Visualforce developers are familiar with using merge fields to provide sObject field values to output tags, or to decide if a section of a page should be rendered. In the tag shown below, the merge field, {!account.Name}, will be replaced with the contents of the name field from the account sObject:

<apex:outputField value="{!account.Name}"/>

Merge fields can also contain formula operators and be used to dynamically style data when it is displayed.

In this recipe we will display a table of campaign records and style the campaign cost in green if it was within budget, or red if it was over budget.

How to do it…

  1. Navigate to the Visualforce setup page by clicking on Your Name | Setup | Develop | Pages.
  2. Click on the New button.
  3. Enter ConditionalColour in the Label field.
  4. Accept the default ConditionalColour that is automatically generated for the Name field.
  5. Paste the contents of the ConditionalColour.page file from the code download into the Visualforce Markup area and click on the Save button.
  6. Click on the Save button to save the page.
  7. Navigate to the Visualforce setup page by clicking on Your Name | Setup | Develop | Pages.
  8. Locate the entry for the ConditionalColour page and click on the Security link.
  9. On the resulting page, select which profiles should have access and click on the Save button.

How it works…

Opening the following URL in your browser displays the ConditionalColour page: https://<instance>/apex/ConditionalColour. Here, <instance> is the Salesforce instance specific to your organization, for example, na6.salesforce.com.

A list of campaigns is displayed, with the campaign cost rendered in red or green depending on whether it came in on or over budget.

Conditional styling is applied to the Actual Cost column by comparing the actual cost with the budgeted cost.

<apex:column style="color:
   {!IF(AND(NOT(ISNULL(campaign.ActualCost)), 
   campaign.ActualCost<=campaign.BudgetedCost), 
  "lawngreen", "red")}" value="{!campaign.ActualCost}"/>

See also

  • The Data-driven decimal places recipe in Chapter 2, Custom Components shows how to format numeric values to a specified number of decimal places.