Use Simple Variables and Formulas
Learning Objectives
After completing this unit, you’ll be able to:
- Explain what a Visualforce expression is and describe where it’s used.
- List three or more global variables available for use in Visualforce expressions.
- Add a Visualforce expression to a Visualforce page.
- Use a function in a Visualforce expression.
Introduction to Global Variables and Visualforce Expressions
Visualforce pages can display data retrieved from the database or web services, data that changes depending on who is logged on and viewing the page, and so on. This dynamic data is accessed in markup through the use of global variables, calculations, and properties made available by the page’s controller. Together these are described generally as Visualforce expressions. Use expressions for dynamic output or passing values into components by assigning them to attributes.
A Visualforce expression is any set of literal values, variables, sub-expressions, or operators that can be resolved to a single value. Method calls aren’t allowed in expressions.
The expression syntax in Visualforce is: {! expression }
Anything inside the {! }
delimiters is evaluated and dynamically replaced when the page is rendered or when the value is used. Whitespace is ignored.
The resulting value can be a primitive (integer, string, and so on), a Boolean, an sObject, a controller method such as an action method, and other useful results.
Global Variables
Use global variables to access and display system values and resources in your Visualforce markup.
For example, Visualforce provides information about the logged-in user in a global variable called $User
. You can access fields of the $User
global variable (and any others) using an expression of the following form: {! $GlobalName.fieldName }
.
- Open the Developer Console and click File | New | Visualforce Page to create a new Visualforce page. Enter
UserStatus
for the page name.
- In the editor, replace any markup with the following.This markup creates a box, ready for you to add some useful information.
<apex:page> <apex:pageBlock title="User Status"> <apex:pageBlockSection columns="1"> </apex:pageBlockSection> </apex:pageBlock> </apex:page>
- Click Preview to open a preview of your page that you can look at while you make changes.
- Add the following markup between the
<apex:pageBlockSection>
tags:{!$User.FirstName }.
You should see your first name in the User Status panel that you created.
- Add two more expressions that use the
$User
global variable to the markup for the User Status panel so that the page looks like the following.<apex:page> <apex:pageBlock title="User Status"> <apex:pageBlockSection columns="1"> {!$User.FirstName } {!$User.LastName } ({! $User.Username }) </apex:pageBlockSection> </apex:pageBlock> </apex:page>
The {! ... }
tells Visualforce that whatever is within the braces is dynamic and written in the expression language. Its value is calculated and substituted at run time, when someone views the page.
Visualforce expressions are case-insensitive, and spaces within the {! ... }
are ignored. So these expressions all produce the same value:
{!$User.FirstName}
{!$USER.FIRSTNAME}
{!$user.firstname }
Formula Expressions
Visualforce lets you use more than just global variables in the expression language. It also supports formulas that let you manipulate values.
For example, the &
character is the formula language operator that concatenates strings.
- In your UserStatus page, replace the separate expressions for the first and last name with the following formula expression. This expression combines the logged in user’s first name and last name, separating them with a space. The output should look identical.
{!$User.FirstName & ' ' & $User.LastName}
- Add the following to the page markup, below the user information.
<p> Next week it will be {! TODAY() + 7 } </p> <p> Today's Date is {! TODAY() } </p>
These are more complex formulas that use the TODAY()
function. Functions are built-in calculations that you can identify by the parenthesis after their name.The first expression simply calculates the current date, and the second uses the addition operator to add seven days to the date. The output in your page will look something like this.
Next week it will be Thu Sep 25 00:00:00 GMT 2014. Today's Date is Thu Sep 18 00:00:00 GMT 2014
- Add the following to the page markup, below the date expressions.
<p>Tomorrow will be day number {! DAY(TODAY() + 1) }</p> <p>Let's find a maximum: {! MAX(1,2,3,4,5,6,5,4,3,2,1) } </p> <p>The square root of 49 is {! SQRT(49) }</p> <p>Is it true? {! CONTAINS('salesforce.com', 'force.com') }</p> <p>The year today is {! YEAR(TODAY()) }</p>
Some functions, like TODAY()
, have empty parenthesis, but some take parameters, values that you want the function to use to do its calculation. In this example, YEAR()
takes a date parameter, which is provided by the TODAY()
function, which takes no parameters. The MAX()
function can take any number of parameters. The CONTAINS()
function is especially interesting. It returns a Boolean value: something that is either true or false. It compares two arguments of text and returns true if the first argument contains the second argument. If not, it returns false. In this case, the string “force.com”
is contained within the string “salesforce.com”
, so it returns true
.
Conditional Expressions
Use a conditional expression to display different information based on the value of the expression.
For example, if an invoice has no line items, you might want to display the word “none” instead of an empty list. Or if an item has expired, you might want to display “Ended” instead of showing the ending date and time.
You can do this in Visualforce by using a conditional formula expression, such as IF()
. The IF()
expression takes three arguments:
- The first is a Boolean: something that is either true or false. For example, the
CONTAINS()
function, which you used earlier.
- The second argument is the value that will be returned if the first parameter is true.
- The third argument is the value that will be returned if the first parameter is false.
- In your
UserStatus
page, below the other expressions, add the following code.<p>{! IF( CONTAINS('salesforce.com','force.com'), 'Yep', 'Nope') }</p> <p>{! IF( DAY(TODAY()) < 15, 'Before the 15th', 'The 15th or after') }</p>
Before you save your changes and look at the results, try to predict what they will be. The results on your page will be something like this.
The first expression uses the same CONTAINS()
function calculation as before. What’s different is that the IF()
function converts the Boolean result of CONTAINS()
into text more useful for displaying to the user. Similarly, the second expression shows one message during the first half of the month, and a different message the second half of the month.
- Delete all of your test expressions, leaving only the lines that use the
$User
global variable. In other words, back to this page.<apex:page> <apex:pageBlock title="User Status"> <apex:pageBlockSection columns="1"> {!$User.FirstName & ' ' & $User.LastName } ({! $User.Username }) </apex:pageBlockSection> </apex:pageBlock> </apex:page>
- Let’s use a conditional expression to do something a little more useful. Replace the line with the
$User.Username
expression with the following code:
({! IF($User.isActive, $User.Username, 'inactive') })
isActive
is another field available on the $User
global variable. It’s a Boolean field that’s true if the user is active, and false if they’ve been deactivated. Now the User Status panel will show the user’s username if they’re active, and “inactive” if they’re not.
Tell Me More...
There are many global variables and functions that you can use in Visualforce expressions.
There are nearly two dozen global variables that can be used within Visualforce. They’re useful for getting information about the currently logged in user, as you saw, but also for getting details about the organization ( $Organization
), settings ( $Setup
), details about custom objects ( $ObjectType
), actions available on those objects ( $Action
), and so on. See the Global Variables in the Visualforce Developer Guide to dive in.
Similarly, there are dozens of functions that can be used in Visualforce. The list is similar to, but not quite the same, as the functions available in formula fields. Where they overlap the functions behave the same, so you can reuse most of what you know about formula fields when you write Visualforce expressions. See Functions in the Visualforce Developer Guide for a complete list.
Expressions have many uses, and are often used to provide values for attributes on Visualforce components.
Resources
-
Salesforce Help: Global Variables
-
Salesforce Help: Elements of a Formula
-
Visualforce Developer Guide: Global Variables
-
Visualforce Developer Guide: Functions
-
Visualforce Developer Guide: Expression Operators
-
Trailhead: Formulas & Validations