0% found this document useful (0 votes)
434 views753 pages

Salesforce Visualforce Pages Developers Guide-Nov-2016

The official Salesforce Visualforce developer's guide. Nov 2016.

Uploaded by

sanjay_scribed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
434 views753 pages

Salesforce Visualforce Pages Developers Guide-Nov-2016

The official Salesforce Visualforce developer's guide. Nov 2016.

Uploaded by

sanjay_scribed
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Visualforce Developer Guide

Version 38.0, Winter 17

@salesforcedocs
Last updated: November 23, 2016

Copyright 20002016 [Link], inc. All rights reserved. Salesforce is a registered trademark of [Link], inc.,

as are other names and marks. Other marks appearing herein may be trademarks of their respective owners.

CONTENTS
Chapter 1: Introducing Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What is Visualforce? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Which Editions Support Visualforce? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Which Permissions are Required for Visualforce Development? . . . . . . . . . . . . . . . . . . . . . . . 4
How is Visualforce Architected? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
What are the Benefits of Visualforce? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
When Should I Use Visualforce? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
How Do Visualforce Pages Compare to S-Controls? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
How is Visualforce Versioned? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Whats New in Visualforce Version 38.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Documentation Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Chapter 2: Tools for Visualforce Development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12


Using the Development Mode Footer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
About the Visualforce Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14

Chapter 3: Getting a Quick Start with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16


Compiling Visualforce Successfully . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Creating Your First Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Displaying Field Values with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Using the Visualforce Component Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Overriding an Existing Page with a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Redirecting to a Standard Object List Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Using Input Components in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Adding and Customizing Input Field Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Setting the Tab Order for Fields in a Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
Adding Dependent Fields to a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Creating Visualforce Dashboard Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Displaying Related Lists for Custom Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Enabling Inline Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Converting a Page to a PDF File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Building a Table of Data in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Editing a Table of Data in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Using Query String Parameters in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Getting Query String Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Setting Query String Parameters in Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Getting and Setting Query String Parameters on a Single Page . . . . . . . . . . . . . . . . . . . 41
Using Ajax in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Implementing Partial Page Updates with Command Links and Buttons . . . . . . . . . . . . . 42

Contents

Providing Status for Asynchronous Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43


Applying Ajax Behavior to Events on Any Component . . . . . . . . . . . . . . . . . . . . . . . . . 44

Chapter 4: Customizing the Appearance and Output of Visualforce Pages . . . . . . . . 46


Styling Visualforce Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Using Salesforce Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Extending Salesforce Styles with Stylesheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Using Custom Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
Suppressing the Salesforce User Interface and Styles . . . . . . . . . . . . . . . . . . . . . . . . . 48
Defining Styles for a Components DOM ID . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Using Styles from Salesforce Stylesheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Identifying the Salesforce Style Your Users See . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
HTML Comments and IE Conditional Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
HTML Tags Added or Modified by Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Relaxed Tidying for the HTML5 Doctype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Manually Override Automatic <html> and <body> Tag Generation . . . . . . . . . . . . . . . 52
Creating an Empty HTML5 Container Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Using a Custom Doctype . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Using a Custom ContentType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
Setting Custom HTML Attributes on Visualforce Components . . . . . . . . . . . . . . . . . . . . . . . . 56
Offline Caching Using the HTML5 manifest Attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Render a Visualforce Page as a PDF File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Add a Save as PDF Feature to a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Render a Visualforce Page as PDF from Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Fonts Available When Using Visualforce PDF Rendering . . . . . . . . . . . . . . . . . . . . . . . 68
Visualforce PDF Rendering Considerations and Limitations . . . . . . . . . . . . . . . . . . . . . 70
Component Behavior When Rendered as PDF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Chapter 5: Standard Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74


Associating a Standard Controller with a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . 74
Accessing Data with a Standard Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
Using Standard Controller Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Validation Rules and Standard Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Styling Pages that Use Standard Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Checking for Object Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

Chapter 6: Standard List Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79


Associating a Standard List Controller with a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . 79
Accessing Data with List Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Using Standard List Controller Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Pagination with a List Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Using List Views with Standard List Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Editing Records with List Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

Chapter 7: Custom Controllers and Controller Extensions . . . . . . . . . . . . . . . . . . . . . 86

Contents

What are Custom Controllers and Controller Extensions? . . . . . . . . . . . . . . . . . . . . . . . . . . 86


Building a Custom Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Building a Controller Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Building a Custom List Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Controller Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
Controller Class Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
Working with Large Sets of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Setting Read-Only Mode for an Entire Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Setting Read-Only Mode for Controller Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
Considerations for Creating Custom Controllers and Controller Extensions . . . . . . . . . . . . . . 97
Order of Execution in a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Order of Execution for Visualforce Page Get Requests . . . . . . . . . . . . . . . . . . . . . . . . . 99
Order of Execution for Visualforce Page Postback Requests . . . . . . . . . . . . . . . . . . . . . 101
Examples of Visualforce Page Execution Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Testing Custom Controllers and Controller Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Validation Rules and Custom Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Using the transient Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

Chapter 8: Advanced Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116


Creating Your First Custom Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Creating a Custom Controller Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
Defining Getter Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Defining Action Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Defining Navigation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Creating a Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Advanced Visualforce Dashboard Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
Integrating Visualforce and Google Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131
Mass-Updating Records with a Custom List Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . 136

Chapter 9: Overriding Buttons, Links, and Tabs with Visualforce . . . . . . . . . . . . . . . . 139


Overriding Tabs Using a Standard List Controller . . . . . . .
Defining Custom Buttons and Links for Visualforce . . . . . .
Adding Custom List Buttons using Standard List Controllers
Displaying Record Types . . . . . . . . . . . . . . . . . . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

140
140
142
144

Chapter 10: Using Static Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145


Creating a Static Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Referencing a Static Resource in Visualforce Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

Chapter 11: Creating and Using Custom Components . . . . . . . . . . . . . . . . . . . . . . . 148


What are Custom Components? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
Defining Custom Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Custom Component Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Using Custom Components in a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
Managing Version Settings for Custom Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151

Contents

Custom Component Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 151


Custom Component Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153

Chapter 12: Dynamic Visualforce Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155


Using Dynamic References with Standard Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Using Dynamic References with Custom Objects and Packages . . . . . . . . . . . . . . . . . . . . . 165
Referencing Apex Maps and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
Working with Field Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
Dynamic References to Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
Dynamic References to Static Resources Using $Resource . . . . . . . . . . . . . . . . . . . . . 173
Dynamic References to Action Methods Using $Action . . . . . . . . . . . . . . . . . . . . . . . . 176
Dynamic References to Schema Details Using $ObjectType . . . . . . . . . . . . . . . . . . . . 178

Chapter 13: Dynamic Visualforce Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182


Dynamic Components Restrictions . . . . . . . . . .
Creating and Displaying Dynamic Components .
Deferred Creation of Dynamic Components . . .
Example Using a Related List . . . . . . . . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

182
183
186
188

Chapter 14: Integrating Email with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194


Sending an Email with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Creating a Custom Controller with the Messaging Class . . . . . . . . . . . . . . . . . . . . . . 194
Creating an Email Attachment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Visualforce Email Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Creating a Visualforce Email Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202
Using a Custom Stylesheet in a Visualforce Email Template . . . . . . . . . . . . . . . . . . . . 204
Adding Attachments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 207
Using Custom Controllers within Visualforce Email Templates . . . . . . . . . . . . . . . . . . . 211

Chapter 15: Visualforce Charting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213


Visualforce Charting Limitations and Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
How Visualforce Charting Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
A Simple Charting Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
Providing Chart Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
Building a Complex Chart with Visualforce Charting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Updating Charts with Refreshed Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Refreshing Chart Data Using <apex:actionSupport> . . . . . . . . . . . . . . . . . . . . . . . . . 224
Refreshing Chart Data Using JavaScript Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Controlling the Appearance of Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Chart Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231
Chart Layout and Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233
Other Linear Series Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Gauge Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238

Contents

Radar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

Chapter 16: Creating Maps with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241


Creating Basic Maps . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Adding Location Markers to a Map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Using Custom Marker Icons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
Adding Info Windows to Markers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
Example of Building Map Data in Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

Chapter 17: Render Flows with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253


Embed Flows in Visualforce Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254
An Advanced Example of Using <flow:interview> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
Set Flow Variable Values from a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
Get Flow Variable Values to a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Control Whether Users Can Pause a Flow from a Visualforce Page . . . . . . . . . . . . . . . . . . 263
Customize How Users Resume Paused Flow Interviews . . . . . . . . . . . . . . . . . . . . . . . . . . 264
Configure the finishLocation Attribute in a Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Customize a Flows User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266

Chapter 18: Templating with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269


Defining Templates with <apex:composition> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Referencing an Existing Page with <apex:include> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273

Chapter 19: Developing for Mobile Devices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275


What is Salesforce Classic Mobile? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
Developing Pages for iPhone and BlackBerry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
iPhone Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
BlackBerry Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Developing Cross-Platform Compatible Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
Using the JavaScript Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
Mobilizing Visualforce Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Building a Visualforce Tab For Use in Salesforce Classic Mobile . . . . . . . . . . . . . . . . . 286
Adding Visualforce Tabs to Mobile Configurations . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Testing Visualforce Mobile Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
Example: Building a Mapping Application for iPhone . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
Creating the Custom Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
Building the Map and List View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
Building the Detail Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295

Chapter 20: Adding Visualforce to a [Link] AppExchange App . . . . . . . . . . . . . 297


Managing Package Version Settings for Visualforce Pages and Components . . . . . . . . . . . 298

Chapter 21: Using JavaScript in Visualforce Pages . . . . . . . . . . . . . . . . . . . . . . . . . . 299


Using $Component to Reference Components from JavaScript . . . . . . . . . . . . . . . . . . . . . 299
Using JavaScript Libraries with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300

Contents

JavaScript Remoting for Apex Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301


What Is JavaScript Remoting? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 301
When to Use JavaScript Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Adding JavaScript Remoting to a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . 303
Declaring a Remote Method in Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Handling the Remote Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
Debugging JavaScript Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
JavaScript Remoting Limits and Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
JavaScript Remoting Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Visualforce Remote Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
A Simple Example of Remote Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312
Using Remote Objects in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
An Example of Using Remote Objects with jQuery Mobile . . . . . . . . . . . . . . . . . . . . . 329
Best Practices for Using Remote Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
Remote Objects Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336

Chapter 22: Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337


Best Practices for Improving Visualforce Performance . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
Best Practices for Accessing Component IDs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
Best Practices for Static Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
Best Practices for Controllers and Controller Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . 342
Best Practices for Using Component Facets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
Best Practices for Page Block Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Best Practices for Rendering PDF Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
Best Practices for <apex:panelbar> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346

Chapter 23: Standard Component Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347


analytics:reportChart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
apex:actionFunction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
apex:actionPoller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
apex:actionRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
apex:actionStatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
apex:actionSupport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
apex:areaSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
apex:attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
apex:axis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
apex:barSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
apex:canvasApp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
apex:chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
apex:chartLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
apex:chartTips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
apex:column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
apex:commandButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
apex:commandLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385

Contents

apex:component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
apex:componentBody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
apex:composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
apex:dataList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
apex:dataTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
apex:define . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
apex:detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
apex:dynamicComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
apex:emailPublisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
apex:enhancedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
apex:facet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
apex:flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
apex:form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
apex:gaugeSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
apex:iframe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
apex:image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
apex:include . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
apex:includeLightning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
apex:includeScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
apex:inlineEditSupport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
apex:input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
apex:inputCheckbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
apex:inputField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
apex:inputFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
apex:inputHidden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
apex:inputSecret . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
apex:inputText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
apex:inputTextarea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
apex:insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
apex:legend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
apex:lineSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
apex:listViews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
apex:logCallPublisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
apex:map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
apex:mapInfoWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
apex:mapMarker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
apex:message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
apex:messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
apex:milestoneTracker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
apex:outputField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
apex:outputLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
apex:outputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
apex:outputPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
apex:outputText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473

Contents

apex:page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
apex:pageBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
apex:pageBlockButtons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
apex:pageBlockSection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
apex:pageBlockSectionItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
apex:pageBlockTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
apex:pageMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
apex:pageMessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
apex:panelBar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
apex:panelBarItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
apex:panelGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
apex:panelGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
apex:param . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
apex:pieSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
apex:radarSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
apex:relatedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
apex:remoteObjectField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
apex:remoteObjectModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
apex:remoteObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
apex:repeat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
apex:scatterSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
apex:scontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
apex:sectionHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
apex:selectCheckboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
apex:selectList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
apex:selectOption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
apex:selectOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
apex:selectRadio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
apex:stylesheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
apex:tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
apex:tabPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
apex:toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
apex:toolbarGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
apex:variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
apex:vote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
chatter:feed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
chatter:feedWithFollowers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
chatter:follow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
chatter:followers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
chatter:newsfeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
chatter:userPhotoUpload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
chatteranswers:aboutme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
chatteranswers:allfeeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
chatteranswers:changepassword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557

Contents

chatteranswers:datacategoryfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
chatteranswers:feedfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
chatteranswers:feeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
chatteranswers:forgotpassword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
chatteranswers:forgotpasswordconfirm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
chatteranswers:guestsignin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
chatteranswers:help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
chatteranswers:login . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
chatteranswers:registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
chatteranswers:searchask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
chatteranswers:singleitemfeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
flow:interview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
ideas:detailOutputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
ideas:listOutputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
ideas:profileListOutputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
knowledge:articleCaseToolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
knowledge:articleList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
knowledge:articleRendererToolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
knowledge:articleTypeList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
knowledge:categoryList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
liveAgent:clientChat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
liveAgent:clientChatAlertMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
liveAgent:clientChatCancelButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
liveAgent:clientChatEndButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
liveAgent:clientChatFileTransfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
liveAgent:clientChatInput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
liveAgent:clientChatLog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
liveAgent:clientChatLogAlertMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
liveAgent:clientChatMessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
liveAgent:clientChatQueuePosition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
liveAgent:clientChatSaveButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
liveAgent:clientChatSendButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
liveAgent:clientChatStatusMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
messaging:attachment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
messaging:emailHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
messaging:emailTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
messaging:htmlEmailBody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
messaging:plainTextEmailBody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
site:googleAnalyticsTracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
site:previewAsAdmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
social:profileViewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
support:caseArticles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
support:caseFeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
support:caseUnifiedFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595

Contents

support:clickToDial . .
support:portalPublisher
topics:widget . . . . . .
wave:dashboard . . .

APPENDICES

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602

Appendix A: Global Variables, Functions, and Expression Operators . . . 602


Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
$Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
$Api . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
$[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 612
$Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 613
$ComponentLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
$CurrentPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
$FieldSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
$Label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
$[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 615
$Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
$ObjectType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
$Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
$Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
$Permission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
$Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
$Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 625
$SControl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
$Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 626
$Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
$[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
$User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
$[Link] and $[Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
$UserRole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
Expression Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644

Appendix B: Security Tips for Apex and Visualforce Development . . . . . 647


Cross Site Scripting (XSS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
Unescaped Output and Formulas in Visualforce Pages . . . . . . . . . . . . . . . . . . . . . . . . . . 649
Cross-Site Request Forgery (CSRF) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
SOQL Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
Data Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653

Appendix C: Apex Classes Used in Visualforce Controllers . . . . . . . . . . . 654


ApexPages Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655

Contents

ApexPages Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655


Action Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
Action Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
Action Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 659
Cookie Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
Cookie Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
Cookie Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
IdeaStandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
IdeaStandardController Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
IdeaStandardSetController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
IdeaStandardSetController Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
KnowledgeArticleVersionStandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
KnowledgeArticleVersionStandardController Constructors . . . . . . . . . . . . . . . . . . . . . 672
KnowledgeArticleVersionStandardController Methods . . . . . . . . . . . . . . . . . . . . . . . 673
Message Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
Message Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675
Message Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676
PageReference Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 678
PageReference Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
PageReference Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
SelectOption Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
SelectOption Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689
SelectOption Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690
StandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
StandardController Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
StandardController Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
StandardSetController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
StandardSetController Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
StandardSetController Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701

Appendix D: Execution Governors and Limits . . . . . . . . . . . . . . . . . . . . . . . 709


GLOSSARY
INDEX

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726

CHAPTER 1

Introducing Visualforce

Over the past several years, Salesforce has created a comprehensive platform for building on-demand applications. Like other sophisticated
application development platforms, the [Link] platform offers separate tools for defining:
The structure of the datathat is, the data model
The rules that detail how that data can be manipulatedthat is, the business logic
The layouts that specify how that data should be displayedthat is, the user interface
Note: Splitting up application development tools based on whether they affect the data model, business logic, or user interface
is also known as the Model-View-Controller (MVC) application development patternthe Model is the data model, the View is
the user interface, and the Controller is the business logic.
While the tools for building the data model and business logic for applications are powerful solutions that run natively on [Link]
platform servers, the existing tools for defining user interfaces have had certain limitations:
Page layouts, the point-and-click tool that allows application developers to organize fields, buttons, and related lists on record
detail pages, do not provide much flexibility in how sets of information are displayed. Fields must always appear above related lists,
buttons must always appear above fields, and s-controls and custom links can only be placed in particular areas.
S-controls, the tool that allows application developers to display custom HTML in a detail page or custom tab, provide more flexibility
than page layouts, but:
Execute from within a browser, causing poor performance if displaying or updating values from more than a few records at a
time
Do not provide an easy way to give custom user interface elements the same look-and-feel as standard Salesforce pages
Require developers to enforce field uniqueness and other metadata dependencies on their own
Important: Visualforce pages supersede s-controls. Organizations that havent previously used s-controls cant create them.
Existing s-controls are unaffected, and can still be edited.
For these reasons, Salesforce has introduced Visualforce, the next-generation solution for building sophisticated custom user interfaces
on the [Link] platform.
SEE ALSO:
How is Visualforce Architected?
What are the Benefits of Visualforce?
Which Editions Support Visualforce?
How Do Visualforce Pages Compare to S-Controls?
What is Visualforce?
Whats New in Visualforce Version 38.0

Introducing Visualforce

What is Visualforce?

What is Visualforce?
Visualforce is a framework that allows developers to build sophisticated, custom user interfaces that can be hosted natively on the
[Link] platform. The Visualforce framework includes a tag-based markup language, similar to HTML, and a set of server-side standard
controllers that make basic database operations, such as queries and saves, very simple to perform.
In the Visualforce markup language, each Visualforce tag corresponds to a coarse or fine-grained user interface component, such as a
section of a page, a related list, or a field. The behavior of Visualforce components can either be controlled by the same logic that is used
in standard Salesforce pages, or developers can associate their own logic with a controller class written in Apex.
Sample of Visualforce Components and their Corresponding Tags

What is a Visualforce Page?


Developers can use Visualforce to create a Visualforce page definition. A page definition consists of two primary elements:
Visualforce markup
A Visualforce controller

Visualforce Markup
Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code embedded within a single
<apex:page> tag. The markup defines the user interface components that should be included on the page, and the way they should
appear.

Visualforce Controllers
A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified in associated
Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that should be displayed in a
page, and can modify component behavior.
A developer can either use a standard controller provided by the [Link] platform, or add custom controller logic with a class written
in Apex:
A standard controller consists of the same functionality and logic that is used for a standard Salesforce page. For example, if you use
the standard Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as clicking Save on a
standard Account edit page.

Introducing Visualforce

Which Editions Support Visualforce?

If you use a standard controller on a page and the user doesn't have access to the object, the page will display an insufficient privileges
error message. You can avoid this by checking the user's accessibility for an object and displaying components appropriately.
A standard list controller enables you to create Visualforce pages that can display or act on a set of records. Examples of existing
Salesforce pages that work with a set of records include list pages, related lists, and mass action pages.
A custom controller is a class written in Apex that implements all of a page's logic, without leveraging a standard controller. If you
use a custom controller, you can define new navigation elements or behaviors, but you must also reimplement any functionality
that was already provided in a standard controller.
Like other Apex classes, custom controllers execute entirely in system mode, in which the object and field-level permissions of the
current user are ignored. You can specify whether a user can execute methods in a custom controller based on the user's profile.
A controller extension is a class written in Apex that adds to or overrides behavior in a standard or custom controller. Extensions
allow you to leverage the functionality of another controller while adding your own custom logic.
Because standard controllers execute in user mode, in which the permissions, field-level security, and sharing rules of the current
user are enforced, extending a standard controller allows you to build a Visualforce page that respects user permissions. Although
the extension class executes in system mode, the standard controller executes in user mode. As with custom controllers, you can
specify whether a user can execute methods in a controller extension based on the user's profile.
Note: Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions
and field-level security, you can choose whether they respect a user's organization-wide defaults, role hierarchy, and sharing rules
by using the with sharing keywords in the class definition. For information, see Using the with sharing or without
sharing Keywords in the Apex Developer Guide.

Where Can Visualforce Pages Be Used?


Developers can use Visualforce pages to:
Override standard buttons, such as the New button for accounts, or the Edit button for contacts
Override tab overview pages, such as the Accounts tab home page
Define custom tabs
Embed components in detail page layouts
Create dashboard components or custom help pages
Customize, extend, or integrate the sidebars in the Salesforce console (custom console components)
Add menu items, actions, and mobile cards in Salesforce1
SEE ALSO:
Building a Custom Controller
Building a Controller Extension

Which Editions Support Visualforce?


Visualforce is available in Contact Manager, Group, Professional, Enterprise, Unlimited, Performance, and Developer Editions.

Introducing Visualforce

Which Permissions are Required for Visualforce Development?

Which Permissions are Required for Visualforce Development?


Visualforce development requires various permissions, depending on the specific activity.
User Permissions Needed
To enable Visualforce development mode:

Customize Application

To create, edit, or delete Visualforce pages:

Customize Application

To create and edit custom Visualforce components:

Customize Application

To edit custom Visualforce controllers or Apex

Author Apex

To set Visualforce page security:

Manage Profiles and Permission Sets

To set version settings for Visualforce pages:

Customize Application

To create, edit, or delete static resources:

Customize Application

To create Visualforce Tabs:

Customize Application

How is Visualforce Architected?


All Visualforce pages run entirely on the [Link] platform, both when a developer creates the page, and when an end user requests
a page, as shown in the following architecture diagrams.
Visualforce System Architecture - Development Mode

Introducing Visualforce

What are the Benefits of Visualforce?

When a developer finishes writing a Visualforce page and saves it to the platform, the platform application server attempts to compile
the markup into an abstract set of instructions that can be understood by the Visualforce renderer. If compilation generates errors, the
save is aborted and the errors are returned to the developer. Otherwise, the instructions are saved to the metadata repository and sent
to the Visualforce renderer. The renderer turns the instructions into HTML and then refreshes the developer's view, thereby providing
instantaneous feedback to the developer for whatever changes were made in the markup.
The architecture diagram below shows the process flow when a non-developer user requests a Visualforce page. Because the page is
already compiled into instructions, the application server simply retrieves the page from the metadata repository and sends it to the
Visualforce renderer for conversion into HTML.
Visualforce System Architecture - Standard User Mode

Note: Your Visualforce pages may be run on one of the [Link] servers instead of a [Link] server.

SEE ALSO:
What is Visualforce?
What are the Benefits of Visualforce?
How Do Visualforce Pages Compare to S-Controls?

What are the Benefits of Visualforce?


As a markup language, Visualforce provides the following benefits:
User-friendly development
Developers can edit their Visualforce markup in the same window that displays the resulting page. Consequently, developers can
instantly verify the result of an edit just by saving their code. The Visualforce editor pane also includes auto-completion and syntax
highlighting.

Introducing Visualforce

When Should I Use Visualforce?

Visualforce also supports quick fixes that allow developers to create supporting components on the fly. For example, a developer
can define a new Visualforce page simply by logging in to Salesforce and then entering the name of the new page in a URL. Much
like a wiki, if the page does not yet exist, the platform creates it for you.
Integration with other Web-based user interface technologies
Because Visualforce markup is ultimately rendered into HTML, designers can use Visualforce tags alongside standard HTML, JavaScript,
Flash, or any other code that can execute within an HTML page on the platform, including [Link] platform merge fields and
expressions.
Model-View-Controller (MVC) style development
Visualforce conforms to the Model-View-Controller (MVC) development pattern by providing a clear division between the view of
an application (the user interface, defined by Visualforce markup), and the controller that determines how the application works (the
business logic, defined by a Visualforce controller written in Apex). With this architecture, designers and developers can easily split
up the work that goes with building a new applicationdesigners can focus on the look and feel of the user interface, while
developers can work on the business logic that drives the app.
Concise syntax
Visualforce pages can implement the same functionality as s-controls but with approximately 90% fewer lines of code.
Data-driven defaults
Visualforce components are rendered intelligently by the platform. For example, rather than forcing page designers to use different
component tags for different types of editable fields (such as email addresses or calendar dates), designers can simply use a generic
<apex:inputField> tag for all fields. The Visualforce renderer displays the appropriate edit interface for each field.
Hosted platform
Visualforce pages are compiled and rendered entirely by the [Link] platform. Because they are so tightly integrated, they display
the same performance as standard Salesforce pages, regardless of the amount of data being displayed or edited.
Automatically upgradeable
Visualforce pages do not need to be rewritten when other parts of the [Link] platform are upgraded. Because the pages are
stored as metadata, they are automatically upgraded with the rest of the system.

When Should I Use Visualforce?


The Salesforce prebuilt applications provide powerful CRM functionality. In addition, Salesforce provides the ability to customize the
prebuilt applications to fit your organization. However, your organization may have complex business processes that are unsupported
by the existing functionality. When this is the case, the [Link] platform includes a number of ways for advanced administrators and
developers to implement custom functionality. These include Visualforce, Apex, and the SOAP API.

Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing
the Salesforce user interface. With Visualforce you can:
Build wizards and other multistep processes.
Create your own custom flow control through an application.
Define navigation patterns and data-specific rules for optimal, efficient application interaction.

Apex
Use Apex if you want to:

Introducing Visualforce

How Do Visualforce Pages Compare to S-Controls?

Create Web services.


Create email services.
Perform complex validation over multiple objects.
Create complex business processes that are not supported by workflow.
Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object).
Attach custom logic to another operation, such as saving a record, so that it occurs whenever the operation is executed, regardless
of whether it originates in the user interface, a Visualforce page, or from SOAP API.
For more information, see the Apex Developer Guide.

SOAP API
Use standard SOAP API calls if you want to add functionality to a composite application that processes only one type of record at a time
and does not require any transactional control (such as setting a Savepoint or rolling back changes).
For more information, see the SOAP API Developer's Guide.

How Do Visualforce Pages Compare to S-Controls?


Important: Visualforce pages supersede s-controls. Organizations that havent previously used s-controls cant create them.
Existing s-controls are unaffected, and can still be edited.
Visualforce pages are considered the next-generation of s-controls and should be used instead of s-controls whenever possible, both
for their increased performance and the ease with which they can be written. The following table outlines the differences between
Visualforce pages and s-controls.
Visualforce Pages

S-Controls

Required technical skills

HTML, XML

HTML, JavaScript, Ajax Toolkit

Language style

Tag markup

Procedural code

Page override model

Assemble standard and custom


components using tags

Write HTML and JavaScript for entire page

Standard Salesforce component library Yes

No

Access to built-in platform behavior

Yes, through the standard controller

No

Data binding

Yes

No

Developers can bind an input component


(such as a text box) with a particular field
(such as Account Name). If a user saves a
value in that input component, it is also
saved in the database.

Developers can't bind an input component


with a particular field. Instead, they must
write JavaScript code that uses the API to
update the database with user-specified
field values.

Yes

No, must bring in Salesforce stylesheets


manually

Stylesheet inheritance

Introducing Visualforce

How is Visualforce Versioned?

Visualforce Pages

S-Controls

Respect for field metadata, such as


uniqueness

Yes, by default

Yes, if coded in JavaScript using a


describe API call

Interaction with Apex

Direct, by binding to a custom controller

Indirect, by using Apex webService


methods through the API

Performance

More responsive because markup is


generated on the [Link] platform

Less responsive because every call to the


API requires a round trip to the serverthe
burden rests with the developer to tune
performance

Page container

Native

In an iFrame

If a user attempts to save a record that


violates uniqueness or requiredness field If a user attempts to save a record that
attributes, an error message is automatically violates uniqueness or requiredness field
displayed and the user can try again.
attributes, an error message is only
displayed if the s-control developer wrote
code that checked those attributes.

SEE ALSO:
What is Visualforce?
What are the Benefits of Visualforce?
How is Visualforce Architected?

How is Visualforce Versioned?


Starting with the Summer '09 release, Visualforce pages and components are versioned. When a page or component has a version
number, the functionality of older Visualforce elements does not change as new implementations are introduced. Visualforce versions
start at 15.0. If you try to set the version of a Visualforce page to a version earlier than 15.0, it will automatically be changed to 15.0.
To aid backwards-compatibility, each Visualforce page and custom component is saved with version settings for the specified version
of the API as well as the specific version of Visualforce. If the Visualforce page or component references installed managed packages,
the version settings for each managed package referenced by the page or component is saved too. This ensures that as Visualforce, the
API, and the components in managed packages evolve in subsequent versions, Visualforce pages and components are still bound to
versions with specific, known behavior.
Custom components that are referenced in Visualforce pages always perform under their own version number. Thus, if a custom
component is set at version 15.0, it always exhibits behavior from Visualforce version 15.0, whether running in a version 15.0 or a 16.0
page.
The release notes list any changes between Visualforce versions. The component reference also lists which Visualforce version a standard
component was introduced in, as well as whether a component or attribute was deprecated in a version.
To set the Salesforce API and Visualforce version for a Visualforce page or custom component:
1. Edit a Visualforce page or component and click Version Settings.
Note: You can only modify the version settings for a page or custom component on the Version Settings tab when editing
the page or component in Setup.

Introducing Visualforce

Whats New in Visualforce Version 38.0

2. Select the Version of the Salesforce API. This is also the version of Visualforce used with the page or component.
3. Click Save.
SEE ALSO:
Managing Version Settings for Custom Components
Managing Package Version Settings for Visualforce Pages and Components

Whats New in Visualforce Version 38.0


Review the current release notes for a summary of new and changed Visualforce features in the latest release.

Past Releases
Our archive of release notes includes details about features we introduced in previous releases.
Summer 16 Release Notes
Spring 16 Release Notes
Winter 16 Release Notes
Summer 15 Release Notes
Spring 15 Release Notes
Winter 15 Release Notes
Summer 14 Release Notes
Spring 14 Release Notes
Winter 14 Release Notes
Summer 13 Release Notes
Spring 13 Release Notes
Winter 13 Release Notes
Summer 12 Release Notes
Spring 12 Release Notes
Winter 12 Release Notes
Summer 11 Release Notes
Spring 11 Release Notes
Winter 11 Release Notes
Summer 10 Release Notes
Spring 10 Release Notes
Winter 10 Release Notes
Summer 09 Release Notes
Spring 09 Release Notes
Winter 09 Release Notes
Summer 08 Release Notes
Spring 08 Release Notes

Introducing Visualforce

Documentation Typographical Conventions

Winter 08 Release Notes


Summer 07 Release Notes
Spring 07 Release Notes
[Link] Mobile 7.0 for BlackBerry Release Notes
[Link] Mobile 6.1 for Windows Mobile 5 Release Notes
Winter 07 Release Notes
Summer 06 Release Notes
Winter 06 Release Notes
[Link] Mobile 6.0 Release Notes
Summer 05 Release Notes
Winter 05 Release Notes
Summer 04 Release Notes
Spring 04 Release Notes
Winter 04 Release Notes

Documentation Typographical Conventions


Apex and Visualforce documentation uses the following typographical conventions.
Convention

Description

Courier font

In descriptions of syntax, monospace font indicates items that you should type as shown,
except for brackets. For example:
Public class HelloWorld

Italics

In descriptions of syntax, italics represent variables. You supply the actual value. In the following
example, three values need to be supplied: datatype variable_name [ = value];
If the syntax is bold and italic, the text represents a code element that needs a value supplied
by you, such as a class name or variable value:
public static class YourClassHere { ... }

Bold Courier font

In code samples and syntax descriptions, bold courier font emphasizes a portion of the code
or syntax.

<>

In descriptions of syntax, less-than and greater-than symbols (< >) are typed exactly as shown.
<apex:pageBlockTable value="{![Link]}" var="contact">
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
</apex:pageBlockTable>

10

Introducing Visualforce

Documentation Typographical Conventions

Convention

Description

{}

In descriptions of syntax, braces ({ }) are typed exactly as shown.


<apex:page>
Hello {!$[Link]}!
</apex:page>

[]

In descriptions of syntax, anything included in brackets is optional. In the following example,


specifying value is optional:
data_type variable_name [ = value];

In descriptions of syntax, the pipe sign means or. You can do one of the following (not all).
In the following example, you can create a new unpopulated set in one of two ways, or you
can populate the set:
Set<data_type> set_name
[= new Set<data_type>();] |
[= new Set<data_type{value [, value2. . .] };] |
;

11

CHAPTER 2

Tools for Visualforce Development

Before you begin developing Visualforce pages and components, familiarize yourself with the different places to create them:
The best way to build Visualforce is by enabling Visualforce development mode. Visualforce development mode is only available for
users with the Customize Application permission. Development mode provides you with:
A special development footer on every Visualforce page that includes the pages view state, any associated controller, a link to
the component reference documentation, and a page markup editor that offers highlighting, find-replace functionality, and
auto-suggest for component tag and attribute names.
The ability to define new Visualforce pages just by entering a unique URL.
Error messages that include more detailed stack traces than what standard users receive.
To enable Visualforce development mode:
1. From your personal settings, enter Advanced User Details in the Quick Find box, then select Advanced User
Details. No results? Enter Personal Information in the Quick Find box, then select Personal Information.
2. Click Edit.
3. Select the Development Mode checkbox.
4. Optionally, select the Show View State in Development Mode checkbox to enable the View State tab on the
development footer. This tab is useful for monitoring the performance of your Visualforce pages.
5. Click Save.
You can also develop Visualforce pages through the Salesforce user interface from Setup by entering Visualforce Pages in
the Quick Find box, then selecting Visualforce Pages. For Visualforce components, from Setup, enter Components in the
Quick Find box, then select Visualforce Components.
The [Link] IDE, a plug-in for the Eclipse IDE, offers capabilities not found elsewhere. The [Link] IDE provides a unified interface
for building and deploying [Link] applications, and includes tools such as source code editors, project wizards, and integrated
help. The IDE is designed for advanced developers and development teams.

Using the Development Mode Footer


With development mode enabled, you can view and edit the content of a page by navigating to the URL of the page. For example, if a
page is named HelloWorld, and your Salesforce instance is [Link], enter
[Link] in your browser's address bar. Development mode also provides you
with a special development footer to edit your Visualforce pages and custom controllers, as well as monitor Visualforce performance.
After enabling development mode, all Visualforce pages display with the development mode footer at the bottom of the browser:
Click the tab with the name of the page to open the page editor to view and edit the associated Visualforce markup without having
to return to the Setup area. Changes display immediately after you save the page.
If the page uses a custom controller, the name of the controller class is available as a tab. Click the tab to edit the associated Apex
class.

12

Tools for Visualforce Development

Using the Development Mode Footer

If the page uses any controller extensions, the names of each extension are available as tabs. Clicking on the tab lets you edit the
associated Apex class.
If enabled in Setup, the View State tab displays information about the items contributing to the view state of the Visualforce page.
Click Save (just above the edit pane) to save your changes and refresh the content of the page.
Click Component Reference to view the documentation for all supported Visualforce components.
Click Where is this used? to view a list of all items in Salesforce that reference the page, such as custom tabs, controllers, or other
pages.
Click the Collapse button (

) to collapse the development mode footer panel. Click the Expand button (

) to toggle it back open.

Click the Disable Development Mode button ( ) to turn off development mode entirely. Development mode remains off until
you enable it again from your personal information page in your personal settings.

About the View State Tab


The view state of a web page is composed of all the data that's necessary to maintain the state of the controller during server requests
(like sending or receiving data). Since the view state contributes to the overall size of your page, performance of a page can depend on
efficiently managing the view state. The View State tab in the development mode footer provides information about the view state of
your Visualforce page as it interacts with Salesforce.
Note: The View State tab should be used by developers that understand the page request process. Familiarize yourself with the
order of execution in a Visualforce page before using the tab.
To enable the View State tab:
1. From your personal settings, enter Advanced User Details in the Quick Find box, then select Advanced User Details.
No results? Enter Personal Information in the Quick Find box, then select Personal Information.
2. Click Edit.
3. Select the Development Mode checkbox if it isn't selected.
4. Select the Show View State in Development Mode checkbox.
5. Click Save.
Note: Since the view state is linked to form data, the View State tab only appears if your page contains an <apex:form> tag.
In addition, the View State tab displays only on pages using custom controllers or controller extensions.
The View State tab is composed of folder nodes. If you click any folder, a pie chart with a Content tab appears. This chart displays the
folder's child Visualforce custom controllers, Apex objects, or fields. You can see which elements contribute to the parent's overall size
by hovering over pieces of the graph. This is the same information as the individual text nodes. The chart requires Flash version 6 or
greater enabled on your browser.
Salesforce allows Visualforce pages to have a maximum view state size of 135 KB. The View State tab shows you which elements on your
page are taking up that space. A smaller view state size generally means quicker load times. To minimize your pages' view state, you
can optimize your Apex controller code and remove any superfluous Visualforce components used. For example:
If you notice that a large percentage of your view state comes from objects used in controllers or controller extensions, consider
refining your SOQL calls to return only data that's relevant to the Visualforce page.
If your view state is affected by a large component tree, try reducing the number of components your page depends on.
For more information on how to improve Visualforce using the View State tab, see Best Practices for Improving Visualforce Performance
on page 337.
The View State tab contains the following columns (in alphabetical order):

13

Tools for Visualforce Development

About the Visualforce Editor

Column

Description

% of Parent

The percent of the overall size that the custom controller, Apex
object, or field contributes to the parent.

Name

The name of the custom controller, Apex object, or field.

Size

The view state size of the custom controller, Apex object, or field.

Type

The type of custom controller, Apex object, or field.

Value

The value of the field.

The Name column contains nodes defining the various parts of your Visualforce page. They are (in alphabetical order):
Node

Description

Component Tree

This represents the overall structure of your page. Its size is affected
by the number of components you have on the page. Generally,
fewer components means a smaller component tree, which could
result in faster load times. You can see how much of your view
state size is made up from the component tree by clicking the
View State folder.

Internal

This represents the internal Salesforce data used by your Visualforce


page. This can't be controlled by developers. You can see how
much of your view state size is made up from internal elements
by clicking the State folder.

Expressions

This represents the data used by formula expressions defined in


your Visualforce page.

State

This folder contains all the Visualforce custom controllers, Apex


objects, or fields. By expanding the child Controller and Controller
Extension folders, you can see each object that's on the page, its
fields, and the value of those fields. Generally, these are dependent
on your Apex controller logic.

View State

This folder contains all the nodes. By clicking on it, you can find
overall information about your Visualforce page's view state. The
Capacity tab tells you how much of your allotted view state size is
being used. If you exceed that amount, the graph will also tell you
how many kilobytes you've gone over.

About the Visualforce Editor


When editing Visualforce pages through the development mode footer or from Setup, an editor is available with the following functionality:
Syntax highlighting
The editor automatically applies syntax highlighting for keywords and all functions and operators.

14

Tools for Visualforce Development

About the Visualforce Editor

Search ( )
Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search textbox
and click Find Next.
To replace a found search string with another string, enter the new string in the Replace textbox and click replace to replace
just that instance, or Replace All to replace that instance and all other instances of the search string that occur in the page, class,
or trigger.
To make the search operation case sensitive, select the Match Case option.
To use a regular expression as your search string, select the Regular Expressions option. The regular expressions follow
JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular expression
group variables ($1, $2, and so on) from the found search string. For example, to replace an <h1> tag with an <h2> tag and
keep all the attributes on the original <h1> intact, search for <h1(\s+)(.*)> and replace it with <h2$1$2>.
Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that line.
Undo ( ) and Redo ( )
Use undo to reverse an editing action and redo to recreate an editing action that was undone.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
Line and column position
The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used with go to line
(

) to quickly navigate through the editor.

Line and character count


The total number of lines and characters is displayed in the status bar at the bottom of the editor.
The editor supports the following keyboard shortcuts:
Tab

Adds a tab at the cursor


SHIFT+Tab

Removes a tab
CTRL+f

Opens the search dialog or searches for the next occurrence of the current search
CTRL+r

Opens the search dialog or replaces the next occurrence of the current search with the specified replacement string
CTRL+g

Opens the go to line dialog


CTRL+s

Performs a quick save.


CTRL+z

Reverses the last editing action


CTRL+y

Recreates the last editing action that was undone

15

CHAPTER 3

Getting a Quick Start with Visualforce

To showcase the essential elements of Visualforce, this chapter includes a set of examples that demonstrate features of the language.
While the examples do not go into every detail, rule, or exception for every tag or controller, new Visualforce developers can use this
tutorial to understand how Visualforce works before proceeding to the more detailed descriptions in the remainder of this guide.
The examples are broken up into beginner and advanced sections. The beginner examples primarily use Visualforce markup. The advanced
examples use [Link] Apex code in addition to Visualforce markup.
Advanced examples that require Apex are in their own chapter.

Compiling Visualforce Successfully


You can't save your Visualforce pages and components unless they correctly compile. Here's a list of things to watch out for when
creating Visualforce pages:
Verify that your component tags start with the correct namespace identifier like apex:that is, apex followed by a colon.
Make sure that every opening quote and bracket has a closing one.
Verify that the controller or controller extension is named correctly.
Visualforce pages and components created using Salesforce API version 19.0 or higher must be written as well-formed XML. In
general, this means that elements must be correctly nested, non-empty elements must have an end tag, empty elements must be
terminated with a closing slash (/), and so on. The World Wide Web Consortium (W3C) provides an article on the specifications
of well-formed XML.
The following exceptions are allowed:
Code that violates well-formed XML is permitted inside JavaScript. For example, you don't need to use <![CDATA[]]> tags
in Visualforce.
Code that violates well-formed XML is permitted inside expressions. For example, you don't need to escape quotation marks
inside formulas.
XML directives that are normally required at the beginning of a pagesuch as <?xml version="1.0"
encoding="UTF-8"?>can occur inside top-level container tags, like <apex:page> and <apex:component>.

Creating Your First Page


With development mode enabled, you can create your first Visualforce page by entering a URL for the page in your browser's address
bar as follows:
[Link]

For example, if you want to create a page called HelloWorld and your Salesforce organization uses [Link], enter
[Link]

16

Getting a Quick Start with Visualforce

Creating Your First Page

Because the page does not yet exist, you are directed to an intermediary page from which you can create your new page. Click Create
Page <myNewPageName> to create it automatically.
Note: If you do not have Visualforce development mode enabled, you can also create a new page from Setup by entering
Visualforce Pages in the Quick Find box, then selecting Visualforce Pages, and then clicking New.
Visualforce pages can always be edited from this part of setup, but to see the results of your edits you have to navigate to the URL
of your page. For that reason, most developers prefer to work with development mode enabled so they can view and edit pages
in a single window.
A New Visualforce Page

You now have a Visualforce page that includes default text. To edit your new page, click the Page Editor bar that appears at the bottom
of the browser. It expands to show you the following Visualforce markup:
<apex:page>
<!-- Begin Default Content REMOVE THIS -->
<h1>Congratulations</h1>
This is your new Apex Page: HelloWorld
<!-- End Default Content REMOVE THIS -->
</apex:page>

This default markup includes the only required tag for any page the <apex:page> tag that begins and ends any page markup.
Embedded within the start and close <apex:page> tags is plain text, some of which is formatted with a standard HTML tag, <h1>.
As long as you keep the required <apex:page> tag you can add as much plain text or valid HTML to this page as you want. For
example, after entering the following code and clicking Save in the Page Editor, the page displays the text Hello World! in bold:
<apex:page>
<b>Hello World!</b>
</apex:page>

Tip: Pay attention to warningsthe Visualforce editor displays a warning if you save a page with HTML that does not include a
matching end tag for every opened tag. Although the page saves, this malformed HTML might cause problems in your rendered
page.

17

Getting a Quick Start with Visualforce

Displaying Field Values with Visualforce

Displaying Field Values with Visualforce


Visualforce pages use the same expression language as formulasthat is, anything inside {! } is evaluated as an expression that can
access values from records that are currently in context. For example, you can display the current user's first name by adding the
{!$[Link]} expression to a page:
<apex:page>
Hello {!$[Link]}!
</apex:page>

$User is a global variable that always represents the current user record. All global variables are referenced with a $ symbol. For a list

of global variables that you can use in Visualforce, see Global Variables on page 602.
To access fields from a record that is not globally available, like a specific account, contact, or custom object record, you need to associate
your page with a controller. Controllers provide pages with the data and business logic that make your application run, including the
logic that specifies how to access a particular object's records. While you can define a custom controller for any page with Apex, Salesforce
includes standard controllers for every standard and custom object.
For example, to use the standard controller for accounts, add the standardController attribute to the <apex:page> tag,
and assign it the name of the account object:
<apex:page standardController="Account">
Hello {!$[Link]}!
</apex:page>

After you save your page, the Accounts tab is highlighted for the page, and the look-and-feel for the components on the page match
the Accounts tab. Additionally, you can now access fields on the account record currently in context by using
{!account.<fieldName>} expression syntax.
For example, to display an account's name on a page, use {![Link]} in the page markup:
<apex:page standardController="Account">
Hello {!$[Link]}!
<p>You are viewing the {![Link]} account.</p>
</apex:page>

The {![Link]} expression makes a call to the getAccount() method in the standard Account controller to return the
record ID of the account currently in context. It then uses dot notation to access the name field for that record.
Note: You cannot access parent objects using this expression language. In other words, {![Link]} will
return an error.
Note: When you save a page, the value attribute of all input components<apex:inputField>, <apex:inputText>,
and so onis validated to ensure its a single expression, with no literal text or white space, and is a valid reference to a single
controller method or object property. An error will prevent saving the page.
To bring an account record into the current context, you must add a query parameter to the page URL that specifies the ID of the record.
To do this:
1. Find the ID of an account by any means you wish. One easy way is to view the detail page of an account record and copy the character
code at the end of the URL. For example, if you navigate to an account detail page with the following URL:
[Link]

Then 001D000000IRt53 is the ID for the account.

18

Getting a Quick Start with Visualforce

Using the Visualforce Component Library

2. Back on your page, add the account ID as a query string parameter to the URL in your browser's address bar. For example, if your
page is located at:
[Link]

Add ?id=001D000000IRt53 to the end of the URL:


[Link]

Note: If you use the id parameter in a URL, it must refer to the same entity referred to in the standard controller.
Once an account ID is specified in the URL, the page displays the appropriate account name, as shown in the following figure.
Displaying Account Data in a Visualforce Page

Using the Visualforce Component Library


Up to this point, the only Visualforce tag that has been used in the examples is the mandatory <apex:page> tag that must be placed
at the start and end of all Visualforce markup. However, just as you can insert images or tables into an HTML document with the <img>
or <table> tags, respectively, you can add user interface components to your Visualforce pages using tags that are defined in the
Visualforce component library.
For example, to add a component that looks like a section on a detail page, use the <apex:pageBlock> component tag:
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$[Link]}!">
You are viewing the {![Link]} account.
</apex:pageBlock>
</apex:page>

19

Getting a Quick Start with Visualforce

Using the Visualforce Component Library

The <apex:pageBlock> Component

Tags also exist for other common Salesforce interface components, such as related lists, detail pages, and input fields. For example, to
add the content of a detail page, use the <apex:detail> component tag:
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$[Link]}!">
You are viewing the {![Link]} account.
</apex:pageBlock>
<apex:detail/>
</apex:page>

The <apex:detail> Component Without Attributes

Without any specified attributes on the tag, <apex:detail> displays the complete detail view for the context record. If you want
to modify properties such as which record details are displayed, or whether related lists or the title appear, you can use attributes on the
tag. For example, the following markup displays the details of the context account's owner, without related lists or a colored title bar:
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$[Link]}!">

20

Getting a Quick Start with Visualforce

Overriding an Existing Page with a Visualforce Page

You are viewing the {![Link]} account.


</apex:pageBlock>
<apex:detail subject="{![Link]}" relatedList="false" title="false"/>
</apex:page>

The <apex:detail> Component Without Related List or Title Elements

To browse the component library, click Component Reference in the Page Editor. From this page you can drill down into any component
to see the attributes that are available for each, including any custom components that you define.
SEE ALSO:
Standard Component Reference

Overriding an Existing Page with a Visualforce Page


Suppose you want to change the format of an existing page, such as the standard account detail page. All the information for an account
displays on a single page. If there's a lot of information, you might end up doing a lot of scrolling. Using a Visualforce page you can make
each section for an account display in a tab, such as contacts, opportunities, and so on.
First, create a new Visualforce page using the quick fix.
1. In your browser, add the text /apex/tabbedAccount to the URL for your Salesforce instance. For example, if your Salesforce
instance is [Link] the new URL would be
[Link] You will get the following error message:

21

Getting a Quick Start with Visualforce

Overriding an Existing Page with a Visualforce Page

2. Click Create Page tabbedAccount to create the new page.


3. Click the Page Editor link in the bottom left corner of the page. This displays the code for the new page, which should look like this:
<apex:page>
<!-- Begin Default Content REMOVE THIS -->
<h1>Congratulations</h1>
This is your new Page: tabbedAccount
<!-- End Default Content REMOVE THIS -->
</apex:page>

4. Replace the existing code with the following and click Save:
<apex:page standardController="Account" showHeader="true"
tabStyle="account" >
<style>
.activeTab {background-color: #236FBD; color:white;
background-image:none}
.inactiveTab { background-color: lightgrey; color:black;
background-image:none}
</style>
<apex:tabPanel switchType="client" selectedTab="tabdetails"
id="AccountTabPanel" tabClass='activeTab'
inactiveTabClass='inactiveTab'>
<apex:tab label="Details" name="AccDetails" id="tabdetails">
<apex:detail relatedList="false" title="true"/>
</apex:tab>
<apex:tab label="Contacts" name="Contacts" id="tabContact">
<apex:relatedList subject="{!account}" list="contacts" />
</apex:tab>
<apex:tab label="Opportunities" name="Opportunities"
id="tabOpp">
<apex:relatedList subject="{!account}"
list="opportunities" />
</apex:tab>
<apex:tab label="Open Activities" name="OpenActivities"
id="tabOpenAct">
<apex:relatedList subject="{!account}"
list="OpenActivities" />
</apex:tab>
<apex:tab label="Notes and Attachments"
name="NotesAndAttachments" id="tabNoteAtt">
<apex:relatedList subject="{!account}"
list="CombinedAttachments" />
</apex:tab>
</apex:tabPanel>
</apex:page>

5. Notice that there is no data in the Account page. You need to specify the ID of a particular account in the URL, as you've done with
previous pages, for example, [Link]
After you add in an account ID, your page should display as follows:

22

Getting a Quick Start with Visualforce

Overriding an Existing Page with a Visualforce Page

Things to note about the page markup:


<style> is actually part of CSS markup, not Visualforce markup. It defines the styles for two types of tabs: activeTab and inactiveTab.
<apex:tabPanel> is used to generate the tabs. Notice how it uses the following attributes:
tabClass attribute: specifies the style class used to display a tab when it is active.
inactiveTabClass attribute: specifies the style class used to display a tab when it is inactive.
Within the definition of the tab panel, is the definition of each child tab component, <apex:tab>. The first tab uses the
<apex:detail> tag to return that portion of the detail view for the page:
<apex:tab label="Details" name="AccDetails" id="tabdetails">
<apex:detail relatedList="false" title="true"/>
</apex:tab>

While the rest of the tabs use the <apex:relatedList> to specify the different parts of the account page. The following is
the tab for contacts. It uses an existing list of contacts.
<apex:tab label="Contacts" name="Contacts" id="tabContact">
<apex:relatedList subject="{!account}" list="contacts" />
</apex:tab>

Now that you've created a page to display an account with tabs, you can use this page to override the detail view for all accounts.
1. From the object management settings for accounts, go to Buttons, Links, and Actions.
2. Click Edit next to View.
3. For Override With select Visualforce Page.
4. From the Visualforce Page drop-down list, select tabbedAccount.
5. Click Save.

23

Getting a Quick Start with Visualforce

Redirecting to a Standard Object List Page

Click the Account tab, and select any account. The detail for the account is now displayed with tabs.
SEE ALSO:
Salesforce Help: Find Object Management Settings

Redirecting to a Standard Object List Page


For buttons or links that navigate a user to a standard tab, you can redirect the content to present a list of standard objects.
Create a Visualforce page with the following markup:
<apex:page action="{!URLFOR($[Link], $[Link])}"/>

The user will see a page that resembles the following:


Overriding the Account Detail Page

The Visualforce page can also refer to other standard objects, such as contacts, by changing the reference to the standard object. For
example:
<apex:page action="{!URLFOR($[Link], $[Link])}"/>

Using Input Components in a Page


So far the examples in this quick start tutorial show ways that you can display data in a Visualforce page. To capture input from a user,
use the <apex:form> tag with one or more input components and a <apex:commandLink> or <apex:commandButton>
tag to submit the form.
The input component tag that is most often used in a form is <apex:inputField>. This tag renders the appropriate input widget
based on a standard or custom object fields type. For example, if you use an <apex:inputField> tag to display a date field, a
calendar widget displays on the form. If you use an <apex:inputField> tag to display a picklist field, a drop-down list displays
instead. The <apex:inputField> tag can be used to capture user input for any standard or custom object field, and respects any
metadata that is set on the field definition, such as whether the field is required or unique, or whether the current user has permission
to view or edit it.
For example, the following page allows users to edit and save the name of an account:
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
[Link]

24

Getting a Quick Start with Visualforce

Adding and Customizing Input Field Labels

Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="Hello {!$[Link]}!">
You are viewing the {![Link]} account. <p/>
Change Account Name: <p/>
<apex:inputField value="{![Link]}"/> <p/>
<apex:commandButton action="{!save}" value="Save New Account Name"/>
</apex:pageBlock>
</apex:form>
</apex:page>

Notice in the example that:


The <apex:inputField> tag is bound to the account name field by setting the tags value attribute. The expression
contains the familiar {![Link]} dot-notation used to display the fields value elsewhere in the page.
The <apex:commandButton> tag has an action attribute. The value for this attribute invokes the save action of the
standard Account controller, which performs identically to the Save button on the standard Account edit page.
Note: When you save a page, the value attribute of all input components<apex:inputField>, <apex:inputText>,
and so onis validated to ensure its a single expression, with no literal text or white space, and is a valid reference to a single
controller method or object property. An error will prevent saving the page.
The <apex:form> Component with a Single Input Field

The only fields that the <apex:inputField> tag cannot display are those defined as member variables of a custom controller
class written in Apex. To gather data for these variables, use the <apex:inputCheckbox>, <apex:inputHidden>,
<apex:inputSecret>, <apex:inputText>, or <apex:inputTextarea> tags instead.

Adding and Customizing Input Field Labels


When used inside of a <apex:pageBlockSection> component, Visualforce input components and some output components
automatically display a form label for the field. For components that map to standard or custom object fields, the displayed label is the

25

Getting a Quick Start with Visualforce

Adding and Customizing Input Field Labels

object field label by default. To override the default value, and for components that arent mapped directly to object fields, you can set
the label using the label attribute of the component. For example:
<apex:page standardController="Contact">
<apex:form>
<apex:pageBlock title="Quick Edit: {![Link]}">
<apex:pageBlockSection title="Contact Details" columns="1">
<apex:inputField value="{![Link]}"/>
<apex:outputField value="{![Link]}"
label="Mobile #"/>
<apex:inputText value="{![Link]}"
label="{![Link] + 's Email'}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

Note: For this page to display contact data, the ID of a valid contact record must be specified as a query parameter in the URL for
the page. For example,
[Link]

Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
The label attribute may be a string, or an expression that evaluates to a string. If you set label to an empty string, the form label
for that field will be suppressed.
The label attribute can be set on the following Visualforce components:
<apex:inputCheckbox>
<apex:inputField>
<apex:inputSecret>
<apex:inputText>
<apex:inputTextarea>
<apex:outputField>

26

Getting a Quick Start with Visualforce

Setting the Tab Order for Fields in a Form

<apex:outputText>
<apex:selectCheckboxes>
<apex:selectList>
<apex:selectRadio>

Custom Labels and Error Messages


When set, the label attribute will be used for component-level error messages, for example, when a field is required or must be
unique. Custom labels won't be used in custom error messages, and the default object field label will be used instead. If you set a label
attribute to an empty string, the default object field label will be used in all error messages.

Setting the Tab Order for Fields in a Form


Visualforce forms have a natural order for tabbing through the input fields: left-to-right, top-to-bottom. For some forms, this might
not be the most efficient or accessible arrangement. You can use the tabIndex and tabOrderHint attributes on input and other
components in your page to change the tab order to anything youd like.
Here is a simple example that uses the tabOrderHint attribute to control the tab order.
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="Edit Account: {![Link]}">
<apex:pageBlockSection title="Account Details" columns="1">
<apex:inputField value="{![Link]}" tabOrderHint="4"/>
<apex:inputField value="{![Link]}" tabOrderHint="3"/>
<apex:inputField value="{![Link]}" tabOrderHint="2"/>
<apex:inputField value="{![Link]}" tabOrderHint="1"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
[Link]

Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
Notice that when you display this page and press TAB, the active field changes in the reverse order than you would normally expect.

Using tabIndex and tabOrderHint


The tabOrderHint attribute is used as a hint when calculating the value to set for the tabindex value of the rendered HTML
element or elements. Its used to indicate the relative order in which the field is selected compared to other page components. This
value must be an integer between 1 and 3276, or an expression which evaluates to an integer value in the same range. The tab order
begins with component 1 being the first component selected when a user presses TAB.
The tabIndex attribute is used to directly set the tabindex value of the rendered HTML element. Its an absolute index setting
the order in which the field is selected, compared to other page components. This value must be an integer between 0 and 32767, or

27

Getting a Quick Start with Visualforce

Adding Dependent Fields to a Page

an expression which evaluates to an integer value in the same range. The tab order begins with component 0 being the first component
selected when a user presses TAB.
The tabOrderHint attribute is available on only the <apex:inputField> component. The tabIndex attribute can be set
on the following Visualforce components.
<apex:commandButton>
<apex:commandLink>
<apex:inputCheckbox>
<apex:inputFile>
<apex:inputSecret>
<apex:inputText>
<apex:inputTextarea>
<apex:outputLabel>
<apex:outputLink>
<apex:selectCheckboxes>
<apex:selectList>
<apex:selectRadio>
When mixing <apex:inputField> with components that use the tabIndex attribute to set the tab order, you can multiply
the tabOrderHint by 10 to get the approximate equivalent value of the tabIndex for that field. Use this to manually calculate
equivalent values to set the appropriate attribute on each of the components in such a way as to set the desired tab order for all elements
on the page.

Adding Dependent Fields to a Page


Dependent fields provide a way to filter the field values displayed on a Visualforce page. Dependent fields consist of two parts: a controlling
field that determines the filtering, and a dependent field that has its values filtered. Dependent fields can dynamically filter values in
fields such as picklists, multi-select picklists, radio buttons, and checkboxes. Dependent picklists can only be displayed on Visualforce
pages with Salesforce API version 19.0 or higher. For more information, see Dependent Picklists in the Salesforce online help.
For this example, well be adding a dependent picklist, Subcategories, to a Visualforce page. First, create this custom picklist:
1. From the object management settings for accounts, go to the fields area, and then click New.
2. Choose Picklist, and then click Next.
3. Enter Subcategories for the Field Label.
4. Enter the following terms for the list of values:
Apple Farms
Cable
Corn Fields
Internet
Radio
Television
Winery
5. Click Next twice, then click Save.

28

Getting a Quick Start with Visualforce

Adding Dependent Fields to a Page

To define the field dependencies for Subcategories:


1. From the object management settings for accounts, go to the fields area.
2. Click Field Dependencies.
3. Click New.
4. Choose Industry as a controlling field, and Subcategories as a dependent field.
5. Click Continue.
6. Each value in the controlling field (from Industry) is listed in the top row and each value in the dependent field (from Subcategory)
is displayed in the column below it. Set your field dependencies to match this image:
The Field Dependency Matrix for Subcategories

You can disregard any other Industry types that arent shown above.
7. Click Save.
Now, create a Visualforce page called dependentPicklists that looks like this:
<apex:page standardController="Account">
<apex:form >
<apex:pageBlock mode="edit">
<apex:pageBlockButtons >
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Dependent Picklists" columns="2">
<apex:inputField value="{![Link]}"/>
<apex:inputField value="{!account.subcategories__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

When you select Agriculture from the Industry picklist, the Subcategories picklist contains Apple Farms, Corn Fields, and Winery. If you
select Communication, your Subcategories picklist contains all the Communication types defined earlier.

Dependent Picklist Considerations


Consider the following when using dependent picklists in Visualforce pages:
You can mix controlling and dependent fields across various field types, such as picklists, multi-picklists, radio buttons, and checkboxes.
Theres a limit of 10 dependent picklist pairs per page. This is totalled across all objects. Thus, you could have five dependent picklists
on Account, and five on Contact, but no more. However, you can repeat the same pair of dependent picklists, such as in an iterative
tag like <apex:repeat>, without counting more than once against your limit.

29

Getting a Quick Start with Visualforce

Adding Dependent Fields to a Page

If the user viewing the page has read-only access to the controlling field, a dependent picklist might not behave as expected. In
this case, the dependent picklist shows all possible values for the picklist, instead of being filtered on the read-only value. This is a
known limitation in Visualforce.
Pages must include the controlling field for a dependent picklist. Failing to include the controlling field on the page causes a runtime
error when the page displays.
Dont mix inline edit-enabled fields with regular input fields from the same dependency group. For example, dont mix a standard
input field for a controlling field with an inline edit-enabled dependent field:
<apex:page standardController="Account">
<apex:form>
<!-- Don't mix a standard input field... -->
<apex:inputField value="{!account.Controlling__c}"/>
<apex:outputField value="{!account.Dependent__c}">
<!-- ...with an inline-edit enabled dependent field -->
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
</apex:form>
</apex:page>

If you combine inline edit-enabled dependent picklists with Ajax-style partial page refreshes, refresh all fields with dependent or
controlling relationships to each other as one group. Refreshing fields individually isnt recommended and might result in inconsistent
undo/redo behavior. Heres an example of the recommended way to partially refresh a form with inline edit-enabled dependent
picklists:
<apex:form>
<!-- other form elements ... -->
<apex:outputPanel id="locationPicker">
<apex:outputField value="{![Link]}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{![Link]}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{![Link]}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
</apex:outputPanel>
<!-- ... -->
<apex:commandButton value="Refresh Picklists" reRender="locationPicker" />
</apex:form>

All of the inline edit-enabled picklists are wrapped in the <apex:outputPanel> component. The <apex:outputPanel>
rerenders when the <apex:commandButton> action method fires.
SEE ALSO:
Salesforce Help: Find Object Management Settings

30

Getting a Quick Start with Visualforce

Creating Visualforce Dashboard Components

Creating Visualforce Dashboard Components


Visualforce pages can be used as dashboard components. A dashboard shows data from source reports as visual components, which
can be charts, gauges, tables, metrics, or Visualforce pages. The components provide a snapshot of key metrics and performance indicators
for your organization. Each dashboard can have up to 20 components.
Visualforce pages that use the Standard Controller cant be used in dashboards. To be included in a dashboard, a Visualforce page must
have either no controller, use a custom controller, or reference a page bound to the StandardSetController Class. If a Visualforce page
does not meet these requirements, it does not appear as an option in the dashboard component Visualforce Page drop-down
list.
Create a Visualforce page called VFDashboard. The following markup shows an example of a Visualforce page that uses a standard
list controller and can be used within a dashboard. It displays a list of the cases associated with your organization:
<apex:page standardController="Case" recordSetvar="cases">
<apex:pageBlock>
<apex:form id="theForm">
<apex:panelGrid columns="2">
<apex:outputLabel value="View:"/>
<apex:selectList value="{!filterId}" size="1">
<apex:actionSupport event="onchange" rerender="list"/>
<apex:selectOptions value="{!listviewoptions}"/>
</apex:selectList>
</apex:panelGrid>
<apex:pageBlockSection>
<apex:dataList var="c" value="{!cases}" id="list">
{![Link]}
</apex:dataList>
</apex:pageBlockSection>
</apex:form>
</apex:pageBlock>
</apex:page>

To create a dashboard that uses this Visualforce page:


1. View the dashboard and click Edit.
2. Click Add Component from the top of any column.
3. Choose a Visualforce Page as the component type.
4. Optionally, enter a header to display at the top of the dashboard component.
5. Optionally, enter a footer to display at the bottom of the dashboard component.
6. From the Visualforce Page drop-down list, select VFDash.
7. Click Save.

31

Getting a Quick Start with Visualforce

Displaying Related Lists for Custom Objects

Sample Visualforce Page Running in a Dashboard

For a more complex example that uses a custom list controller, see Advanced Visualforce Dashboard Components on page 130.

Displaying Related Lists for Custom Objects


Displaying custom objects and their related lists with Visualforce is very simple.
Suppose you have three custom objects: MyChildObject, MyMasterObject, and MyLookupObject. MyChildObject has a master-detail
relationship with MyMasterObject (which is the master). MyLookupObject also has a Lookup relationship with MyChildObject.
If you want to create a Visualforce page that displays the related list for MyMasterObject, use the following markup:
<apex:page standardController="MyMasterObject__c">
<apex:relatedList list="MyChildObjects__r" />
</apex:page>

For this page to display the related list data, the ID of a valid custom object record with a custom relationship must be specified as a
query parameter in the URL for the page, for example,
[Link]
Although MyLookupObject uses a different type of relationship, the syntax is identical:
<apex:page standardController="MyLookupObject__c">
<apex:relatedList list="MyChildObjects__r" />
</apex:page>

Enabling Inline Editing


Visualforce pages 21.0 and above support inline editing. Inline editing lets users quickly edit field values, right on a records detail page.
Editable cells display a pencil icon ( ) when you hover over the cell, while non-editable cells display a lock icon ( ).
The <apex:detail> component has an attribute that activates inline editing, while the <apex:inlineEditSupport>
component provides inline editing functionality to several container components.
To see the power of inline editing, create a page called inlineDetail with the following code:
<apex:page standardController="Account">
<apex:detail subject="{![Link]}" relatedList="false" />
</apex:page>

32

Getting a Quick Start with Visualforce

Enabling Inline Editing

Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
[Link]

Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
Try to double-click one of the fields, like Account Number. Youll notice that nothing happens.
Now, replace the page with the following code:
<apex:page standardController="Account">
<apex:detail subject="{![Link]}" relatedList="false" inlineEdit="true"/>
</apex:page>

Hover over any of the fields, and youll notice that you can now edit their contents directly. Clicking Save at the top of the section
preserves all your changed information. Components that support inline editing must always be descendants of the <apex:form>
tag. However, the <apex:detail> component doesnt have to be a descendant of an <apex:form> to support inline editing.
The <apex:inlineEditSupport> component must be a descendant of the following components:
<apex:dataList>
<apex:dataTable>
<apex:form>
<apex:outputField>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockTable>
<apex:repeat>
Heres a sample that demonstrates how you can create a page using <apex:pageBlockTable> that makes use of inline editing:
<apex:page standardController="Account" recordSetVar="records" id="thePage">
<apex:form id="theForm">
<apex:pageBlock id="thePageBlock">
<apex:pageBlockTable value="{!records}" var="record" id="thePageBlockTable">
<apex:column >
<apex:outputField value="{![Link]}" id="AccountNameDOM" />
<apex:facet name="header">Name</apex:facet>
</apex:column>
<apex:column >
<apex:outputField value="{![Link]}" id="AccountTypeDOM" />
<apex:facet name="header">Type</apex:facet>
</apex:column>
<apex:column >
<apex:outputField value="{![Link]}"
id="AccountIndustryDOM" />
<apex:facet name="header">Industry</apex:facet>
</apex:column>
<apex:inlineEditSupport event="ondblClick"
showOnEdit="saveButton,cancelButton" hideOnEdit="editButton" />
</apex:pageBlockTable>
<apex:pageBlockButtons >
<apex:commandButton value="Edit" action="{!save}" id="editButton" />

33

Getting a Quick Start with Visualforce

Enabling Inline Editing

<apex:commandButton value="Save" action="{!save}" id="saveButton" />


<apex:commandButton value="Cancel" action="{!cancel}" id="cancelButton"
/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

The following are cases when inline editing isnt supported.


Inline editing isnt available in:
Accessibility mode
Setup pages
Dashboards
Customer Portal
Descriptions for HTML solutions
The following standard checkboxes on case and lead edit pages are not inline editable:
Case Assignment (Assign using active assignment rules)
Case Email Notification (Send notification email to contact)
Lead Assignment (Assign using active assignment rule)
The fields in the following standard objects are not inline editable.
All fields in Documents and Price Books
All fields in Tasks except for Subject and Comment
All fields in Events except for Subject, Description, and Location
Full name fields of Person Accounts, Contacts, and Leads. However, their component fields are, for example, First Name
and Last Name.
You can use inline editing to change the values of fields on records for which you have read-only access, either via field-level security
or your organization's sharing model; however, Salesforce doesn't let you save your changes, and displays an insufficient privileges
error message when you try to save the record.
Inline editing isnt supported for standard rich text area (RTA) fields, such as [Link], that are bound to
<apex:outputField> when Visualforce pages are served from a separate domain, other than the Salesforce domain. By
default, Visualforce pages are served from a separate domain unless your administrator has disabled this setting. Custom RTA fields
arent affected by this limitation and support inline editing.
Inline editing is supported for dependent picklists that use <apex:outputField>.
Pages must include the controlling field for a dependent picklist. Failing to include the controlling field on the page causes a runtime
error when the page displays.
Dont mix inline edit-enabled fields with regular input fields from the same dependency group. For example, dont mix a standard
input field for a controlling field with an inline edit-enabled dependent field:
<apex:page standardController="Account">
<apex:form>
<!-- Don't mix a standard input field... -->
<apex:inputField value="{!account.Controlling__c}"/>
<apex:outputField value="{!account.Dependent__c}">
<!-- ...with an inline-edit enabled dependent field -->
<apex:inlineEditSupport event="ondblClick" />

34

Getting a Quick Start with Visualforce

Converting a Page to a PDF File

</apex:outputField>
</apex:form>
</apex:page>

If you combine inline edit-enabled dependent picklists with Ajax-style partial page refreshes, refresh all fields with dependent or
controlling relationships to each other as one group. Refreshing fields individually isnt recommended and might result in inconsistent
undo/redo behavior. Heres an example of the recommended way to partially refresh a form with inline edit-enabled dependent
picklists:
<apex:form>
<!-- other form elements ... -->
<apex:outputPanel id="locationPicker">
<apex:outputField value="{![Link]}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{![Link]}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{![Link]}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
</apex:outputPanel>
<!-- ... -->
<apex:commandButton value="Refresh Picklists" reRender="locationPicker" />
</apex:form>

All of the inline edit-enabled picklists are wrapped in the <apex:outputPanel> component. The <apex:outputPanel>
rerenders when the <apex:commandButton> action method fires.

Converting a Page to a PDF File


You can render any page as a PDF by adding the renderAs attribute to the <apex:page> component, and specifying pdf as
the rendering service. For example:
<apex:page renderAs="pdf">

Visualforce pages rendered as PDFs will either display in the browser or download as a PDF file, depending on your browser settings.
In the previous tutorial, you used a Visualforce page to change the name of a company. Suppose you wanted to generate an announcement
of the new name as a PDF. The following example produces such a page, along with the current date and time.
<apex:page standardController="Account" renderAs="pdf" applyBodyTag="false">
<head>
<style>
body { font-family: 'Arial Unicode MS'; }
.companyName { font: bold 30px; color: red; }
</style>
</head>
<body>
<center>
<h1>New Account Name!</h1>
<apex:panelGrid columns="1" width="100%">

35

Getting a Quick Start with Visualforce

Converting a Page to a PDF File

<apex:outputText value="{![Link]}" styleClass="companyName"/>


<apex:outputText value="{!NOW()}"></apex:outputText>
</apex:panelGrid>
</center>
</body>
</apex:page>

Things to note about the page:


<style> is CSS markup, not Visualforce markup. It defines the font family used for the entire page, as well as a particular style for
the company name.
Some of the output text is contained in an <apex:panelGrid> component. A panel grid renders as an HTML table. Each
component found in the body of the <apex:panelGrid> component is placed into a corresponding cell in the first row until
the number of columns is reached. As there is only a single cell, each output text is displayed in a separate row.
A Visualforce Page Rendered as PDF

Always verify the format of your rendered page before deploying it.
SEE ALSO:
Render a Visualforce Page as a PDF File
Visualforce PDF Rendering Considerations and Limitations

36

Getting a Quick Start with Visualforce

Building a Table of Data in a Page

Building a Table of Data in a Page


Some Visualforce components, such as <apex:pageBlockTable> or <apex:dataTable>, allow you to display information
from multiple records at a time by iterating over a collection of records. To illustrate this concept, the following page uses the
<apex:pageBlockTable> component to list the contacts associated with an account that is currently in context:
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$[Link]}!">
You are viewing the {![Link]} account.
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:pageBlockTable value="{![Link]}" var="contact">
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
[Link]

Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
The <apex:pageBlockTable> Component

Like other iteration components, <apex:pageBlockTable> includes two required attributes, value and var:
value takes a list of sObject records or values of any other Apex type. In the example above, {![Link]} retrieves
the ID of the account that is currently in context and then traverses the relationship to retrieve the list of the associated contacts.

37

Getting a Quick Start with Visualforce

Editing a Table of Data in a Page

var specifies the name of the iteration variable. This variable is used within the body of the <apex:pageBlockTable> tag
to access the fields on each contact. In this example, value="{![Link]}" is used on the <apex:column> tag
to display the name of the contact.
The <apex:pageBlockTable> component takes one or more child <apex:column> components. The number of rows in
the table is controlled by the number of records returned with the value attribute.
Note: The <apex:pageBlockTable> component automatically takes on the styling of a standard Salesforce list. To display
a list with your own styling, use <apex:dataTable> instead.

Editing a Table of Data in a Page


In the last tutorial, you built a table of data. Using <apex:inputField> in the data table columns, you can create a table with
editable fields. Using <apex:commandButton> you can save the data you change. Any message (such as Saving) is automatically
displayed with the <apex:pageMessages> tag.
The following page creates a page that enables you to edit a series of Industry types at the same time:
<apex:page standardController="Account" recordSetVar="accounts"
tabstyle="account" sidebar="false">
<apex:form>
<apex:pageBlock >
<apex:pageMessages />
<apex:pageBlockButtons>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!accounts}" var="a">
<apex:column value="{![Link]}"/>
<apex:column headerValue="Industry">
<apex:inputField value="{![Link]}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

Note: If you have an ID attribute in the URL, this page does not display correctly. For example,
[Link] produces an error.

You need to remove the ID from the URL.


Notice the following about the page markup:
This page takes advantage of standard set controllers to generate the data for the table. Use the recordSetVar attribute to
specify the name of the set of data you want to use. Then, in the <apex:pageBlockTable> value, use the name of that set
to populate the table with data.
The <apex:inputField> tag automatically generates the correct display for the field. In this case, as a drop-down list.
The page must be enclosed in an <apex:form> tag in order to use the <apex:commandButton> tag. A form specifies a
portion of a Visualforce page that users can interact with.

38

Getting a Quick Start with Visualforce

Using Query String Parameters in a Page

Example of Editing a Table of Data

Using Query String Parameters in a Page


As shown in earlier examples, the default page contextthat is, the record that provides the source of data displayed on the pageis
controlled by a query string parameter named id in the page URL. You can also get and set query string parameters in the Visualforce
markup. The following topics provide examples:
Getting Query String Parameters
Setting Query String Parameters in Links
Getting and Setting Query String Parameters on a Single Page

Getting Query String Parameters


You can reference query string parameters in Visualforce markup by using the $CurrentPage global variable. Using $CurrentPage,
you can access the query string parameters for the page by specifying the parameters attribute, after which you can access each
individual parameter:
$[Link].parameter_name

For example, suppose you want to add detail information about a specific contact to an Account page. The account record ID is specified
by the default id query string parameter, and the contact record ID is specified by the query string parameter named cid:
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$[Link]}!">
You are displaying values from the {![Link]} account and a separate contact
that is specified by a query string parameter.
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:dataTable value="{![Link]}" var="contact" cellPadding="4" border="1">
<apex:column>
<apex:facet name="header">Name</apex:facet>
{![Link]}
</apex:column>
<apex:column>
<apex:facet name="header">Phone</apex:facet>
{![Link]}
</apex:column>
</apex:dataTable>

39

Getting a Quick Start with Visualforce

Getting Query String Parameters

</apex:pageBlock>
<apex:detail subject="{!$[Link]}" relatedList="false" title="false"/>
</apex:page>

For this example to render properly, you must associate the Visualforce page with valid account and contact IDs in the URL. For example,
if 001D000000IRt53 is the account ID and 003D000000Q0bIE is the contact ID, the resulting URL should be:
[Link]

Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
Note: If you use the id parameter in a URL, it must refer to the same entity referred to in the standard controller.
Using Query String Parameters in a Page

40

Getting a Quick Start with Visualforce

Setting Query String Parameters in Links

Setting Query String Parameters in Links


You can set query string parameters in links to pages by constructing the link URL manually, or by using <apex:param> tags within
the <apex:outputLink> tag. For example, both of the following examples create identical links to an external page:
<apex:outputLink value="[Link]
Search Google
</apex:outputLink>
<apex:outputLink value="[Link]
Search Google
<apex:param name="q" value="{![Link]}"/>
</apex:outputLink>

The latter method, which uses <apex:param> tags instead of manually creating the URL, is preferable for stylistic reasons.
Note: In addition to <apex:outputLink>, use <apex:param> to set request parameters for <apex:commandLink>,
and <apex:actionFunction>.

Getting and Setting Query String Parameters on a Single Page


Having seen examples of both getting and setting query string parameters, this example shows how the two actions can be combined
on a single page to produce a more interesting result. Based on the example from Getting Query String Parameters, the following page
makes the name of each contact in the list a hyperlink that controls the context of the detail component below it.
This is possible by:
Wrapping the data table in an <apex:form> tag
Turning each contact name into an <apex:commandLink> that sets the cid parameter appropriately with an
<apex:param> tag
When used with a standard controller, command links always entirely refresh the current page with the new information added to the
pagein this case, an updated cid that updates the contact detail component.
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$[Link]}!">
You are displaying contacts from the {![Link]} account.
Click a contact's name to view his or her details.
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:form>
<apex:dataTable value="{![Link]}" var="contact" cellPadding="4"
border="1">
<apex:column>
<apex:facet name="header">Name</apex:facet>
<apex:commandLink>
{![Link]}
<apex:param name="cid" value="{![Link]}"/>
</apex:commandLink>
</apex:column>
<apex:column>
<apex:facet name="header">Phone</apex:facet>
{![Link]}
</apex:column>
</apex:dataTable>

41

Getting a Quick Start with Visualforce

Using Ajax in a Page

</apex:form>
</apex:pageBlock>
<apex:detail subject="{!$[Link]}" relatedList="false" title="false"/>
</apex:page>

After saving this markup, refresh your browser with the id query string parameter but without the cid parameter in the URL For
example,
[Link]

Initially the contact detail page is not rendered, but when you click a contact name the page renders the appropriate detail view.
Note: If you use the id parameter in a URL, it must refer to the same entity referred to in the standard controller.

SEE ALSO:
Controller Methods

Using Ajax in a Page


Some Visualforce components are Ajax aware and allow you to add Ajax behaviors to a page without having to write any JavaScript.
The following topics provide examples:
Implementing Partial Page Updates with Command Links and Buttons
Providing Status for Asynchronous Operations
Applying Ajax Behavior to Events on Any Component

Implementing Partial Page Updates with Command Links and Buttons


One of the most widely used Ajax behaviors is a partial page update, in which only a specific portion of a page is updated following some
user action, rather than a reload of the entire page.
The simplest way to implement a partial page update is to use the reRender attribute on an <apex:commandLink> or
<apex:commandButton> tag to identify a component that should be refreshed. When a user clicks the button or link, only the
identified component and all of its child components are refreshed.
For example, consider the contact list example shown in Getting and Setting Query String Parameters on a Single Page on page 41. In
that example, when a user clicks the name of a contact in the list to view the details for that contact, the entire page is refreshed as a
result of this action. With just two modifications to that markup, we can change the behavior of the page so that only the area below
the list refreshes:
1. First, create or identify the portion of the page that should be rerendered. To do this, wrap the <apex:detail> tag in an
<apex:outputPanel> tag, and give the output panel an id parameter. The value of id is the name that we can use
elsewhere in the page to refer to this area. It must be unique in the page.
2. Next, indicate the point of invocation (the command link) that we want to use to perform a partial page update of the area that we
just defined. To do this, add a reRender attribute to the <apex:commandLink> tag, and give it the same value that was
assigned to the output panel's id.
The final markup looks like this:
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$[Link]}!">
You are displaying contacts from the {![Link]} account.

42

Getting a Quick Start with Visualforce

Providing Status for Asynchronous Operations

Click a contact's name to view his or her details.


</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:form>
<apex:dataTable value="{![Link]}" var="contact" cellPadding="4"
border="1">
<apex:column>
<apex:commandLink rerender="detail">
{![Link]}
<apex:param name="cid" value="{![Link]}"/>
</apex:commandLink>
</apex:column>
</apex:dataTable>
</apex:form>
</apex:pageBlock>
<apex:outputPanel id="detail">
<apex:detail subject="{!$[Link]}" relatedList="false"
title="false"/>
</apex:outputPanel>
</apex:page>

After saving the page, click any contact and notice how the detail component displays without a complete page refresh.
Note: You cannot use the reRender attribute to update content in a table.

Providing Status for Asynchronous Operations


Ajax behaviors, such as partial page updates, are asynchronous events that occur in the background while a page user continues to
work. For good usability, designers often add a status element to alert the user of any background activity currently in progress.
Visualforce supports status updates with the <apex:actionStatus> tag. This tag allows you to display text at the beginning or
end of a background event with the startText or stopText attributes, or, for more advanced developers, allows you to display
an image or other component.
For this example, we'll add status text to the contact list page that we have been developing. After a user clicks the name of a contact,
the detail area displays the text, Requesting... while the detail area is rendered.
To implement the message, wrap <apex:actionStatus> around the <apex:detail> component, since that is the component
being updated asynchronously. In between the two tags, add an <apex:facet> tag named stop.
A facet consists of content in an area of a Visualforce component that provides contextual information about the data that is presented
in the component. For example, <apex:dataTable> supports facets for the header, footer, and caption of a table, while
<apex:column> only supports facets for the header and footer of the column. The <apex:facet> component allows you to
override the default facet on a Visualforce component with your own content. Facets only allow a single child within the start and close
tags.
Note: Not all components support facets. Those that do are listed in the Standard Component Reference.
In the following example, <apex:actionStatus> supports a facet named stop that contains the component that should be
displayed as soon as the action completesin this case, the detail area:
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$[Link]}!">
You are displaying contacts from the {![Link]} account.
Click a contact's name to view his or her details.

43

Getting a Quick Start with Visualforce

Applying Ajax Behavior to Events on Any Component

</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:form>
<apex:dataTable value="{![Link]}" var="contact" cellPadding="4"
border="1">
<apex:column>
<apex:commandLink rerender="detail">
{![Link]}
<apex:param name="cid" value="{![Link]}"/>
</apex:commandLink>
</apex:column>
</apex:dataTable>
</apex:form>
</apex:pageBlock>
<apex:outputPanel id="detail">
<apex:actionStatus startText="Requesting...">
<apex:facet name="stop">
<apex:detail subject="{!$[Link]}"
relatedList="false" title="false"/>
</apex:facet>
</apex:actionStatus>
</apex:outputPanel>
</apex:page>

Remember when you visit this page, to include an ID as part of the URL. For example,
[Link]

Applying Ajax Behavior to Events on Any Component


Using command links and buttons to implement a partial page update is relatively simple, but suppose you want to have the same page
update occur just by hovering the mouse over a contact's name?
To do this with the contact list example, remove the <apex:commandLink> tag from the data table and wrap the contact name
in an <apex:outputPanel> tag instead. Within this output panel, add an <apex:actionSupport> element as a sibling
of the contact's name:
The <apex:outputPanel> tag defines the area over in which we want the specialized behavior.
The <apex:actionSupport> tag defines the partial page update behavior that was implemented previously by the command
link.
The event attribute specifies the DOM event that should trigger the update. Whereas <apex:commandLink> only
executes during the onclick event, <apex:actionSupport> can execute on any valid event such as onclick, ondblclick,
or, for this example, onmouseover.
The reRender attribute specifies which part of the page should refresh.
The <apex:param> tag sets the value of the cid query string parameter when the specified event occurs.
The resulting markup looks like this:
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$[Link]}!">
You are displaying contacts from the {![Link]} account.
Mouse over a contact's name to view his or her details.
</apex:pageBlock>

44

Getting a Quick Start with Visualforce

Applying Ajax Behavior to Events on Any Component

<apex:pageBlock title="Contacts">
<apex:form>
<apex:dataTable value="{![Link]}" var="contact" cellPadding="4"
border="1">
<apex:column>
<apex:outputPanel>
<apex:actionSupport event="onmouseover" rerender="detail">
<apex:param name="cid" value="{![Link]}"/>
</apex:actionSupport>
{![Link]}
</apex:outputPanel>
</apex:column>
</apex:dataTable>
</apex:form>
</apex:pageBlock>
<apex:outputPanel id="detail">
<apex:actionStatus startText="Requesting...">
<apex:facet name="stop">
<apex:detail subject="{!$[Link]}" relatedList="false"
title="false"/>
</apex:facet>
</apex:actionStatus>
</apex:outputPanel>
</apex:page>

After saving the page, move the mouse over any contact and notice that the detail area refreshes appropriately without clicking on it.
SEE ALSO:
Using JavaScript in Visualforce Pages

45

CHAPTER 4

Customizing the Appearance and Output of


Visualforce Pages

Visualforce pages and components output HTML thats sent to the browser for rendering. Visualforces HTML generation is sophisticated,
automatically providing page structure, contents, and styling. Visualforce also provides a number of ways to alter Visualforces default
HTML, substitute your own, or associate additional resources, such as CSS stylesheets or JavaScript files, with a page.

Styling Visualforce Pages


Its easy to style a Visualforce page, either by mimicking the look and feel of a standard Salesforce page, or by using your own stylesheets
or content types.
Many Visualforce components have a style or styleClass attribute. Defining either of these attributes allows you to associate
CSS code with the component. Custom CSS code enables you to change the default visual style of a component, including its width,
height, color, and font.

Using Salesforce Styles


Many Visualforce components already have the look and feel of the same components in Salesforce, such as the related list in a detail
page, or a section header. Part of the styling of these components, including the components color scheme, is based on the tab on
which the component appears. You can specify the tab style that should be used to style a component by associating a page with a
standard controller, or by setting the tabStyle attribute on the <apex:page> or <apex:pageBlock> tags.
When you use a standard controller with a Visualforce page, your new page takes on the style of the associated objects standard
tab in Salesforce. It also allows you to access the methods and records associated with the associated object.
When you use a custom controller, the tabStyle attribute of an <apex:page> tag allows you to mimic the look and feel of
the associated Salesforce page. If you only want portions of the page to be similar to a Salesforce page, you can use the tabStyle
attribute on the <apex:pageBlock> tag. For an example, see Defining Getter Methods on page 117.

Extending Salesforce Styles with Stylesheets


Use the <apex:stylesheet> tag to add additional stylesheets to a page. Use the style or styleClass attribute available
on most Visualforce components to connect them to style definitions in your stylesheets. This technique lets you extend the Salesforce
styles with your own.
The following markup shows a very basic page. The <apex:stylesheet> tag references a CSS stylesheet that is saved as a static
resource named TestStyles and listed on the Static Resources page. Its referenced by the $Resource global variable in the
<apex:stylesheet> tags value attribute. The styleClass attribute of the <apex:outputText> tag uses the sample
style class defined in the style sheet.
<apex:page>
<apex:stylesheet value="{!$[Link]}"/>

46

Customizing the Appearance and Output of Visualforce Pages

Using Custom Styles

<apex:outputText value="Styled Text in a sample style class" styleClass="sample"/>


</apex:page>

This is the style sheet used for this example.


.sample {
font-weight: bold;
}

Using Custom Styles


Use the <apex:stylesheet> tag or static HTML to include your own style sheet or styles.
For HTML tags, you can define inline CSS code, just like in a regular HTML page.
<apex:page>
<style type="text/css">
p { font-weight: bold; }
</style>
<p>This is some strong text!</p>
</apex:page>

This example references a style sheet that is defined as a static resource. First, create a style sheet and upload it as a static resource named
customCSS.
h1 { color: #f00; }
p { background-color: #eec; }
newLink { color: #f60; font-weight: bold; }

Next, create a page that refers to this static resource.


<apex:page showHeader="false">
<apex:stylesheet value="{!$[Link]}" />
<h1>Testing Custom Stylesheets</h1>
<p>This text could go on forever...<br/><br/>
But it won't!</p>
<apex:outputLink value="[Link] styleClass="newLink">
Click here to switch to [Link]
</apex:outputLink>
</apex:page>

Tip: If youre not using Salesforce styles, you can shrink your page size by preventing the standard Salesforce style sheets from
loading. To prevent loading, set the standardStylesheets attribute on the <apex:page> component to false.
<apex:page standardStylesheets="false">
<!-- page content here -->
</apex:page>

If you dont load the Salesforce style sheets, components that require them dont display correctly.
Visualforce components that produce HTML have pass-through style and styleClass attributes. These attributes allow you to
use your own styles and style classes to control the look and feel of the resulting HTML. style allows you to set styles directly on a

47

Customizing the Appearance and Output of Visualforce Pages

Suppressing the Salesforce User Interface and Styles

component, while styleClass lets you attach classes for styles defined elsewhere. For example, the following code sets the class
of the <apex:outputText> and applies a style.
<apex:page>
<style type="text/css">
.asideText { font-style: italic; }
</style>
<apex:outputText style="font-weight: bold;"
value="This text is styled directly."/>
<apex:outputText styleClass="asideText"
value="This text is styled via a stylesheet class."/>
</apex:page>

To apply a style using a DOM ID, use CSS attribute selectors for the style definition. See Defining Styles for a Components DOM ID on
page 49.
If you intend to use images in your style sheet, zip the images with the CSS file, and upload the file as a single static resource. For example,
suppose your CSS file has a line like the following.
body { background-image: url("images/[Link]") }

Combine the entire images directory and the parent CSS file into a single zip file. In this example, the zip file resource name is myStyles.
<apex:stylesheet value="{!URLFOR($[Link], '[Link]')}"/>

Warning: If a style sheet has an empty string in a url value, you cant render that page as a PDF. For example, the style rule
body { background-image: url(""); } prevents any page that includes the rule from being rendered as a PDF.

Suppressing the Salesforce User Interface and Styles


By default, Visualforce pages adopt the same visual styling and user interface chrome as the rest of Salesforce. This makes it easy for
you to create pages that look like theyre built right into Salesforce. If you dont want a page to have the Salesforce look and feel, you
can suppress various aspects of the Salesforce page and visual design.
Its easy to create pages with a different look and feel. You can change the page-level user interface resources added by Visualforce using
the following attributes on the <apex:page> component.
sidebarSet to false to suppress the standard sidebar. Removing the sidebar gives your page a wider canvas. For example,
you can show more columns in a table.
This attribute doesnt affect the rest of the Salesforce look and feel. You can continue to use components like <apex:pageBlock>,
<apex:detail>, and <apex:inputField> that render with Salesforce user interface styling.
showHeaderSet to false to suppress the standard Salesforce page design. The header, tabs, and sidebar are removed, along
with their associated style sheets and JavaScript resources. You have a blank page ready to fill in with your own user interface.
It does not, however, suppress all the style sheets that provide the Salesforce visual design. Visualforce components that you add to
the page continue to adopt the Salesforce visual design.
standardStylesheetsSet to false, along with setting showHeader to false, to suppress the inclusion of the style
sheets that support the Salesforce visual design. When you suppress the standard style sheets, your page is completely unstyled,
except for your own style sheets.

48

Customizing the Appearance and Output of Visualforce Pages

Defining Styles for a Components DOM ID

Note: If you dont load the Salesforce style sheets, components that require them dont display correctly.
Setting this attribute to false has no effect if showHeader isnt also set to false.

Defining Styles for a Components DOM ID


Use CSS attribute selectors for the style definition if you want to apply a style using a DOM ID. Attribute selectors rely on the definition
of an attribute, rather than an HTML tag, to apply a CSS style.
You can set the id value on any Visualforce component to set its DOM ID. However, the id in the rendered HTML is usually preprended
with the id of parent components, as part of Visualforces automatic ID generation process. For instance, the actual HTML id of the
following code is j_id0:myId:
<apex:page>
<apex:outputText id="myId" value="This is less fancy."/>
</apex:page>

Your CSS should take this into consideration by using an attribute selector:
<apex:page>
<style type="text/css">
[id*=myId] { font-weight: bold; }
</style>
<apex:outputText id="myId" value="This is way fancy !"/>
</apex:page>

This selector matches any DOM ID that contains myId anywhere within the ID, so the id you set on a Visualforce component should
be unique on the page if you intend to use it for styling purposes.

Using Styles from Salesforce Stylesheets


Salesforce uses different stylesheets (.css files) throughout the application to ensure that every tab conforms to the Salesforce look and
feel. These stylesheets are automatically included on a Visualforce page unless you specify false for the showHeader attribute of
the <apex:page> tag.
Warning: Salesforce stylesheets arent versioned, and the appearance and class names of components change without notice.
Salesforce strongly recommends that you use Visualforce components that mimic the look-and-feel of Salesforce styles instead
of directly referencingand depending uponSalesforce stylesheets.
When you disable the inclusion of the Salesforce stylesheets, only your custom stylesheets affect the styling of the page. For the purposes
of building up styles that partially or fully match the Salesforce look and feel, you might want to look at and use selected contents from
the default stylesheets.
The following stylesheets contain style classes you can reference. They are located in the /dCSS/ directory of your Salesforce instance.
[Link] Contains the majority of style definitions for standard objects and tabs.
[Link] Contains style definitions for custom tabs.
Important: Salesforce doesnt provide notice of changes to or documentation of the built-in styles. Use at your own risk.

49

Customizing the Appearance and Output of Visualforce Pages

Identifying the Salesforce Style Your Users See

Identifying the Salesforce Style Your Users See


When youre creating a Visualforce page, its often useful to know the Salesforce look and feel your user expects, in order to render a
page that matches their style. For example, some users have the choice to customize their look and feel. Youll need to design your
Visualforce pages to take these differences into consideration.
There are two global variables that can help you identify which style a user sees: $[Link] and
$[Link]. The difference between the two variables is that $[Link] returns the look and feel the
user is supposed to see, while $[Link] returns the look and feel the user actually sees. For example, a user
may have the preference and permissions to see the Lightning Experience look and feel, but if they are using a browser that doesnt
support that look and feel, for example, older versions of Internet Explorer, $[Link] returns a different value.
Both variables return one of the following values:
Theme1Obsolete Salesforce theme
Theme2Salesforce Classic 2005 user interface theme
Theme3Salesforce Classic 2010 user interface theme
Theme4dModern Lightning Experience Salesforce theme
Theme4tSalesforce1 mobile Salesforce theme
PortalDefaultSalesforce Customer Portal theme
WebstoreSalesforce AppExchange theme
Suppose a developer has hard coded some CSS styles to resemble Salesforce. In order to preserve the same look and feel on the Visualforce
page for new styles, the developer needs to select between several stylesheets to handle the preferences of the user. The following
example shows one possible way of accomplishing this:
<apex:page standardController="Account">
<apex:variable var="newUI" value="newSkinOn"
rendered="{!$[Link] = 'Theme3'}">
<apex:stylesheet value="{!URLFOR($[Link], '[Link]')}" />
</apex:variable>
<apex:variable var="oldUI" value="oldSkinOn"
rendered="{!$[Link] != 'Theme3'}">
<apex:stylesheet value="{!URLFOR($[Link], '[Link]')}" />
</apex:variable>
<!-- Continue page design -->
</apex:page>

Notice in this example that:


Using the rendered attribute you can toggle which sections display.
Since the <apex:stylesheet> tag doesn't have a rendered attribute, youll need to wrap it in a component that does.
Even if a new look and feel is enabled for your users, they may not be running the right browser or accessibility settings to see it. Heres
a code example that makes use of the $[Link] variable to present alternate information to the user:
<apex:page showHeader="true" tabstyle="Case">
<apex:pageMessage severity="error" rendered="{!$[Link] = 'Theme3' &&
$[Link] != 'Theme3'}">
We've noticed that the new look and feel is enabled for your organization.
However, you can't take advantage of its brilliance. Please check with
your administrator for possible reasons for this impediment.
</apex:pageMessage>

50

Customizing the Appearance and Output of Visualforce Pages

HTML Comments and IE Conditional Comments

<apex:ListViews type="Case" rendered="{!$[Link] = 'Theme3' &&


$[Link] = 'Theme3'}"/>
</apex:page>

Notice that although $[Link] equals Theme3, $[Link] doesnt, and so the page wont render
to its full potential.

HTML Comments and IE Conditional Comments


Visualforce removes most HTML and XML comments from the page before rendering, without processing their contents. Internet Explorer
conditional comments, however, wont be removed, allowing you to include IE-specific resources and meta tags.
Internet Explorer conditional comments are most commonly used to address browser compatibility issues, generally with older versions
of IE. Although conditional comments work wherever theyre used on the page, theyre frequently placed inside the pages <head>
tags, where they can be used to include version-specific stylesheets or JavaScript compatibility shims.
To place conditional comments inside a pages <head> tag, disable the standard Salesforce header, sidebar, and stylesheets, and add
your own <head> and <body> tags:
<apex:page docType="html-5.0" showHeader="false" standardStylesheets="false">
<head>
<!-- Base styles -->
<apex:stylesheet value="{!URLFOR($[Link], 'css/[Link]')}"/>

<!--[if lt IE 7]>
<script type="text/javascript"
src="{!URLFOR($[Link], 'js/[Link]')}>
</script>
<link rel="stylesheet" type="text/css"
href="{!URLFOR($[Link], 'css/[Link]')}"
/>
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css"
href="{!URLFOR($[Link], 'css/[Link]')}" />
<![endif]-->
</head>
<body>
<h1>Browser Compatibility</h1>
<p>It's not just a job. It's an adventure.</p>
</body>
</apex:page>

Visualforce doesnt support or evaluate Visualforce tags, for example, <apex:includeScript/>, within standard HTML comments.
However, it will evaluate the following expressions within IE conditional comments:
Global variables, such as $Resource and $User
The URLFOR() function
See Microsofts documentation for Internet Explorer conditional comments for further details of how to use them.

51

Customizing the Appearance and Output of Visualforce Pages

HTML Tags Added or Modified by Visualforce

HTML Tags Added or Modified by Visualforce


By default, Visualforce automatically adds required HTML tags to a page to ensure the result is a valid HTML (and XML) document. You
can relax and even override this behavior.
For pages using this automatic behavior, Visualforce adds HTML tags in two contexts: a simpler GET request context, when a page is
initially loaded and rendered; and a POSTBACK context, when an <apex:form> is submitted back, an Ajax request is made using
an <apex:actionXXX> tag, and so on.
In a GET context, the HTML rendered by Visualforce is somewhat relaxed. It adds <html> tags to wrap the page, <head> tags to
wrap the pages title and any stylesheets or scripts added to the page using <apex:stylesheet> or <apex:includeScript>,
and <body> tags to wrap the pages content.
HTML generated by other Visualforce tags will be complete and valid HTML, and you cant save a Visualforce page with invalid static
XML. However, HTML added by expressions that access controller methods, sObject fields, and other non-Visualforce sources isnt
validated by Visualforce before its returned. Its therefore possible to return an invalid XML document via a GET request.
In a POSTBACK context, Visualforce is more strict. Because the contents of the request might need to be inserted into an existing DOM,
the response HTML is post-processed to ensure its valid. This tidying fixes missing and unclosed tags, removes invalid tags or attributes,
and otherwise cleans up invalid HTML so that it will insert cleanly into the DOM of any page its returned back to. This behavior is intended
to ensure that tags that update an existing DOM, such as <apex:actionHandler>, work reliably.

Relaxed Tidying for the HTML5 Doctype


To relax the default HTML tidying for HTML5 applications where it causes problems, set the docType to html-5.0 and the API version
to 28.0 or greater.
Beginning in API version 28.0, the tidying behavior for Visualforce pages with docType="html5.0" changed for the POSTBACK
context, so that HTML5 tags and attributes arent stripped away. Visualforce always validates the XML correctness of every page when
its saved, and requires that the page be well-formed XML, but post-process tidying no longer removes unknown tags or attributes for
POSTBACK requests. This should make it much easier to work with HTML5 and JavaScript frameworks that use HTML attributes
extensively.
Its worth remembering that while modern browsers are very good at doing their own tidying, that behavior is less consistent than
rendering valid markup. Reduced HTML tidying in html5.0 mode represents a smaller safety net, in return for significantly increased
flexibility. We recommend you use this relaxed tidying mode only on HTML5 pages that need it, and with HTML validation and debugging
tools in hand.
Note: In API version 28.0 or greater, the scope of how the docType is determined for a page is different. When child pages are
added to a root page using <apex:include>, if any page in the hierarchy is set to docType="html5.0" and the root
page is set to API version 28.0 or later, the entire page hierarchy is rendered in html5.0 mode.

Manually Override Automatic <html> and <body> Tag Generation


Use the applyHtmlTag and applyBodyTag attributes of the <apex:page> tag to suppress the automatic generation of
<html> and <body> tags, in favor of static markup you add to the page yourself.
Heres an example that illustrates how to do this:
<apex:page showHeader="false" sidebar="false" standardStylesheets="false"
applyHtmlTag="false" applyBodyTag="false" docType="html-5.0">
<html>

52

Customizing the Appearance and Output of Visualforce Pages

Creating an Empty HTML5 Container Page

<body>
<header>
<h1>Congratulations!</h1>
</header>
<article>
<p>This page looks almost like HTML5!</p>
</article>
</body>
</html>
</apex:page>

The attributes act independently of each other; you can use them in any combination of true, false, or unset. When both attributes
are set to true, the default, automatic generation of <html> and <body> tags is preserved. When either is set to false, you are
fully responsible for adding the corresponding tags to your markup. In this mode, Visualforce wont prevent you from creating nonsense
tag combinations or attributes that give even modern browsers fits.
Note: A <head> section is always generated if required, regardless of the values for applyHtmlTag and applyBodyTag.
For example, a <head> tag is generated if you use <apex:includeScript> or <apex:stylesheet> tags, set the
page title, and so on.
Theres one exception to this rule. If applyHtmlTag is set to false and there are no other elements in the page except for
<apex:includeScript>, no <head> is generated. For example, the following code automatically adds <body> tags,
but doesnt add a <head> section:
<apex:page showHeader="false" applyHtmlTag="false">
<html>
<apex:includeScript
value="//[Link]/ajax/libs/jquery/1.9.1/[Link]"/>
</html>
</apex:page>

This behavior shouldnt cause problems for real-world pages.


The applyHtmlTag attribute is available on the <apex:page> tag for Visualforce pages set to API version 27.0 or higher. The
applyBodyTag attribute is available on the <apex:page> tag for Visualforce pages set to API version 28.0 or higher. They both
have the following additional restrictions:
The showHeader attribute must be set to false for the page, for example, <apex:page showHeader="false">.
The contentType attribute must be set to text/html (the default).
The values for the top level, or outermost, <apex:page> tag are used; applyHtmlTag and applyBodyTag attributes on
pages added using the <apex:include> tag are ignored.

Creating an Empty HTML5 Container Page


Use an empty container page when you want to bypass most of Visualforce and add your own markup. A container page is especially
useful for HTML5 and mobile development, and other web apps for which standard Visualforce output isnt desired.
You use Remote Objects, JavaScript remoting, or other [Link] APIs to make service requests and then render the results with
JavaScript.
The following code provides a sample container page to start with.
<apex:page docType="html-5.0" applyHtmlTag="false" applyBodyTag="false"
showHeader="false" sidebar="false" standardStylesheets="false"

53

Customizing the Appearance and Output of Visualforce Pages

Using a Custom Doctype

title="Unused Title">
<html>
<head>
<title>HTML5 Container Page</title>
</head>
<body>
<h1>An Almost Empty Page</h1>
<p>This is a very simple page.</p>
</body>
</html>
</apex:page>

The <apex:page> component and its attributes is the core of a container pages definition.
docType="html-5.0" sets the page to use the modern HTML5 docType.
applyHtmlTag="false" and applyBodyTag="false" tell Visualforce that your markup supplies the <html> and
<body> tags so that it doesnt generate its own.
Note: When you set applyHtmlTag or applyBodyTag to false, the title attribute of the <apex:page>
component is ignored.
The showHeader="false", sidebar="false", and standardStylesheets="false" attributes suppress the
standard header, sidebar, and style sheets that add the Salesforce user interface and visual design to Visualforce pages.
The <head> tag isnt required in a container page, but its a good idea to include it. If you need to add values to the <head> element,
you must add the <head> tag yourself. In that case, Visualforce adds any of its required values to your <head>. Otherwise, Visualforce
renders its own <head> to add any necessary values.
You can use Visualforce components, such as <apex:includeScript>, <apex:stylesheet>, and <apex:image>, to
reference static resources on the page. The output of <apex:includeScript> and <apex:stylesheet> is added to the
<head> element. If you didnt include one, Visualforce adds its own. The <apex:image> output is rendered wherever you place
it on the page.
Note: An empty Visualforce page renders the minimum amount of HTML markup, but it isnt completely empty, or free of
resources you dont control. JavaScript code thats essential for Visualforce, such as instrumentation, is still added. Visualforce also
automatically adds resources required for markup you add. For example, references to Remote Objects or JavaScript remoting
resources, if you use them in your code.

Using a Custom Doctype


You can specify a different doctype (document type, or DTD) for a Visualforce page by using the docType attribute on the
<apex:page> tag. This changes the doctype declaration at the beginning of the page. This is particularly useful if youre working
with HTML5, and might also allow you to address browser compatibility issues.
By default, Visualforce pages are served with a doctype of HTML 4.01 Transitional. Specifically, pages begin with this doctype declaration:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"[Link]

You can specify a different doctype for a Visualforce page by using the docType attribute on the <apex:page> tag.

54

Customizing the Appearance and Output of Visualforce Pages

Using a Custom ContentType

The docType attribute takes a string representing the document type. The format of the string is:
<doctype>-<version>[-<variant>]

where
doctype is either html or xhtml
version is a decimal version number valid for the doctype
variant, if included, is:
strict, transitional, or frameset for all html document types and the xhmtl-1.0 document type, or
<blank> or basic for the xhmtl-1.1 document type
If an invalid document type is specified, the default doctype is used. For more information about valid HTML doctypes, see the list at the
W3C website.
Note: In API 28.0 and greater, the scope of how the docType is determined for a page depends on the entire page hierarchy,
not just the main page. When pages are added to the main page using the <apex:include> tag, if any page in the hierarchy
is set to docType="html-5.0", the entire page hierarchy is rendered in that mode.

Custom Doctype Example


To create a Visualforce page with an XHTML 1.0 Strict document type, use the docType attribute on the <apex:page> tag, and
specify a value of xhtml-1.0-strict:
<apex:page docType="xhtml-1.0-strict" title="Strictly XHTML"
showHeader="false" sidebar="false">
<h1>This is Strict XHTML!</h1>
<p>
Remember to close your tags correctly:<br/>
<apex:image url="/img/[Link]" alt="Person icon"/>
</p>
</apex:page>

Note: Visualforce doesnt alter markup generated by components to match the doctype, nor the markup for standard Salesforce
elements such as the header and sidebar. Salesforce elements are valid for most doctypes and function properly with any doctype,
but if you choose a strict doctype and wish to pass an HTML validation test, you might need to suppress or replace the standard
Salesforce elements.

Using a Custom ContentType


You can specify a different format for a Visualforce page by using the ContentType attribute on the <apex:page> tag. This sets
the Content-Type HTTP header for the response to the value of the pages ContentType attribute.
The ContentType attribute takes a Multipurpose Internet Mail Extension (MIME) media type as a value, such as
application/[Link]-excel, text/csv, or image/gif.
Note: Browsers can behave unpredictably if you set an invalid ContentType. For more information about valid MIME media
types, see [Link]

55

Customizing the Appearance and Output of Visualforce Pages

Setting Custom HTML Attributes on Visualforce Components

Microsoft Excel ContentType Example


To display Visualforce page data in a Microsoft Excel spreadsheet, use the contentType attribute on the <apex:page> tag, and
specify a value of application/[Link]-excel.
For example, the following page builds a simple list of contacts. Its a simplified version of the example shown in Building a Table of Data
in a Page on page 37.
<apex:page standardController="Account">
<!-- This page must be accessed with an Account Id in the URL. For example:
[Link] -->
<apex:pageBlock title="Contacts">
<apex:pageBlockTable value="{![Link]}" var="contact">
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

To display this page in Excel, add the contentType attribute to the <apex:page> tag, as follows:
<apex:page standardController="Account" contentType="application/[Link]-excel">
<apex:pageBlock title="Contacts">
<apex:pageBlockTable value="{![Link]}" var="contact">
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

If the page doesnt display properly in Excel, try a different MIME type, such as text/csv.

Setting Custom HTML Attributes on Visualforce Components


You can add arbitrary attributes to many Visualforce components that are passed through to the rendered HTML. This is useful, for
example, when using Visualforce with JavaScript frameworks, such as jQuery Mobile, AngularJS, and Knockout, which use data-* or
other attributes as hooks to activate framework functions.
Pass-through attributes can also be used to improve usability with HTML5 features such as placeholder ghost text, pattern
client-side validation, and title help text attributes.
Important: The behavior of HTML5 features is determined by the users browser, not Visualforce, and varies considerably from
browser to browser. If you want to use these features, test early and often on every browser and device you plan to support.
To add a pass-through attribute to, for example, an <apex:outputPanel> component, prefix the attribute with html- and set
the attribute value as normal.
<apex:page showHeader="false" standardStylesheets="false" doctype="html-5.0">
<apex:outputPanel layout="block" html-data-role="panel" html-data-id="menu">
<apex:insert name="menu"/>

56

Customizing the Appearance and Output of Visualforce Pages

Setting Custom HTML Attributes on Visualforce Components

</apex:outputPanel>
<apex:outputPanel layout="block" html-data-role="panel" html-data-id="main">
<apex:insert name="main"/>
</apex:outputPanel>
</apex:page>

This produces the following HTML output.


<!DOCTYPE HTML>
<html>
<head> ... </head>
<div id="..." data-id="menu" data-role="panel">
<!-- contents of menu -->
</div>
<div id="..." data-id="main" data-role="panel">
<!-- contents of main -->
</div>
</html>

Every attribute that begins with html- is passed through to the resulting HTML, with the html- removed.
Note: Pass-through attributes that conflict with built-in attributes for the component generate a compilation error.
Pass-through attributes are supported by the following Visualforce components.
<apex:column>
<apex:commandButton>
<apex:commandLink>
<apex:component>
<apex:dataTable>
<apex:form>
<apex:iframe>
<apex:image>
<apex:includeScript>
<apex:input>
<apex:inputCheckbox>
<apex:inputField>
<apex:inputHidden>
<apex:inputSecret>
<apex:inputText>
<apex:inputTextarea>
<apex:messages>
<apex:outputField>
<apex:outputLabel>
<apex:outputLink>

57

Customizing the Appearance and Output of Visualforce Pages

Offline Caching Using the HTML5 manifest Attribute

<apex:outputPanel>
<apex:outputText>
<apex:page>
<apex:pageBlock>
<apex:pageBlockButtons>
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:pageBlockTable>
<apex:panelBar>
<apex:panelBarItem>
<apex:panelGrid>
<apex:sectionHeader>
<apex:selectCheckboxes>
<apex:selectList>
<apex:selectOption>
<apex:selectOptions>
<apex:selectRadio>
<apex:stylesheet>
<apex:tab>
<apex:tabPanel>
For additional information about individual components, including the specifics of where pass-through attributes are added to their
rendered HTML, see Standard Component Reference on page 347.
To create HTML markup that cant be generated using components that support pass-through attributes, combine Visualforce tags with
static HTML. For example, to create a jQuery Mobile listview, combine the <apex:repeat> tag with the HTML tags you need.
<ul data-role="listview" data-inset="true" data-filter="true">
<apex:repeat value="{! someListOfItems}" var="item">
<li><a href="#">{! [Link]}</a></li>
</apex:repeat>
</ul>

Pass-through attributes arent supported in dynamic Visualforce.

Offline Caching Using the HTML5 manifest Attribute


Use the manifest attribute of the <apex:page> tag to set an HTML5 cache manifest for offline caching of a pages critical
resources.
The value of the manifest attribute is passed through to the generated HTML. For example:
<apex:page showHeader="false" sidebar="false" standardStylesheets="false"
docType="html-5.0" manifest="/apex/CacheManifest">
<header>
<h1>Congratulations!</h1>
</header>

58

Customizing the Appearance and Output of Visualforce Pages

Render a Visualforce Page as a PDF File

<article>
<p>This page looks almost like HTML5!</p>
</article>
</apex:page>

Renders the following <html> tag:


<html manifest="/apex/CacheManifest">

The manifest attribute is available on the <apex:page> tag for Visualforce pages set to API version 28.0 or higher, and also
requires that the applyHtmlTag is set to true (the default).
You can use Visualforce to provide a pages cache manifest. For example, the CacheManifest page referenced above might be:
<apex:page contentType="text/cache-manifest" applyHtmlTag="false"
standardStylesheets="false" showHeader="false">
CACHE MANIFEST
[Link]
[Link]
images/[Link]
scripts/[Link]
</apex:page>

Render a Visualforce Page as a PDF File


You can generate a downloadable, printable PDF file of a Visualforce page using the PDF rendering service.
Convert a page to PDF by changing the <apex:page> tag.
<apex:page renderAs="pdf">

A Visualforce page rendered as a PDF file displays either in the browser or is downloaded, depending on the browsers settings. Specific
behavior depends on the browser, version, and user settings, and is outside the control of Visualforce.
The following page includes some account details and renders as a PDF file.
<apex:page standardController="Account" renderAs="pdf">
<apex:stylesheet value="{!URLFOR($[Link],'[Link]')}"/>
<h1>Welcome to Universal Samples!</h1>
<p>Thank you, <b><apex:outputText value=" {![Link]}"/></b>, for
becoming a new account with Universal Samples.</p>
<p>Your account details are:</p>
<table>
<tr><th>Account Name</th>
<td><apex:outputText value="{![Link]}"/></td>
</tr>
<tr><th>Account Rep</th>
<td><apex:outputText value="{![Link]}"/></td>
</tr>
<tr><th>Customer Since</th>

59

Customizing the Appearance and Output of Visualforce Pages

Add a Save as PDF Feature to a Visualforce Page

<td><apex:outputText value="{0,date,long}">
<apex:param value="{![Link]}"/>
</apex:outputText></td>
</tr>
</table>
</apex:page>

A Visualforce Page Rendered as a PDF File

Add a Save as PDF Feature to a Visualforce Page


You can add a Save as PDF element to a page to dynamically toggle between rendering the page as HTML or as a PDF file. You can also
set the name for the PDF file.
The following page presents a list of contacts for an account. You can display it on screen, or download it as a PDF file by clicking the
Save to PDF link.
<apex:page showHeader="false" standardStylesheets="false"
standardController="Account" extensions="SaveAsPdfExtension"
contentType="{! renderedContentType }" renderAs="{! renderingService }">

60

Customizing the Appearance and Output of Visualforce Pages

Add a Save as PDF Feature to a Visualforce Page

<!-This page must be called with an Account ID in the URL, e.g.:


[Link]
-->
<apex:form rendered="{! renderingService != 'PDF' }"
style="text-align: right; margin: 10px;">
<apex:commandLink action="{! saveToPdf }" value="Save to PDF">
<apex:param assignTo="{! renderedFileName }" value="[Link]"/>
</apex:commandLink>
<hr/>
</apex:form>
<h1>Contacts for {! [Link]}</h1>
<apex:dataTable value="{! [Link] }" var="contact">
<apex:column headerValue="Name" value="{! [Link]
<apex:column headerValue="Title" value="{! [Link]
<apex:column headerValue="Phone" value="{! [Link]
<apex:column headerValue="Email" value="{! [Link]
</apex:dataTable>

}"/>
}"/>
}"/>
}"/>

<hr/>
<!-- A little bit of info about the page's rendering;
see how it changes when saved as a PDF. -->
contentType: <apex:outputText value=" {! renderedContentType }"/><br/>
renderingService: <apex:outputText value=" {! renderingService }"/><br/>
</apex:page>

This example has two important elements. First, the renderAs and contentType attributes of the <apex:page> component
are set dynamically using expressions. The values of these expressions control into which format the page is rendered.
The other element is the <apex:form>, which provides a user interface for saving the page to PDF. The form has one element, an
<apex:commandLink> that calls the saveToPdf action method. An <apex:param> component provides a name for the
PDF file, which is used in the controller code to set the file name.
The form is only displayed when the page is rendered as HTML; its not visible in the PDF version. This display trick is accomplished by
setting the rendered attribute on the <apex:form> component to false when the page is rendered as a PDF file.
Heres the controller extension, which you can easily reuse in your own pages.
public class SaveAsPdfExtension {
// Required extension constructor (empty, no-op)
public SaveAsPDFExtension([Link] controller) {}
// Determines what kind of rendering to use for the page request
public String renderingService { get; private set; }
// Allow the page to set the PDF file name
public String renderedFileName {
get;
set { renderedFileName = [Link](value); }
}

61

Customizing the Appearance and Output of Visualforce Pages

Add a Save as PDF Feature to a Visualforce Page

// Rendered content MIME type, used to affect HTTP response


public String renderedContentType {
get {
String renderedContentType = 'text/html'; // the default
if( ! [Link]() ) {
// Provides a MIME type for a PDF document
renderedContentType = 'application/pdf';
// Add a file name for the PDF file
if( [Link] != null) {
// This is supposed to set the file name, but it doesn't work
renderedContentType += '#' + [Link];
// This is a work-around to set the file name
[Link]().getHeaders().put(
'content-disposition', 'attachment; filename=' +
[Link]);
}
}
return renderedContentType;
}
}
// Are we rendering to HTML or PDF?
public Boolean renderingAsHtml() {
return ( (renderingService == null) ||
( ! [Link]('PDF')) );
}
// Action method to save (or "print") to PDF
public PageReference saveToPdf() {
renderingService = 'PDF';
return null;
}
// Private helper -- basic, conservative santization
private String sanitizeFileName(String unsafeName) {
String allowedCharacters = '0-9a-zA-Z-_.';
String sanitizedName =
[Link]('[^' + allowedCharacters + ']', '');
// You might also want to check filename length,
// that the filename ends in '.pdf', etc.
return(sanitizedName);
}
}

The main part of the extension is simple. The renderingService property controls whether the page is rendered in HTML or PDF.
Its value defaults to null when the page is loaded, and changes to PDF if the saveToPdf action method is called. The renderAs
attribute of the <apex:page> component references renderingService. When its anything other than PDF the page renders
normally as HTML. When its PDF the pageyou guessed itrenders as a PDF file.

62

Customizing the Appearance and Output of Visualforce Pages

Render a Visualforce Page as PDF from Apex

The renderedContentType property provides a MIME type value that is used by the contentType attribute of the Visualforce
<apex:page> component. Setting this value affects the server response. It adds an HTTP header that tells the client browser the
format of the responsein this case, either HTML or PDF.
The renderedContentType property also sets the file name for the downloaded PDF file. It gets the file name from the
renderedFileName property, which is set using the <apex:param> component in the page. Although its documented that
appending # and a file name to the contentType sets the file name thats sent to the client browser, this convention doesnt work.
Therefore, a header is set to provide the file name.
If you dont need to set the file name for the PDF download, you can ignore the renderedContentType and
renderedFileName properties. This simpler approach to adding a save to PDF function is demonstrated in Fonts Available When
Using Visualforce PDF Rendering on page 68.

Render a Visualforce Page as PDF from Apex


You can use the [Link]() method in Apex to render a Visualforce page as PDF data. Then use
Apex code to convert that PDF data to an email attachment, a document, a Chatter post, and so on.
The following example is a simple three element form that selects an account and a report format, and then sends the resulting report
to the specified email address.
<apex:page title="Account Summary" tabStyle="Account"
controller="PdfEmailerController">
<apex:pageMessages />
<apex:form >
<apex:pageBlock title="Account Summary">
<p>Select a recently modified account to summarize.</p>
<p/>
<apex:pageBlockSection title="Report Format">
<!-- Select account menu -->
<apex:pageBlockSectionItem>
<apex:outputLabel for="selectedAccount" value="Account"/>
<apex:selectList id="selectedAccount" value="{! selectedAccount }"
size="1">
<apex:selectOption /> <!-- blank by default -->
<apex:selectOptions value="{! recentAccounts }" />
</apex:selectList>
</apex:pageBlockSectionItem>
<!-- Select report format menu -->
<apex:pageBlockSectionItem >
<apex:outputLabel for="selectedReport" value="Summary Format"/>
<apex:selectList id="selectedReport" value="{! selectedReport }"
size="1">
<apex:selectOptions value="{! reportFormats }" />
</apex:selectList>
</apex:pageBlockSectionItem>
<!-- Email recipient input field -->

63

Customizing the Appearance and Output of Visualforce Pages

Render a Visualforce Page as PDF from Apex

<apex:pageBlockSectionItem >
<apex:outputLabel for="recipientEmail" value="Send To"/>
<apex:inputText value="{! recipientEmail }" size="40"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton action="{! sendReport }" value="Send Account Summary" />
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

This page is a simple user interface. When youre generating a PDF file from Apex, all the action is in the Apex code.
In this example, that code is in the PdfEmailerController class thats specified as the pages controller.
public with sharing class PdfEmailerController {
// Form fields
public Id selectedAccount
{ get; set; }
public String selectedReport { get; set; }
public String recipientEmail { get; set; }

// Account selected on Visualforce page


// Report selected
// Send to this email

// Action method for the [Send Account Summary] button


public PageReference sendReport() {
// NOTE: Abbreviated error checking to keep the code sample short
//
You, of course, would never do this little error checking
if([Link]([Link]) || [Link]([Link])) {
[Link](new
[Link]([Link],
'Errors on the form. Please correct and resubmit.'));
return null; // early out
}
// Get account name for email message strings
Account account = [SELECT Name
FROM Account
WHERE Id = :[Link]
LIMIT 1];
if(null == account) {
// Got a bogus ID from the form submission
[Link](new
[Link]([Link],
'Invalid account. Please correct and resubmit.'));
return null; // early out
}
// Create email
[Link] message = new [Link]();

64

Customizing the Appearance and Output of Visualforce Pages

Render a Visualforce Page as PDF from Apex

[Link](new String[]{ [Link] });


[Link]('Account summary for ' + [Link]);
[Link]('Here\'s a summary for the ' + [Link] + ' account.');
// Create PDF
PageReference reportPage =
(PageReference)[Link]([Link]);
[Link]().put('id', [Link]);
Blob reportPdf;
try {
reportPdf = [Link]();
}
catch (Exception e) {
reportPdf = [Link]([Link]());
}
// Attach PDF to email and send
[Link] attachment = new [Link]();
[Link]('application/pdf');
[Link]('AccountSummary-' + [Link] + '.pdf');
[Link](false);
[Link](reportPdf);
[Link](new [Link][]{ attachment });
[Link](new [Link][]{ message });
[Link](new
[Link]([Link],
'Email sent with PDF attachment to ' + [Link]));
return null; // Stay on same page, even on success
}

/***** Form Helpers *****/


// Ten recently-touched accounts, for the Account selection menu
public List<SelectOption> recentAccounts {
get {
if(null == recentAccounts){
recentAccounts = new List<SelectOption>();
for(Account acct : [SELECT Id,Name,LastModifiedDate
FROM Account
ORDER BY LastModifiedDate DESC
LIMIT 10]) {
[Link](new SelectOption([Link], [Link]));
}
}
return recentAccounts;
}
set;
}
// List of available reports, for the Summary Format selection menu
public List<SelectOption> reportFormats {

65

Customizing the Appearance and Output of Visualforce Pages

Render a Visualforce Page as PDF from Apex

get {
if(null == reportFormats) {
reportFormats = new List<SelectOption>();
for(Map <String,Object> report : reports) {
[Link](new SelectOption(
(String)[Link]('name'), (String)[Link]('label')));
}
}
return reportFormats;
}
set;
}

/***** Private Helpers *****/


// List of report templates to make available
// These are just Visualforce pages you might print to PDF
private Map<String,PageReference> reportPagesIndex;
private List<Map<String,Object>> reports {
get {
if(null == reports) {
reports = new List<Map<String,Object>>();
// Add one report to the list of reports
Map<String,Object> simpleReport = new Map<String,Object>();
[Link]('name', 'simple');
[Link]('label', 'Simple');
[Link]('page',
[Link]);
[Link](simpleReport);
// Add your own, more complete list of PDF templates here
// Index the page names for the reports
[Link] = new Map<String,PageReference>();
for(Map<String,Object> report : reports) {
[Link](
(String)[Link]('name'), (PageReference)[Link]('page'));
}
}
return reports;
}
set;
}
}

This Apex controller can be conceptually divided into four parts.


The three public properties at the beginning capture the values submitted by the three input elements on the form.
The sendReport() action method fires when the Send Account Summary button is clicked.
The two public helper properties supply the values to use in the two select list input elements.
The private helpers at the end encapsulate the list of possible PDF report formats. You can add your own report by creating a
Visualforce page and then adding an entry for it in this section.
When the sendReport() action method fires, the code does the following.

66

Customizing the Appearance and Output of Visualforce Pages

Render a Visualforce Page as PDF from Apex

It performs rudimentary error checking to ensure that the form fields have useful values.
Note: This error checking is inadequate for a form that must survive contact with real people. In your production code perform
more complete form validation.
Next it uses the value of the selected account to look up the name of that account. The account name is used in text thats added
to the email message. This lookup is also an opportunity to further validate the form value and ensure that a real account was selected.
It uses the [Link] class to assemble an email message, setting the To, Subject, and Body email
message values.
The code creates a PageReference for the selected report format and then sets a page request parameter on it. The parameter
is named id, and its value is set to the selected accounts ID. This PageReference represents a specific request to access this
page in the context of the specified account. When getContentAsPdf() is called, the referenced Visualforce page has access
to the specified account, and the page is rendered with that accounts details.
Finally, the PDF data is added to an attachment, and the attachment is added to the email message created earlier. The message is
then sent.
When using [Link](), the return type of the method call is Blob, which stands for binary
large object. In Apex, the Blob data type represents untyped binary data. Its only when the reportPdf variable is added to the
[Link] with a content type of application/pdf that the binary data becomes a PDF file.
In addition, the call to getContentAsPdf() is wrapped in a try/catch block. If the call fails, the catch replaces the hoped
for PDF data with a Blob version of the exceptions message text.
Rendering a Visualforce page as PDF data is treated semantically as a callout to an external service for various reasons. One reason is that
the rendering service can fail in all the same ways that an external service can fail. For instance, the page references external resources
that arent available. Another example is when the page contains too much datausually in the form of imagesor the rendering time
exceeds a limit. For this reason, always wrap the getContentAsPdf() rendering call in a try/catch block when rendering a
Visualforce page as PDF data in Apex.
For completeness, heres the report template page thats rendered into PDF data by the Apex code.
<apex:page showHeader="false" standardStylesheets="false"
standardController="Account">
<!-This page must be called with an Account ID in the request, e.g.:
[Link]
-->
<h1>Account Summary for {! [Link] }</h1>
<table>
<tr><th>Phone</th> <td><apex:outputText value="{! [Link] }"/></td></tr>
<tr><th>Fax</th>
<td><apex:outputText value="{! [Link] }"/></td></tr>
<tr><th>Website</th><td><apex:outputText value="{! [Link] }"/></td></tr>
</table>
<p><apex:outputText value="{! [Link] }"/></p>
</apex:page>

67

Customizing the Appearance and Output of Visualforce Pages

Fonts Available When Using Visualforce PDF Rendering

Fonts Available When Using Visualforce PDF Rendering


Visualforce PDF rendering supports a limited set of fonts. To ensure that PDF output renders as you expect, use the supported font names.
For each typeface, the first font-family name listed is recommended.
Typeface

font-family Values

Arial Unicode MS

Arial Unicode MS

Helvetica

sans-serif
SansSerif
Dialog

Times

serif
Times

Courier

monospace
Courier
Monospaced
DialogInput

Note:
These rules apply to server-side PDF rendering. Viewing pages in a web browser can have different results.
Text styled with a value not listed here uses Times. For example, if you use the word Helvetica, it renders as Times, because
thats not a supported value for the Helvetica font. We recommend using sans-serif.
Arial Unicode MS is the only multibyte font available. Its the only font that provides support for the extended character sets
of languages that dont use the Latin character set.
Web fonts arent supported when the page is rendered as a PDF file. You can use web fonts in your Visualforce pages when
theyre rendered normally.

Testing Font Rendering


You can use the following page to test font rendering with the Visualforce PDF rendering engine.
<apex:page showHeader="false" standardStylesheets="false"
controller="SaveToPDF" renderAs="{! renderAs }">
<apex:form rendered="{! renderAs != 'PDF' }" style="text-align: right; margin: 10px;">
<div><apex:commandLink action="{! print }" value="Save to PDF"/></div>
<hr/>
</apex:form>
<h1>PDF Fonts Test Page</h1>
<p>This text, which has no styles applied, is styled in the default font for the

68

Customizing the Appearance and Output of Visualforce Pages

Fonts Available When Using Visualforce PDF Rendering

Visualforce PDF rendering engine.</p>


<p>The fonts available when rendering a page as a PDF are as follows. The first
listed <code>font-family</code> value for each typeface is the recommended choice.</p>
<table border="1" cellpadding="6">
<tr><th>Font Name</th><th>Style <code>font-family</code> Value to Use (Synonyms)</th></tr>
<tr><td><span style="font-family: Arial Unicode MS; font-size: 14pt; ">Arial
Unicode MS</span></td><td><ul>
<li><span style="font-family: Arial Unicode MS; font-size: 14pt;">Arial Unicode
MS</span></li>
</ul></td></tr>
<tr><td><span style="font-family: Helvetica; font-size: 14pt;">Helvetica</span></td>
<td><ul>
<li><span style="font-family: sans-serif; font-size: 14pt;">sans-serif</span></li>
<li><span style="font-family: SansSerif; font-size: 14pt;">SansSerif</span></li>
<li><span style="font-family: Dialog; font-size: 14pt;">Dialog</span></li>
</ul></td></tr>
<tr><td><span style="font-family: Times; font-size: 14pt;">Times</span></td><td><ul>
<li><span style="font-family: serif; font-size: 14pt;">serif</span></li>
<li><span style="font-family: Times; font-size: 14pt;">Times</span></li>
</ul></td></tr>
<tr><td><span style="font-family: Courier; font-size: 14pt;">Courier</span></td>
<td><ul>
<li><span style="font-family: monospace; font-size: 14pt;">monospace</span></li>
<li><span style="font-family: Courier; font-size: 14pt;">Courier</span></li>
<li><span style="font-family: Monospaced; font-size: 14pt;">Monospaced</span></li>
<li><span style="font-family: DialogInput; font-size: 14pt;">DialogInput</span></li>
</ul></td></tr>
</table>
<p><strong>Notes:</strong>
<ul>
<li>These rules apply to server-side PDF rendering. You might see different results
when viewing this page in a web browser.</li>
<li>Text styled with any value besides those listed above receives the default font
style, Times. This means that, ironically, while Helvetica's synonyms render as
Helvetica, using "Helvetica" for the font-family style renders as Times.
We recommend using "sans-serif".</li>
<li>Arial Unicode MS is the only multibyte font available, providing support for the
extended character sets of languages that don't use the Latin character set.</li>
</ul>
</p>
</apex:page>

The preceding page uses the following controller, which provides a simple Save to PDF function.
public with sharing class SaveToPDF {
// Determines whether page is rendered as a PDF or just displayed as HTML
public String renderAs { get; set; }

// Action method to "print" to PDF

69

Customizing the Appearance and Output of Visualforce Pages

Visualforce PDF Rendering Considerations and Limitations

public PageReference print() {


renderAs = 'PDF';
return null;
}
}

Visualforce PDF Rendering Considerations and Limitations


When designing Visualforce pages intended to be rendered to PDF, take the following considerations into account. Always verify the
formatting and appearance of the PDF version of your page before putting it into production.
Limitations of the Visualforce PDF rendering service include the following.
PDF is the only supported rendering service.
The PDF rendering service renders PDF version 1.4.
Rendering a Visualforce page as a PDF file is intended for pages designed and optimized for print.
A Visualforce page rendered as a PDF file displays either in the browser or is downloaded, depending on the browsers settings.
Specific behavior depends on the browser, version, and user settings, and is outside the control of Visualforce.
The PDF rendering service renders the markup and data on your page, but it might not render formatting contained within the
contents of rich text area fields added to the page.
Long lines of text that dont have break points, such as a space or dash, cant be wrapped by the PDF rendering service. This most
commonly happens with very long URLs, registry entries, and so on. When these lines are wider than the page, they increase the
width of the pages content beyond the edge of the PDF page. This causes content to flow off the side of the page, cutting it off.
Dont use standard components that arent easily formatted for print, or form elements such as inputs or buttons, or any component
that requires JavaScript to be formatted.
PDF rendering doesnt support JavaScript-rendered content.
PDF rendering isnt supported for pages in Salesforce1.
The font used on the page must be available on the Visualforce PDF rendering service. Web fonts arent supported.
If the PDF file fails to display all the pages text, particularly multibyte characters such as Japanese or accented international characters,
adjust your CSS to use a font that supports them. For example:
<apex:page showHeader="false" applyBodyTag="false" renderAs="pdf">
<head>
<style>
body { font-family: 'Arial Unicode MS'; }
</style>
</head>
<body>

<br/>
This is a sample page: API version 28.0
</body>
</apex:page>

Arial Unicode MS is the only font supported for extended character sets that include multibyte characters.
If you use inline CSS styles, set the API version to 28.0 or later. Also set <apex:page applyBodyTag="false">, and add
static, valid <head> and <body> tags to your page, as in the previous example.

70

Customizing the Appearance and Output of Visualforce Pages

Component Behavior When Rendered as PDF

The maximum response size when creating a PDF file must be less than 15 MB before being rendered as a PDF file. This limit is the
standard limit for all Visualforce requests.
The maximum file size for a generated PDF file is 60 MB.
The maximum total size of all images included in a generated PDF is 30 MB.
PDF rendering doesnt support images encoded in the data: URI scheme format.
The following components dont support double-byte fonts when rendered as PDF.
<apex:pageBlock>
<apex:sectionHeader>
These components arent recommended for use in pages rendered as PDF.
If an <apex:dataTable> or <apex:pageBlockTable> has no <apex:column> components that are rendered,
rendering the page as PDF fails. To work around this issue, set the table components rendered attribute to false if none of
its child <apex:column> components are rendered.

Component Behavior When Rendered as PDF


Understanding how Visualforce components behave when converted to PDF is essential to creating pages that render well.
The Visualforce PDF rendering service renders static HTML and basic CSS that is explicitly provided by the page. As a rule, dont use
components that:
Rely on JavaScript to perform an action
Depend on Salesforce style sheets
Use assets such as style sheets or graphics that arent available in the page itself or in a static resource
To check if your Visualforce page falls into one of these categories, right-click anywhere on the page and view the HTML source. If you
see a <script> tag that refers to JavaScript (.js) or a <link> tag that refers to a style sheet (.css), verify that the generated
PDF file displays as expected.

Components That Are Safe When Rendering as PDF


<apex:composition> (as long as the page contains PDF-safe components)
<apex:dataList>
<apex:define>
<apex:facet>
<apex:include> (as long as the page contains PDF-safe components)
<apex:insert>
<apex:image>
<apex:outputLabel>
<apex:outputLink>
<apex:outputPanel>
<apex:outputText>
<apex:page>
<apex:panelGrid>
<apex:panelGroup>
<apex:param>

71

Customizing the Appearance and Output of Visualforce Pages

Component Behavior When Rendered as PDF

<apex:repeat>
<apex:stylesheet> (as long as the URL isnt directly referencing Salesforce style sheets)
<apex:variable>

Components to Use with Caution When Rendering as PDF


<apex:attribute>
<apex:column>
<apex:component>
<apex:componentBody>
<apex:dataTable>

Components That Are Unsafe to Use When Rendering as PDF


<apex:actionFunction>
<apex:actionPoller>
<apex:actionRegion>
<apex:actionStatus>
<apex:actionSupport>
<apex:commandButton>
<apex:commandLink>
<apex:detail>
<apex:enhancedList>
<apex:flash>
<apex:form>
<apex:iframe>
<apex:includeScript>
<apex:inputCheckbox>
<apex:inputField>
<apex:inputFile>
<apex:inputHidden>
<apex:inputSecret>
<apex:inputText>
<apex:inputTextarea>
<apex:listViews>
<apex:message>
<apex:messages>
<apex:outputField>
<apex:pageBlock>
<apex:pageBlockButtons>
<apex:pageBlockSection>

72

Customizing the Appearance and Output of Visualforce Pages

Component Behavior When Rendered as PDF

<apex:pageBlockSectionItem>
<apex:pageBlockTable>
<apex:pageMessage>
<apex:pageMessages>
<apex:panelBar>
<apex:panelBarItem>
<apex:relatedList>
<apex:scontrol>
<apex:sectionHeader>
<apex:selectCheckboxes>
<apex:selectList>
<apex:selectOption>
<apex:selectOptions>
<apex:selectRadio>
<apex:tab>
<apex:tabPanel>
<apex:toolbar>
<apex:toolbarGroup>

73

CHAPTER 5

Standard Controllers

A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified in associated
Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that should be displayed in a
page, and can modify component behavior.
The [Link] platform provides a number of standard controllers that contain the same functionality and logic that are used for standard
Salesforce pages. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the
same behavior as clicking Save on a standard Account edit page.
A standard controller exists for every Salesforce object that can be queried using the [Link] API.
The following topics include additional information about using standard controllers:
Associating a Standard Controller with a Visualforce Page
Accessing Data with a Standard Controller
Using Standard Controller Actions
Validation Rules and Standard Controllers
Styling Pages that Use Standard Controllers
Checking for Object Accessibility
Custom Controllers and Controller Extensions

Associating a Standard Controller with a Visualforce Page


To associate a standard controller with a Visualforce page, use the standardController attribute on the <apex:page> tag
and assign it the name of any Salesforce object that can be queried using the [Link] API.
For example, to associate a page with the standard controller for a custom object named MyCustomObject, use the following markup:
<apex:page standardController="MyCustomObject__c">
</apex:page>

Note: When you use the standardController attribute on the <apex:page> tag, you cannot use the controller
attribute at the same time.

Accessing Data with a Standard Controller


Every standard controller includes a getter method that returns the record specified by the id query string parameter in the page URL.
This method allows the associated page markup to reference fields on the context record by using {!object} syntax, where object
is the lowercase name of the object associated with the controller. For example, a page that uses the Account standard controller can
use {![Link]} to return the value of the name field on the account that is currently in context.

74

Standard Controllers

Using Standard Controller Actions

Note: For the getter method to succeed, the record specified by the id query string parameter in the URL must be of the same
type as the standard controller. For example, a page that uses the Account standard controller can only return an account record.
If a contact record ID is specified by the id query string parameter, no data is returned by the {!account} expression.
As with queries in the [Link] API, you can use merge field syntax to retrieve data from related records:
You can traverse up to five levels of child-to-parent relationships. For example, if using the Contact standard controller, you can use
{![Link]} (a three-level child-to-parent relationship) to return the name of the owner
of the account record that is associated with the contact.
You can traverse one level of parent-to-child relationships. For example, if using the Account standard controller, you can use
{![Link]} to return an array of all contacts associated with the account that is currently in context.

Using Standard Controller Actions


Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of
the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following
tags:
<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as onclick, onmouseover, and so on) on another, named component, call
an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
The following table describes the action methods that are supported by all standard controllers. You can associate these actions with
any Visualforce component that includes an action attribute.
Action

Description

save

Inserts a new record or updates an existing record if it is currently in context. After this operation is
finished, the save action returns the user to the original page (if known), or navigates the user to
the detail page for the saved record.

quicksave

Inserts a new record or updates an existing record if it is currently in context. Unlike the save action,
this page does not redirect the user to another page.

edit

Navigates the user to the edit page for the record that is currently in context. After this operation is
finished, the edit action returns the user to the page where the user originally invoked the action.

delete

Deletes the record that is currently in content. After this operation is finished, the delete action
either refreshes the page or sends the user to tab for the associated object.

cancel

Aborts an edit operation. After this operation is finished, the cancel action returns the user to the
page where the user originally invoked the edit.

list

Returns a PageReference object of the standard list page, based on the most recently used list filter
for that object. For example, if the standard controller is contact, and the last filtered list that the
user viewed is New Last Week, the contacts created in the last week are displayed.

75

Standard Controllers

Validation Rules and Standard Controllers

For example, the following page allows you to update an account. When you click Save, the save action is triggered on the standard
controller, and the account is updated.
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="My Content" mode="edit">
<apex:pageBlockButtons>
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="My Content Section" columns="2">
<apex:inputField value="{![Link]}"/>
<apex:inputField value="{![Link]}"/>
<apex:inputField value="{![Link]}"/>
<apex:inputField value="{![Link]}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
[Link]

Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
Note: Command buttons and links that are associated with save, quicksave, edit, or delete actions in a standard
controller are only rendered if the user has the appropriate permissions. Likewise, if no particular record is associated with a page,
command buttons and links associated with the edit and delete actions are not rendered.

Validation Rules and Standard Controllers


If a user enters data on a Visualforce page that uses a standard controller, and that data causes a validation rule error, the error can be
displayed on the Visualforce page. If the validation rule error location is a field associated with an <apex:inputField> component,
the error displays there. If the validation rule error location is set to the top of the page, use the <apex:pageMessages> or
<apex:messages> component within the <apex:page> to display the error.

Styling Pages that Use Standard Controllers


Any page associated with a standard controller automatically inherits the style that is used for standard Salesforce pages associated with
the specified object. That is, the tab for the specified object appears selected, and the associated color of the tab is used to style all page
elements.
You can override the styling of a page that uses a standard controller with the tabStyle attribute on the <apex:page> tag. For
example, the following page uses the Account standard controller, but renders a page that highlights the Opportunities tab and uses
the Opportunity tab's yellow coloring:
<apex:page standardController="Account" tabStyle="Opportunity">
</apex:page>

76

Standard Controllers

Checking for Object Accessibility

To use the styling associated with MyCustomObject:


<apex:page standardController="Account" tabStyle="MyCustomObject__c">
</apex:page>

To use the styling associated with a custom Visualforce tab, set the attribute to the name (not label) of the tab followed by a
double-underscore and the word tab. For example, to use the styling of a Visualforce tab with the name Source and a label Sources, use:
<apex:page standardController="Account" tabStyle="Source__tab">
</apex:page>

Alternatively, you can override standard controller page styles with your own custom stylesheets and inline styles.
SEE ALSO:
Styling Visualforce Pages

Checking for Object Accessibility


If a user has insufficient privileges to view an object, any Visualforce page that uses a controller to render that object will be inaccessible.
To avoid this error, you should ensure that your Visualforce components will only render if a user has access to the object associated
with the controller.
You can check for the accessibility of an object like this:
{!$[Link]}

This expression returns a true or false value.


For example, to check if you have access to the standard Lead object, use the following code:
{!$[Link]}

For custom objects, the code is similar:


{!$ObjectType.MyCustomObject__c.accessible}

where MyCustomObject__c is the name of your custom object.


To ensure that a portion of your page will display only if a user has access to an object, use the render attribute on a component. For
example, to display a page block if a user has access to the Lead object, you would do the following:
<apex:page standardController="Lead">
<apex:pageBlock rendered="{!$[Link]}">
<p>This text will display if you can see the Lead object.</p>
</apex:pageBlock>
</apex:page>

It is good practice to provide an alternative message if a user cannot access an object. For example:
<apex:page standardController="Lead">
<apex:pageBlock rendered="{!$[Link]}">
<p>This text will display if you can see the Lead object.</p>
</apex:pageBlock>
<apex:pageBlock rendered="{! NOT($[Link]) }">
<p>Sorry, but you cannot see the data because you do not have access to the Lead
object.</p>

77

Standard Controllers

Checking for Object Accessibility

</apex:pageBlock>
</apex:page>

78

CHAPTER 6

Standard List Controllers

Standard list controllers allow you to create Visualforce pages that can display or act on a set of records. Examples of existing Salesforce
pages that work with a set of records include list pages, related lists, and mass action pages. Standard list controllers can be used with
the following objects:
Account
Asset
Campaign
Case
Contact
Contract
Idea
Lead
Opportunity
Order
Product2
Solution
User
Custom objects
The following topics include additional information about using standard list controllers:
Associating a Standard List Controller with a Visualforce Page
Accessing Data with List Controllers
Using Standard List Controller Actions
Using List Views with Standard List Controllers
Overriding Tabs Using a Standard List Controller
Adding Custom List Buttons using Standard List Controllers
SEE ALSO:
Building a Custom Controller

Associating a Standard List Controller with a Visualforce Page


Using a standard list controller is very similar to using a standard controller. First you set the standardController attribute on
the <apex:page> component, then you set the recordSetVar attribute on the same component.

79

Standard List Controllers

Accessing Data with List Controllers

For example, to associate a page with the standard list controller for accounts, use the following markup:
<apex:page standardController="Account" recordSetVar="accounts">

Note: When you use the standardController attribute on the <apex:page> tag, you cant use the controller
attribute at the same time.
The recordSetVar attribute not only indicates that the page uses a list controller, it sets the variable name of the record collection.
This variable can be used to access data in the record collection.

Accessing Data with List Controllers


Once you have associated a page with a list controller, you can refer to the set of records using expression language syntax. For example,
to create a simple table of accounts, create a page with the following markup:
<apex:page standardController="Account" recordSetVar="accounts" tabstyle="account"
sidebar="false">
<apex:pageBlock >
<apex:pageBlockTable value="{!accounts}" var="a">
<apex:column value="{![Link]}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

This results in a page that lists all the account names in your organization:

Note: This page does not specify a filter in the request, so the page is displayed with the last used filter. For information on using
filters with list controllers, see Using List Views with Standard List Controllers on page 82.
As with queries in the [Link] API, you can use expression language syntax to retrieve data from related records. As with standard
controllers, you can traverse up to five levels of child-to-parent relationships and one level of parent-to-child relationships.
When using a standard list controller, the returned records sort on the first column of data, as defined by the current view, even if that
column is not rendered. When using an extension or custom list controller, you can control the sort method.
Note: No more than 10,000 records can be returned by a standard list controller. Custom controllers can work with larger results
sets. See Working with Large Sets of Data on page 96.
SEE ALSO:
[Link] SOQL and SOSL Reference: Relationship Queries

80

Standard List Controllers

Using Standard List Controller Actions

Using Standard List Controller Actions


Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of
the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following
tags:
<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as onclick, onmouseover, and so on) on another, named component, call
an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
The following table describes the action methods that are supported by all standard list controllers. You can associate these actions with
any Visualforce component that includes an action attribute.
Action

Description

save

Inserts new records or updates existing records that have been changed. After this operation is
finished, the save action returns the user to the original page, if known, or the home page.

quicksave

Inserts new records or updates existing records that have been changed. Unlike the save action,
quicksave does not redirect the user to another page.

list

Returns a PageReference object of the standard list page, based on the most recently used list filter
for that object when the filterId is not specified by the user.

cancel

Aborts an edit operation. After this operation is finished, the cancel action returns the user to the
page where the user originally invoked the edit.

first

Displays the first page of records in the set.

last

Displays the last page of records in the set.

next

Displays the next page of records in the set.

previous

Displays the previous page of records in the set.

In the following example, the user specifies a filter for viewing account records. When the user clicks Go, the standard list page displays,
using the selected filter.
<apex:page standardController="Account" recordSetVar="accounts">
<apex:form>
<apex:selectList value="{!filterid}" size="1">
<apex:selectOptions value="{!listviewoptions}"/>
</apex:selectList>
<apex:commandButton value="Go" action="{!list}"/>
</apex:form>
</apex:page>

81

Standard List Controllers

Pagination with a List Controller

Pagination with a List Controller


You can add pagination to a page using a list controller by utilizing the next and previous actions. For example, if you create a
page with the following markup:
<apex:page standardController="Account" recordSetvar="accounts">
<apex:pageBlock title="Viewing Accounts">
<apex:form id="theForm">
<apex:pageBlockSection >
<apex:dataList var="a" value="{!accounts}" type="1">
{![Link]}
</apex:dataList>
</apex:pageBlockSection>
<apex:panelGrid columns="2">
<apex:commandLink action="{!previous}">Previous</apex:commandlink>
<apex:commandLink action="{!next}">Next</apex:commandlink>
</apex:panelGrid>
</apex:form>
</apex:pageBlock>
</apex:page>

By default, a list controller returns 20 records on the page. To control the number of records displayed on each page, use a controller
extension to set the pageSize. For information on controller extensions, see Building a Controller Extension on page 89.
Note: When you use pagination, an exception is thrown when there are modified rows in the collection. This includes any new
rows added to the collection through an extension action. The handling of error messages in this case follows the standard behavior
and can either be displayed upon the page. For example, you can use the <apex:pageMessages> or <apex:messages>
component to display an error message to the user.

Using List Views with Standard List Controllers


Many Salesforce pages include list views that allow you to filter the records displayed on the page. For example, on the opportunities
home page, you can choose to view a list of only the opportunities you own by selecting My Opportunities from the list view
drop-down. On a page that is associated with a list controller, you can also use list views.
For example, to create a simple list of accounts with a list view, create a page with the following markup:
<apex:page standardController="Account" recordSetvar="accounts">
<apex:pageBlock title="Viewing Accounts">
<apex:form id="theForm">
<apex:panelGrid columns="2">
<apex:outputLabel value="View:"/>
<apex:selectList value="{!filterId}" size="1">
<apex:actionSupport event="onchange" rerender="list"/>
<apex:selectOptions value="{!listviewoptions}"/>
</apex:selectList>
</apex:panelGrid>
<apex:pageBlockSection >
<apex:dataList var="a" value="{!accounts}" id="list">
{![Link]}
</apex:dataList>
</apex:pageBlockSection>
</apex:form>

82

Standard List Controllers

Using List Views with Standard List Controllers

</apex:pageBlock>
</apex:page>

When you open that page, you'll see something like the following:

This page is associated with the standard account controller and the <apex:selectlist> component is populated by
{!listviewoptions}, which evaluates to the list views the user can see. When the user chooses a value from the drop-down
list, it is bound to the filterId property for the controller. When the filterId is changed, the records available to the page
changes, so, when the <apex:datalist> is updated, that value is used to update the list of records available to the page.
You can also use a view list on an edit page, like the following:
<apex:page standardController="Opportunity" recordSetVar="opportunities"
tabStyle="Opportunity"
sidebar="false">
<apex:form>
<apex:pageBlock>
<apex:pageMessages/>
<apex:pageBlock>
<apex:panelGrid columns="2">
<apex:outputLabel value="View:"/>
<apex:selectList value="{!filterId}" size="1">
<apex:actionSupport event="onchange" rerender="opp_table"/>
<apex:selectOptions value="{!listviewoptions}"/>
</apex:selectList>
</apex:panelGrid>
</apex:pageBlock>
<apex:pageBlockButtons>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!opportunities}" var="opp" id="opp_table">
<apex:column value="{![Link]}"/>
<apex:column headerValue="Stage">
<apex:inputField value="{![Link]}"/>
</apex:column>
<apex:column headerValue="Close Date">
<apex:inputField value="{![Link]}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>

83

Standard List Controllers

Editing Records with List Controllers

</apex:form>
</apex:page>

Note: If the user changes the list view, an exception is thrown if there are modified rows in the collection. The handling of error
messages in this case follows the standard behavior and can either be displayed upon the page. For example, you can use the
<apex:pageMessages> or <apex:messages> component to display an error message to the user.

Editing Records with List Controllers


You can edit a set of records using list controllers, too. For example, if you create a page with the following markup:
<apex:page standardController="Opportunity" recordSetVar="opportunities"
tabStyle="Opportunity" sidebar="false">
<apex:form >
<apex:pageBlock >
<apex:pageMessages />
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!opportunities}" var="opp">
<apex:column value="{![Link]}"/>
<apex:column headerValue="Stage">
<apex:inputField value="{![Link]}"/>
</apex:column>
<apex:column headerValue="Close Date">
<apex:inputField value="{![Link]}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

you see a page that allows you to update and save the Stage and Close Date on your opportunities, like the following:

84

Standard List Controllers

Editing Records with List Controllers

For more information, see Mass-Updating Records with a Custom List Controller on page 136.
Note: Command buttons and links that are associated with save, quicksave, or edit actions in a list controller are not
rendered if the user does not have the appropriate permissions. Likewise if no particular record is associated with a page, command
buttons and links associated with the edit actions are not rendered.

85

CHAPTER 7

Custom Controllers and Controller Extensions

Standard controllers can provide all the functionality you need for a Visualforce page because they include the same logic that is used
for a standard page. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the
same behavior as clicking Save on a standard Account edit page.
However, if you want to override existing functionality, customize the navigation through an application, use callouts or Web services,
or if you need finer control for how information is accessed for your page, you can write a custom controller or a controller extension
using Apex:
What are Custom Controllers and Controller Extensions?
Building a Custom Controller
Building a Controller Extension
Controller Methods
Controller Class Security
Considerations for Creating Custom Controllers and Controller Extensions
Order of Execution in a Visualforce Page
Testing Custom Controllers and Controller Extensions
Validation Rules and Custom Controllers
Using the transient Keyword

What are Custom Controllers and Controller Extensions?


A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. Use custom
controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level
security of the current user.
A controller extension is an Apex class that extends the functionality of a standard or custom controller. Use controller extensions when:
You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view, save, or
delete.
You want to add new actions.
You want to build a Visualforce page that respects user permissions. Although a controller extension class executes in system mode,
if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode.
Instead, it executes in user mode, in which permissions, field-level security, and sharing rules of the current user apply.
Note: Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions
and field-level security, you can choose whether they respect a user's organization-wide defaults, role hierarchy, and sharing rules
by using the with sharing keywords in the class definition. For information, see Using the with sharing or without
sharing Keywords in the Apex Developer Guide.

86

Custom Controllers and Controller Extensions

Building a Custom Controller

Building a Custom Controller


A custom controller is an Apex class that uses the default, no-argument constructor for the outer, top-level class. You cannot create a
custom controller constructor that includes parameters.
To create a custom controller:
1. From Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
2. Click New.
3. Click Version Settings to specify the version of Apex and the API used with this class. If your organization has installed managed
packages from the AppExchange, you can also specify which version of each managed package to use with this class. Use the default
values for all versions. This associates the class with the most recent version of Apex and the API, as well as each managed package.
You can specify an older version of a managed package if you want to access components or functionality that differs from the most
recent package version. You can specify an older version of Apex and the API to maintain specific behavior.
4. In the class editor, enter the Apex code for the class. A single class can be up to 1 million characters in length, not including comments,
test methods, or classes defined using @isTest.
5. Click Save to save your changes and return to the class detail screen, or click Quick Save to save your changes and continue editing
your class. Your Apex class must compile correctly before you can save your class.
The following class is a simple example of a custom controller:
public class MyController {
private final Account account;
public MyController() {
account = [SELECT Id, Name, Site FROM Account
WHERE Id = :[Link]().getParameters().get('id')];
}
public Account getAccount() {
return account;
}
public PageReference save() {
update account;
return null;
}
}

The following Visualforce markup shows how the custom controller above can be used in a page:
<apex:page controller="myController" tabStyle="Account">
<apex:form>
<apex:pageBlock title="Congratulations {!$[Link]}">
You belong to Account Name: <apex:inputField value="{![Link]}"/>
<apex:commandButton action="{!save}" value="save"/>
</apex:pageBlock>
</apex:form>
</apex:page>

The custom controller is associated with the page because of the controller attribute of the <apex:page> component.

87

Custom Controllers and Controller Extensions

Building a Custom Controller

As with standard controllers and controller extensions, custom controller methods can be referenced with {! } notation in the
associated page markup. In the example above, the getAccount method is referenced by the <apex:inputField> tag's
value attribute, while the <apex:commandButton> tag references the save method with its action attribute.
Note: Like other Apex classes, all custom controllers run in system mode. Consequently, the current user's credentials are not
used to execute controller logic, and the user's permissions and field-level security do not apply.
You can choose whether a custom controller respects a user's organization-wide defaults, role hierarchy, and sharing rules by
using the with sharing keywords in the class definition. For information, see Using the with sharing or without
sharing Keywords in the Apex Developer Guide.
A custom controller can also be used to create new records. For example:
public class NewAndExistingController {
public Account account { get; private set; }
public NewAndExistingController() {
Id id = [Link]().getParameters().get('id');
account = (id == null) ? new Account() :
[SELECT Name, Phone, Industry FROM Account WHERE Id = :id];
}
public PageReference save() {
try {
upsert(account);
} catch([Link] e) {
[Link](e);
return null;
}
// After successful Save, navigate to the default view page
PageReference redirectSuccess = new [Link](Account).view();
return (redirectSuccess);
}
}

The following Visualforce markup shows how the custom controller above can be used in a page:
<apex:page controller="NewAndExistingController" tabstyle="Account">
<apex:form>
<apex:pageBlock mode="edit">
<apex:pageMessages/>
<apex:pageBlockSection>
<apex:inputField value="{![Link]}"/>
<apex:inputField value="{![Link]}"/>
<apex:inputField value="{![Link]}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

88

Custom Controllers and Controller Extensions

Building a Controller Extension

Building a Controller Extension


A controller extension is any Apex class containing a constructor that takes a single argument of type
[Link] or CustomControllerName, where CustomControllerName is the name of
a custom controller you want to extend.
The following class is a simple example of a controller extension:
public class myControllerExtension {
private final Account acct;
// The extension constructor initializes the private member
// variable acct by using the getRecord method from the standard
// controller.
public myControllerExtension([Link] stdController) {
[Link] = (Account)[Link]();
}
public String getGreeting() {
return 'Hello ' + [Link] + ' (' + [Link] + ')';
}
}

The following Visualforce markup shows how the controller extension from above can be used in a page:
<apex:page standardController="Account" extensions="myControllerExtension">
{!greeting} <p/>
<apex:form>
<apex:inputField value="{![Link]}"/> <p/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:form>
</apex:page>

The extension is associated with the page using the extensions attribute of the <apex:page> component.
As with all controller methods, controller extension methods can be referenced with {! } notation in page markup. In the example
above, the {!greeting} expression at the top of the page references the controller extension's getGreeting method.
Because this extension works in conjunction with the Account standard controller, the standard controller methods are also available.
For example, the value attribute in the <apex:inputField> tag retrieves the name of the account using standard controller
functionality. Likewise, the <apex:commandButton> tag references the standard account save method with its action
attribute.
Multiple controller extensions can be defined for a single page through a comma-separated list. This allows for overrides of methods
with the same name. For example, if the following page exists:
<apex:page standardController="Account"
extensions="ExtOne,ExtTwo" showHeader="false">
<apex:outputText value="{!foo}" />
</apex:page>

with the following extensions:


public class ExtOne {
public ExtOne([Link] acon) { }

89

Custom Controllers and Controller Extensions

Building a Custom List Controller

public String getFoo() {


return 'foo-One';
}
}
public class ExtTwo {
public ExtTwo([Link] acon) { }
public String getFoo() {
return 'foo-Two';
}
}

The value of the <apex:outputText> component renders as foo-One. Overrides are defined by whichever methods are defined
in the leftmost extension, or, the extension that is first in the comma-separated list. Thus, the getFoo method of ExtOne is
overriding the method of ExtTwo.
Note: Like other Apex classes, controller extensions run in system mode. Consequently, the current user's credentials are not
used to execute controller logic, and the user's permissions and field-level security do not apply. However, if a controller extension
extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user
mode, in which the permissions, field-level security, and sharing rules of the current user apply.
You can choose whether a controller extension respects a user's organization-wide defaults, role hierarchy, and sharing rules by
using the with sharing keywords in the class definition. For information, see Using the with sharing or without
sharing Keywords in the Apex Developer Guide.

Building a Custom List Controller


A custom list controller is similar to a standard list controller. Custom list controllers can implement Apex logic that you define to show
or act on a set of records.
For example you can create the following custom list controller based on a SOQL query:
public class opportunityList2Con {
// [Link] must be instantiated
// for standard list controllers
public [Link] setCon {
get {
if(setCon == null) {
setCon = new [Link]([Link](
[SELECT Name, CloseDate FROM Opportunity]));
}
return setCon;
}
set;
}
// Initialize setCon and return a list of records
public List<Opportunity> getOpportunities() {
return (List<Opportunity>) [Link]();
}
}

90

Custom Controllers and Controller Extensions

Building a Custom List Controller

Note: The list of sObjects returned by getRecords() is immutable. For example, you cant call clear() on it. You can
make changes to the sObjects contained in the list, but you cant add items to or remove items from the list itself.
The following Visualforce markup shows how the custom controller above can be used in a page:
<apex:page controller="opportunityList2Con">
<apex:pageBlock>
<apex:pageBlockTable value="{!opportunities}" var="o">
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

You can also create a custom list controller that uses anti- and semi-joins as part of the SOQL query. The following code is implemented
as an extension to the account standard controller:
public with sharing class AccountPagination {
private final Account acct;
// The constructor passes in the standard controller defined
// in the markup below
public AccountPagination([Link] controller) {
[Link] = (Account)[Link]();
}
public [Link] accountRecords {
get {
if(accountRecords == null) {
accountRecords = new [Link](
[Link]([SELECT Name FROM Account WHERE Id NOT IN
(SELECT AccountId FROM Opportunity WHERE IsClosed = true)]));
}
return accountRecords;
}
private set;
}
public List<Account> getAccountPagination() {
return (List<Account>) [Link]();
}
}

The page that displays these records uses a mix of standard list controller actions, but depends on iterating over the records returned
from the custom list controller:
<apex:page standardController="Account" recordSetVar="accounts"
extensions="AccountPagination">
<apex:pageBlock title="Viewing Accounts">
<apex:form id="theForm">
<apex:pageBlockSection >
<apex:dataList value="{!accountPagination}" var="acct" type="1">
{![Link]}
</apex:dataList>
</apex:pageBlockSection>
<apex:panelGrid columns="2">
<apex:commandLink action="{!previous}">Previous</apex:commandlink>

91

Custom Controllers and Controller Extensions

Controller Methods

<apex:commandLink action="{!next}">Next</apex:commandlink>
</apex:panelGrid>
</apex:form>
</apex:pageBlock>
</apex:page>

Controller Methods
Visualforce markup can use the following types of controller extension and custom controller methods:
Action
Getter
Setter

Action Methods
Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of
the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following
tags:
<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as onclick, onmouseover, and so on) on another, named component, call
an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
For example, in the sample page in Building a Custom Controller on page 87, the controller's save method is called by the action
parameter of the <apex:commandButton> tag. Other examples of action methods are discussed in Defining Action Methods on
page 119.

Getter Methods
Getter methods return values from a controller. Every value that is calculated by a controller and displayed in a page must have a
corresponding getter method, including any Boolean variables. For example, in the sample page in Building a Custom Controller on
page 87, the controller includes a getAccount method. This method allows the page markup to reference the account member
variable in the controller class with {! } notation. The value parameter of the <apex:inputField> tag uses this notation
to access the account, and dot notation to display the account's name. Getter methods must always be named getVariable.
Important: Its a best practice for getter methods to be idempotent, that is, to not have side effects. For example, dont increment
a variable, write a log message, or add a new record to the database. Visualforce doesnt define the order in which getter methods
are called, or how many times they might be called in the course of processing a request. Design your getter methods to produce
the same outcome, whether they are called once or multiple times for a single page request.

92

Custom Controllers and Controller Extensions

Controller Methods

Setter Methods
Setter methods pass user-specified values from page markup to a controller. Any setter methods in a controller are automatically executed
before any action methods.
For example, the following markup displays a page that implements basic search functionality for Leads. The associated controller
includes getter and setter methods for the search box input, and then uses the search text to issue a SOSL query when the user clicks
Go!. Although the markup doesnt explicitly call the search text setter method, it executes before the doSearch action method when
a user clicks the command button:
<apex:page controller="theController">
<apex:form>
<apex:pageBlock mode="edit" id="block">
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:outputLabel for="searchText">Search Text</apex:outputLabel>
<apex:panelGroup>
<apex:inputText id="searchText" value="{!searchText}"/>
<apex:commandButton value="Go!" action="{!doSearch}"
rerender="block" status="status"/>
</apex:panelGroup>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:actionStatus id="status" startText="requesting..."/>
<apex:pageBlockSection title="Results" id="results" columns="1">
<apex:pageBlockTable value="{!results}" var="l"
rendered="{!NOT(ISNULL(results))}">
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

The following class is the controller for the page markup above:
public class theController {
String searchText;
List<Lead> results;
public String getSearchText() {
return searchText;
}
public void setSearchText(String s) {
searchText = s;
}
public List<Lead> getResults() {
return results;
}

93

Custom Controllers and Controller Extensions

Controller Methods

public PageReference doSearch() {


results = (List<Lead>)[FIND :searchText RETURNING Lead(Name, Email, Phone)][0];
return null;
}
}

While a getter method is always required to access values from a controller, its not always necessary to include a setter method to pass
values into a controller. If a Visualforce component is bound to an sObject that is stored in a controller, the sObject's fields are automatically
set if changed by the user, as long as the sObject is saved or updated by a corresponding action method. An example of this behavior
is shown in the sample page in Building a Custom Controller on page 87.
Setter methods must always be named setVariable.
Important: Its a best practice for setter methods to be idempotent, that is, to not have side effects. For example, dont increment
a variable, write a log message, or add a new record to the database. Visualforce doesnt define the order in which setter methods
are called, or how many times they might be called in the course of processing a request. Design your setter methods to produce
the same outcome, whether they are called once or multiple times for a single page request.

Getting and Setting Data with a Custom Extension or Controller


There is no guaranteed order in which Apex methods and variables are processed by a controller extension or custom controller. Therefore,
do not allow controller and extension classes to rely on another method being run, call that method directly. This applies specifically to
setting variables and accessing data from the database.
For example, in the following custom controller, the first method, getContactMethod1, always returns the correct value because
it doesnt assume that the contact variable c already exists. The second method, getContactMethod2, however, sometimes
returns the correct value, but not every time if c hasnt yet been set.
public class conVsBad {
Contact c;
public Contact getContactMethod1() {
if (c == null) c = [SELECT Id, Name FROM Contact LIMIT 1];
return c;
}
public Contact getContactMethod2() {
return c;
}
}

The following custom controller has the exact same methods. However, getContactMethod2 calls contactMethod1, so the
variable c is always set, and always contains the correct value when returned.
public class conVsGood {
Contact c;
public Contact getContactMethod1() {
if(c == null) c = [SELECT Id, Name FROM Contact LIMIT 1];
return c;
}
public Contact getContactMethod2() {
return getContactMethod1();

94

Custom Controllers and Controller Extensions

Controller Class Security

}
}

The following markup shows two pages that call these controllers. The Visualforce markup is identical, only the controller name is
changed:
<apex:page controller="conVsGood">
getContactMethod2(): {![Link]}<br/>
getContactMethod1(): {![Link]}
</apex:page>
<apex:page controller="conVsBad">
getContactMethod2(): {![Link]}<br/>
getContactMethod1(): {![Link]}
</apex:page>

Controller Class Security


Like other Apex classes, you can specify whether a user can execute methods in a custom controller or controller extension class based
on the user's profile.
Note: If youve installed a managed package in your org, you can set security only for the Apex classes in the package that are
declared as global or for classes that contain methods declared as webService.
If users have the Author Apex permission, they can access all Apex classes in the associated organization, regardless of the security
settings for individual classes.
Permission for an Apex class is checked only at the top level. For example, if class A calls class B, and a user profile has access only to
class A but not class B, the user can still execute the code in class A. Likewise, if a Visualforce page uses a custom component with an
associated controller, security is only checked for the controller associated with the page. The controller associated with the custom
component executes regardless of permissions.
To set Apex class security from the class list page:
1. From Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
2. Next to the name of the class that you want to restrict, click Security.
3. Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable
from the Enabled Profiles list and click Remove.
4. Click Save.
To set Apex class security from the class detail page:
1. From Setup, enter Apex Classes in the Quick Find box, then select Apex Classes.
2. Click the name of the class that you want to restrict.
3. Click Security.
4. Select the profiles that you want to enable from the Available Profiles list and click Add, or select the profiles that you want to disable
from the Enabled Profiles list and click Remove.
5. Click Save.
SEE ALSO:
Security Tips for Apex and Visualforce Development

95

Custom Controllers and Controller Extensions

Working with Large Sets of Data

Working with Large Sets of Data


Visualforce custom controllers and controller extensions are subject to Apex governor limits. For more information about governor limits,
see Execution Governors and Limits on page 709. Additionally, Visualforce iteration components, such as <apex:pageBlockTable>
and <apex:repeat>, are limited to a maximum of 1,000 items in the collection they iterate over.
Sometimes your Visualforce pages may need to work with or display larger sets of data, but not need to make modifications to that data;
for example, if you are providing custom reporting and analytics. Visualforce offers developers a read-only mode, which relaxes the
limit on the number of rows which can be queried in one request, and increases the limit on the number of collection items which can
be iterated over within the page.
You can specify read-only mode either for an entire page or, with certain limitations, on individual components or methods.
Note: You can only iterate over large sets of data if you specify read-only mode for the entire page.

SEE ALSO:
Setting Read-Only Mode for an Entire Page
Setting Read-Only Mode for Controller Methods

Setting Read-Only Mode for an Entire Page


To enable read-only mode for an entire page, set the readOnly attribute on the <apex:page> component to true.
For example, here is a simple page that will be processed in read-only mode:
<apex:page controller="SummaryStatsController" readOnly="true">
<p>Here is a statistic: {!veryLargeSummaryStat}</p>
</apex:page>

The controller for this page is also simple, but illustrates how you can calculate summary statistics for display on a page:
public class SummaryStatsController {
public Integer getVeryLargeSummaryStat() {
Integer closedOpportunityStats =
[SELECT COUNT() FROM Opportunity WHERE [Link] = true];
return closedOpportunityStats;
}
}

Normally, queries for a single Visualforce page request may not retrieve more than 50,000 rows. In read-only mode, this limit is relaxed
to allow querying up to 1,000,000 rows.
In addition to querying many more rows, the readOnly attribute also increases the maximum number of items in a collection that
can be iterated over using components such as <apex:dataTable>, <apex:dataList>, and <apex:repeat>. This limit
increased from 1,000 items to 10,000. Here is a simple controller and page demonstrating this:
public class MerchandiseController {
public List<Merchandise__c> getAllMerchandise() {
List<Merchandise__c> theMerchandise =
[SELECT Name, Price__c FROM Merchandise__c LIMIT 10000];
return(theMerchandise);

96

Custom Controllers and Controller Extensions

Setting Read-Only Mode for Controller Methods

}
}
<apex:page controller="MerchandiseController" readOnly="true">
<p>Here is all the merchandise we have:</p>
<apex:dataTable value="{!AllMerchandise}" var="product">
<apex:column>
<apex:facet name="header">Product</apex:facet>
<apex:outputText value="{![Link]}" />
</apex:column>
<apex:column>
<apex:facet name="header">Price</apex:facet>
<apex:outputText value="{!product.Price__c}" />
</apex:column>
</apex:dataTable>
</apex:page>

While Visualforce pages that use read-only mode for the entire page cant use data manipulation language (DML) operations, they can
call getter, setter, and action methods which affect form and other user interface elements on the page, make additional read-only
queries, and so on.

Setting Read-Only Mode for Controller Methods


Visualforce controller methods can, with some important limitations, use the Apex ReadOnly annotation, even if the page itself isnt
in read-only mode.
Visualforce controller methods with the @ReadOnly annotation automatically take advantage of read-only mode. However, restrictions
on the @ReadOnly annotation means that, for Visualforce controller methods, a read-only method must also have the
@RemoteAction annotation. The @RemoteAction annotation requires that the method be:
Either global or public
static
Enabling read-only mode by using the @ReadOnly annotation must be done on the top level method call. If the top level method
call doesnt have the@ReadOnly annotation, the normal restrictions on maximum queried rows are enforced for the entire request,
even if secondary methods are annotated with @ReadOnly.
Using the @ReadOnly annotation on a controller method allows you to retrieve a larger collection of records as the result of a Visualforce
expression. However, it doesnt increase the maximum number of items in a collection for iteration components. If you want to iterate
over larger collections of results, you need to enable read-only mode for the entire page.
SEE ALSO:
Setting Read-Only Mode for an Entire Page
"ReadOnly Annotation" in the [Link] Apex Code Developer's Guide

Considerations for Creating Custom Controllers and Controller


Extensions
Note the following considerations when creating controller extensions and custom controllers:

97

Custom Controllers and Controller Extensions

Order of Execution in a Visualforce Page

Unless a class has a method defined as webService, custom extension and controller classes and methods are generally defined
as public. If a class includes a web service method, it must be defined as global.
Use sets, maps, or lists when returning data from the database. This makes your code more efficient because the code makes fewer
trips to the database.
The Apex governor limits for Visualforce controller extensions and custom controllers are the same as the limits for anonymous block
or WSDL methods. For more information about governor limits, see Execution Governors and Limits in the Appendix.
If you are building a custom controller or controller extension, be careful that you do not inadvertently expose sensitive data that
would normally be hidden from users. Consider using the with sharing keywords on class definitions to enforce permissions.
Also be careful using Web services, which are secured as top-level entry points by the profile, but execute in the system context
once they are initiated.
Apex methods and variables are not instantiated in a guaranteed order. For more information, see Getting and Setting Data with a
Custom Extension or Controller on page 94.
You can't use data manipulation language (DML) operations in a getxxx method in a controller. For example, if your controller had
a getName method, you could not use insert or update in the method to create an object.
You can't use data manipulation language (DML) operations in a constructor method in a controller.
You can't use the @future annotation in a getxxx or setxxx method in a controller, or in the constructor for a controller.
Primitive Apex data types such as String or Integer are passed by value to the component's controller.
Non-primitive Apex data types such as lists and sObjects are passed by reference to component's controller. This means that if
component's controller changes the name of an account, the changes are available in page's controller.
If your org uses person accounts
When referencing an account record's name field with a custom controller using the <apex:inputField> component
you must specify isPersonAccount in your query.
If you create a new account and set name, the record will be a business account. If you create a new account and set lastname,
it will be a person account.
As a best practice, create a custom name formula field that will render properly for both person accounts and business accounts,
then use that field instead of the standard field in your Visualforce pages.
If you plan on including your Visualforce page in a [Link] AppExchange package, in your controller or controller extension,
you cannot explicitly reference fields that exist only in a person account.

Order of Execution in a Visualforce Page


When a user views a Visualforce page, instances of the controller, extensions, and components associated with the page are created by
the server. The order in which these elements are executed can affect how the page is displayed to the user.
To fully understand the order of execution of elements on a Visualforce page, you must first understand the page's lifecyclethat is, how
the page is created and destroyed during the course of a user session. The lifecycle of a page is determined not just by the content of
the page, but also by how the page was requested. There are two types of Visualforce page requests:
A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the
user to a new page.
A postback request is made when user interaction requires a page update, such as when a user clicks on a Save button and triggers
a save action.
For specific details of the two types of requests, examples illustrating the lifecycle of a page, and tips on how to handle execution order
when writing your own custom controllers and controller extensions, see:
Order of Execution for Visualforce Page Get Requests

98

Custom Controllers and Controller Extensions

Order of Execution for Visualforce Page Get Requests

Order of Execution for Visualforce Page Postback Requests


Examples of Visualforce Page Execution Order
Note: The maximum response size from a Visualforce page request must be below 15 MB.

Order of Execution for Visualforce Page Get Requests


A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user
to a new page. The following diagram shows how a Visualforce page interacts with a controller extension or a custom controller class
during a get request:

99

Custom Controllers and Controller Extensions

Order of Execution for Visualforce Page Get Requests

In the diagram above the user initially requests a page, either by entering a URL or clicking a link or button. This initial page request is
called the get request.
1. The constructor methods on the associated custom controller or controller extension classes are called, instantiating the controller
objects.
2. If the page contains any custom components, they are created and the constructor methods on any associated custom controllers
or controller extensions are executed. If attributes are set on the custom component using expressions, the expressions are evaluated
after the constructors are evaluated.

100

Custom Controllers and Controller Extensions

Order of Execution for Visualforce Page Postback Requests

3. The page then executes any assignTo attributes on any custom components on the page. After the assignTo methods are
executed, expressions are evaluated, the action attribute on the <apex:page> component is evaluated, and all other method
calls, such as getting or setting a property value, are made.
4. If the page contains an <apex:form> component, all of the information necessary to maintain the state of the database between
page requests is saved as an encrypted view state. The view state is updated whenever the page is updated.
5. The resulting HTML is sent to the browser. If there are any client-side technologies on the page, such as JavaScript, the browser
executes them.
As the user interacts with the page, the page contacts the controller objects as required to execute action, getter, and setter methods.
Once a new get request is made by the user, the view state and controller objects are deleted.
Note: If the user is redirected to a page that uses the same controller and the same or a proper subset of controller extensions,
a postback request is made. When a postback request is made, the view state is maintained.
If the user interaction requires a page update, such as when the user clicks a Save button that triggers a save action, a postback request
is made. For more information on postback requests, see Order of Execution for Visualforce Page Postback Requests on page 101.
For a specific example of a get request, see Examples of Visualforce Page Execution Order on page 103.

Order of Execution for Visualforce Page Postback Requests


A postback request is made when user interaction requires a page update, such as when a user clicks on a Save button and triggers a
save action. The following diagram shows how a Visualforce page interacts with a controller extension or a custom controller class during
a postback request:

101

Custom Controllers and Controller Extensions

Order of Execution for Visualforce Page Postback Requests

1. During a postback request, the view state is decoded and used as the basis for updating the values on the page.
Note: A component with the immediate attribute set to true bypasses this phase of the request. In other words, the
action executes, but no validation is performed on the inputs and no data changes on the page.
2. After the view state is decoded, expressions are evaluated and set methods on the controller and any controller extensions, including
set methods in controllers defined for custom components, are executed.
These method calls do not update the data unless all methods are executed successfully. For example, if one of the methods updates
a property and the update is not valid due to validation rules or an incorrect data type, the data is not updated and the page redisplays
with the appropriate error messages.

102

Custom Controllers and Controller Extensions

Examples of Visualforce Page Execution Order

3. The action that triggered the postback request is executed. If that action completes successfully, the data is updated. If the postback
request returns the user to the same page, the view state is updated.
Note: The action attribute on the <apex:page> component is not evaluated during a postback request. It is only
evaluated during a get request.
4. The resulting HTML is sent to the browser.
If the postback request indicates a page redirect and the redirect is to a page that uses the same controller and a proper subset of
controller extensions of the originating page, a postback request is executed for that page. Otherwise, a get request is executed for the
page. If the postback request contains an <apex:form> component, only the ID query parameter on a postback request is returned.
Tip: You can use the setRedirect attribute on a pageReference to control whether a postback or get request is
executed. If setRedirect is set to true, a get request is executed. Setting it to false does not ignore the restriction that a
postback request will be executed if and only if the target uses the same controller and a proper subset of extensions. If
setRedirect is set to false, and the target does not meet those requirements, a get request will be made.
Once the user is redirected to another page, the view state and controller objects are deleted.
For a specific example of a postback request, see Examples of Visualforce Page Execution Order on page 103.

Examples of Visualforce Page Execution Order


The following examples illustrate the lifecycle of a Visualforce page as a user interacts with it. The page used in the examples is designed
to show information about an account, the value of the variables on the page, and allows the user to edit details of the account if the
key value is set to anything except false.
To set up the Visualforce page for the examples:
1. Create a controller for a custom component called componentController:
public class componentController {
public String selectedValue {
get;
set {
editMode = (value != null);
// Side effect here - don't do this!
selectedValue = value;
}
}
public Boolean editMode {get; private set;}
}

2. Create a custom component called editMode:


<apex:component controller="componentController">
<apex:attribute name="value" type="String" description="Sample component."
assignTo="{!selectedValue}"/>
<p>
Value = {!value}<br/>
selectedValue = {!selectedValue}<br/>
EditMode = {!EditMode}
</p>
</apex:component>

103

Custom Controllers and Controller Extensions

Examples of Visualforce Page Execution Order

3. Create a custom controller called myController:


public with sharing class myController {
private final Account account;
public myController() {
account = [select id, name, site, NumberOfEmployees, Industry from Account
where id = :[Link]().getParameters().get('id')];
}
public Account getAccount() {
return account;
}
public PageReference save() {
update account;
return null;
}
public PageReference cancel() {
return null;
}
}

4. Create a controller extension called lifecycle:


public with sharing class lifecycle {
private final Account acct;
Integer EmpAdd;
public lifecycle(myController controller) {
[Link] = (Account)[Link]();
}
public String getGreeting() {
return [Link] + ' Current Information';
}
public void resetEmp() {
[Link] = 10;
update acct;
}
}

5. Create a page called setEmps:


<apex:page controller="myController" tabStyle="Account" extensions="lifecycle"
action="{!resetEmp}">
<apex:messages />
<apex:pageBlock title="{!greeting}">
<apex:outputLabel value="{!$[Link]}: "
for="acctName"/>

104

Custom Controllers and Controller Extensions

Examples of Visualforce Page Execution Order

<apex:outputField value="{![Link]}" id="acctName"/>


<br/>
<apex:outputLabel
value="{!$[Link]}: "
for="emps"/>
<apex:outputField value="{![Link]}" id="emps"/>
<br/>
</apex:pageBlock>
<apex:pageBlock title="Variable values">
<c:editMode value="{!$[Link]}"/>
</apex:pageBlock>
<apex:form rendered="{!$[Link] = 'true'}">
<apex:pageBlock title="Update the Account" id="thePageBlock">
<apex:pageBlockSection columns="1">
<apex:inputField id="aName" value="{![Link]}"/>
<apex:inputField value="{![Link]}"/>
<apex:pageBlockSectionItem>
<apex:outputLabel value="{!$[Link]}"
for="acctIndustry"/>
<apex:actionRegion>
<apex:inputField value="{![Link]}" id="acctIndustry">
<apex:actionSupport event="onchange" rerender="thePageBlock"
status="status"/>
</apex:inputField>
</apex:actionRegion>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton action="{!save}" value="Save"/>
<apex:commandButton action="{!cancel}" value="Cancel" immediate="true"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

Get Request Example One


For the first example, visit the setEmps page using a URL of the form
[Link] where Salesforce_instance is the name
of your instance (for example, na1) and recordID is the ID of an account record in your organization (for example,
001D000000IRt53). You'll see a page with content similar to the following:

105

Custom Controllers and Controller Extensions

Examples of Visualforce Page Execution Order

Let's trace the lifecycle to see why the page displays what it does. Since you've requested the page directly by entering a URL, this page
is the result of a get request, not a postback request.
1. The first thing that happens in a get request is that constructor methods on the custom controller and controller extension are called.
The myController method is the constructor on the controller and the lifecycle method is the constructor on the
extension. Those are executed and the two objects now exist. The controller now has a variable, called account, that is the result
of a query that uses the id parameter from the URL, to identify which account object to query. The extension now has a variable,
called acct, that is created by calling the getAccount method on the controller. The getAccount method has no side-effects.
2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or
controller extensions. The page includes one custom component:
<c:editMode value="{!$[Link]}"/>

This custom component has an associated controller, but the controller has no explicit constructor. As with all Apex objects without
explicit constructors, the object is created using an implicit, no-argument, public constructor. As part of creating the custom
component, the value attribute on the custom component is set. In this case, it is equal to the result of the expression
{!$[Link]}. Since we did not specify the key attribute in the URL, value is set to null.
3. After custom components are created, all assignTo attributes on those custom components are executed. An assignTo
attribute is a setter method that assigns the value of this attribute to a class variable in the associated custom component controller.
The editMode custom component does have an assignTo method, so it is executed. The assignTo method sets
selectedValue on the attribute to the value attribute. The value attribute is set to null, so selectedValue is set to
null.
4. The next step in a get request is evaluation of the action attribute on the <apex:page> component , expressions, and the
required getter and setter methods. Although we'll step through these below, remember that the order of these evaluations is
indeterminate and may be different than the following:
The <apex:page> component has an action attribute which calls the resetEmp method on the extension. That
method sets the numberofemployees field on the acct object to 10.
There are several expressions that evaluate on the page. Let's focus on three:
<apex:pageBlock title="{!greeting}">
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting.
This is rendered on the page as Global Media Current Information.
<apex:form rendered="{!$[Link] = 'true'}">
The rendered attribute on <apex:form> is set based on the value of the key parameter. We did not set key when
calling the page, so the form is not rendered.
Value = {!value}<br/> selectedValue = {!selectedValue}<br/> EditMode =
{!EditMode}

This expression occurs in the custom component. We've already discussed that value and selectedValue are set
to null, however, the value of EditMode is not yet known. EditMode is a boolean variable on the
componentController. It is set based on the whether value is equal to null:
set {
selectedValue = value;
// Side effect here - don't do this!
editMode = (value != null);
}

106

Custom Controllers and Controller Extensions

Examples of Visualforce Page Execution Order

Since value is null, EditMode is set to false. Note, however, that there is a side-effect in the setter method for
EditMode. As part of setting editMode, we also setselectedValue to value. Since value is null, this doesn't
change anything, but this behavior has an impact in a later example.
The other expressions and methods are evaluated in a similar manner.
5. Since the <apex:form> component isn't rendered, the view state isn't created.
6. The last step in the get request is to send the HTML to the browser, which renders the HTML.

Get Request Example Two


For the second example, visit the setEmps page using a URL of the form
[Link] where Salesforce_instance
is the name of your instance (for example, na1) and recordID is the ID of an account record in your organization (for example,
001D000000IRt53). Unlike the first example, this example includes a second parameter, key=false. You'll see a page with

content similar to the following:

Let's trace the lifecycle again. This page is also the result of a get request:
1. The first thing that happens in a get request is that constructor methods on the custom controller and controller extension are called.
The myController method is the constructor on the controller and the lifecycle method is the constructor on the
extension. These are executed and the two objects now exist. The controller now has a variable, called account, that is the result
of a query that uses the id parameter from the URL to identify which account record to query. The extension now has a variable,
called acct, that is created by calling the getAccount method on the controller.
2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or
controller extensions. The page includes one custom component:
<c:editMode value="{!$[Link]}"/>

This custom component has an associated controller without a constructor, so the controller object is created using an implicit,
no-argument, public constructor. As part of creating the custom component, the value attribute on the custom component is
set. In this case, it is equal to the result of the expression {!$[Link]}. We specified the key
attribute as false, so value is set to false.
3. After custom components are created, all assignTo attributes on those custom components are executed. The assignTo
method sets selectedValue on the attribute to the value attribute. The value attribute is set to false, so selectedValue
is set to false.
4. The next step in a get request is evaluation of the action attribute on the <apex:page> component , expressions, and the
required getter and setter methods. Although we'll step through these below, remember that the order of these evaluations is
indeterminate and may be different than the following:
The <apex:page> component has an action attribute which calls the resetEmp method on the extension. That
method sets the numberofemployees field on the acct object to 10.

107

Custom Controllers and Controller Extensions

Examples of Visualforce Page Execution Order

Of the expressions on the page, let's see how our chosen three are evaluated:
<apex:pageBlock title="{!greeting}">
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting. It

is rendered on the page as Global Media Current Information.


<apex:form rendered="{!$[Link] = 'true'}">
The rendered attribute on <apex:form> is set based on the value of the key parameter. We set key to false when

calling the page, so the form is not rendered.


Value = {!value}<br/> selectedValue = {!selectedValue}<br/> EditMode = {!EditMode}
This expression occurs in the custom component. Since value is not null, EditMode is set to true. At this point,
selectedValue is set to null. Remember, however, that the setter method for EditMode has a side-effect. In this
case, the side-effect sets selectedValue to the value attribute on the custom component. Since value is set to
false, selectedValue is set to false. This illustrates why you should not use side-effects in your methods. If the
evaluation order were different, and the value for selectedValue were determined before the setter for EditMode
was evaluated, selectedValue would still be null. Execution order is not guaranteed, and the result for
selectedValue could change the next time this page is visited.

Warning: Do not use side-effects in your getters or setters!


5. Since the <apex:form> component isn't rendered, the view state isn't created
6. The last step in the get request is to send the HTML to the browser, which renders the HTML.

Get Request Example Three


For the third example, visit the setEmps page using a URL of the form
[Link] where Salesforce_instance
is the name of your instance (for example, na1) and recordID is the ID of an account record in your organization (for example,
001D000000IRt53). Unlike the second example, this example sets key=true. You'll see a page with content similar to the
following:

Let's trace the get request lifecycle one more time:


1. The first thing that happens in a get request is that constructor methods on the custom controller and controller extension are called.
The myController method is the constructor on the controller and the lifecycle method is the constructor on the
extension. These are executed and the two objects now exist. The controller now has a variable, called account, that is the result
of a query that uses the id parameter from the URL to identify which account record to query. The extension now has a variable,
called acct, that is created by calling the getAccount method on the controller.

108

Custom Controllers and Controller Extensions

Examples of Visualforce Page Execution Order

2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or
controller extensions. The page includes one custom component:
<c:editMode value="{!$[Link]}"/>

This custom component has an associated controller without a constructor, so the controller object is created using an implicit,
no-argument, public constructor. As part of creating the custom component, the value attribute on the custom component is
set. In this case, it is equal to the result of the expression {!$[Link]}. We specified the key
attribute as true, so value is set to true.
3. After custom components are created, all assignTo attributes on those custom components are executed. The assignTo
method sets selectedValue on the attribute to the value attribute. The value attribute is set to true, so selectedValue
is set to true.
4. The next step in a get request is evaluation of the action attribute on the <apex:page> component, expressions, and the
required getter and setter methods. Although we'll step through these below, remember that the order of these evaluations is
indeterminate and may be different than the following:
The <apex:page> component has an action attribute which calls the resetEmp method on the extension. That
method sets the numberofemployees field on the acct object to 10.
Of the expressions on the page, let's see how our chosen three are evaluated:
<apex:pageBlock title="{!greeting}">
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting. It

is rendered on the page as Global Media Current Information.


<apex:form rendered="{!$[Link] = 'true'}">
The rendered attribute on <apex:form> is set based on the value of the key parameter. We set key to true

when calling the page, so the form is rendered.


Value = {!value}<br/> selectedValue = {!selectedValue}<br/> EditMode = {!EditMode}
This expression occurs in the custom component. Since value is not null, EditMode is set to true. As in the previous
example, selectedValue is set to null. The side-effect in the setter method for EditMode sets selectedValue
to true.

5. Since the <apex:form> component is rendered, the view state is created.


6. The last step in the get request is to send the HTML to the browser, which renders the HTML.

Postback Request Example


Unlike the first two examples, the third example rendered a final page with editable fields clickable buttons. To understand how a
postback request works, use the final page in Example 3 to change the account name to Pan Galactic Media, the employee count to
42, and the industry to Other. Then click Save. This initiates a postback request:
1. The first thing that happens in a postback request is that the view state is decoded. The view state contains all the information
required to render the page. If, during the postback request, an operation fails, the view state is used to display the page to the user.
2. Next, all expressions are evaluated and methods on controllers and controller extensions are executed.
Of the expressions on the page, let's see how our chosen three are evaluated:
<apex:pageBlock title="{!greeting}">
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting. In our
edit, we changed the value of the Account name. Thus, the value of greeting changes to Pan Galactic Media Current

Information.

109

Custom Controllers and Controller Extensions

Testing Custom Controllers and Controller Extensions

<apex:form rendered="{!$[Link] = 'true'}">


The rendered attribute on <apex:form> is set based on the value of the key parameter. We have not changed the
key parameter, so the value in the view state is used. Since the value was true when the view state was created, it is still true

and the form is rendered.


Value = {!value}<br/> selectedValue = {!selectedValue}<br/> EditMode = {!EditMode}

We have not changed any of these values, so, for each expression, the value in the view state is used.
3. Lastly, the save action, the action that triggered the postback request, is evaluated. The save action is the following method on the
controller:
public PageReference save() {
update account;
return null;
}

This method updates the record with the new data. If this method fails, which it might do if the user does not have permission to
update the record, or if there are validation rules that are triggered by the change, the page is displayed along with error messages
describing the error. The values the user entered are not lost. They remain as they were when the user clicked the Save button.
Assuming there are no errors, the data on the object is updated, the view state is updated, and, since the action that triggered the
postback did not include a page redirect, the view state is updated. The resulting HTML is sent to the browser:

SEE ALSO:
Using the Development Mode Footer

Testing Custom Controllers and Controller Extensions


Controller extensions and custom controllers, like all Apex scripts, should be covered by unit tests. Unit tests are class methods that verify
whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, and are
flagged with the testMethod keyword in the method definition.
When writing unit tests for controller extension and custom controller classes, you can set query parameters that can then be used in
the tests. For example, the following custom controller and markup is based on the example from Controller Methods on page 92, but

110

Custom Controllers and Controller Extensions

Testing Custom Controllers and Controller Extensions

has been extended to expect the following query parameter in the URL for the page: ?qp=yyyy. A test method class follows, which
exercises the functionality of this page:
public class thecontroller {
private
private
private
private
private

String
String
String
String
String

firstName;
lastName;
company;
email;
qp;

public thecontroller() {
[Link] = [Link]().getParameters().get('qp');
}
public String getFirstName() {
return [Link];
}
public void setFirstName(String firstName) {
[Link] = firstName;
}
public String getLastName() {
return [Link];
}
public void setLastName(String lastName) {
[Link] = lastName;
}
public String getCompany() {
return [Link];
}
public void setCompany(String company) {
[Link] = company;
}
public String getEmail() {
return [Link];
}
public void setEmail(String email) {
[Link] = email;
}
public PageReference save() {
PageReference p = null;
if ([Link] == null || !'yyyy'.equals([Link])) {
p = [Link];
[Link]().put('error', 'noParam');
} else {
try {

111

Custom Controllers and Controller Extensions

Testing Custom Controllers and Controller Extensions

Lead newlead = new Lead(LastName=[Link],


FirstName=[Link],
Company=[Link],
Email=[Link]);
insert newlead;
} catch (Exception e) {
p = [Link];
[Link]().put('error', 'noInsert');
}
}
if (p == null) {
p = [Link];
}
[Link](true);
return p;
}
}

The controller calls two additional pages: a success page and a failure page. The text of those pages is not important for this example.
They merely have to exist.
The following markup uses the controller above:
<apex:page controller="thecontroller" tabstyle="lead">
<apex:pageBlock>
<apex:form>
<h1>Test page for adding leads</h1>
<p>This is a test page for adding leads.</p>
<p>First name: <apex:inputText value="{!FirstName}"></apex:inputText></p>
<p>Last name: <apex:inputText value="{!LastName}"></apex:inputText></p>
<p>Company: <apex:inputText value="{!Company}"></apex:inputText></p>
<p>Email address: <apex:inputText value="{!Email}"></apex:inputText></p>
<apex:commandButton action="{!save}" value="Save New Lead"/>
</apex:form>
</apex:pageBlock>
</apex:page>

The following class tests the controller:


@isTest
public class thecontrollerTests {
public static testMethod void testMyController() {
PageReference pageRef = [Link];
[Link](pageRef);
thecontroller controller = new thecontroller();
String nextPage = [Link]().getUrl();
// Verify that page fails without parameters
[Link]('/apex/failure?error=noParam', nextPage);
// Add parameters to page URL
[Link]().getParameters().put('qp', 'yyyy');

112

Custom Controllers and Controller Extensions

Validation Rules and Custom Controllers

// Instantiate a new controller with all parameters in the page


controller = new thecontroller();
[Link]('lastname');
[Link]('firstname');
[Link]('acme');
[Link]('firstlast@[Link]');
nextPage = [Link]().getUrl();
// Verify that the success page displays
[Link]('/apex/success', nextPage);
Lead[] leads = [select id, email from lead where Company = 'acme'];
[Link]('firstlast@[Link]', leads[0].email);
}
}

Tip: If you are testing your controller you may see the following error message:
Method does not exist or incorrect signature: [Link]([Link])

If this message appears, look to see if you have created a class called Test. If you have, rename the class.
SEE ALSO:
"Testing Apex" in the [Link] Apex Code Developer's Guide

Validation Rules and Custom Controllers


If a user enters data on a Visualforce page that uses a custom controller, and that data causes a validation rule error, the error can be
displayed on the Visualforce page. Like a page that uses a standard controller, if the validation rule error location is a field associated
with an <apex:inputField> component, the error displays there. If the validation rule error location is set to the top of the page,
use the <apex:messages> component within the <apex:page> to display the error. However, to get the information to the
page, the custom controller must catch the exception.
For example, suppose you have the following page:
<apex:page controller="MyController" tabStyle="Account">
<apex:messages/>
<apex:form>
<apex:pageBlock title="Hello {!$[Link]}!">
This is your new page for the {!name} controller. <br/>
You are viewing the {![Link]} account.<br/><br/>
Change Account Name: <p></p>
<apex:inputField value="{![Link]}"/> <p></p>
Change Number of Locations:
<apex:inputField value="{!account.NumberofLocations__c}" id="Custom_validation"/>
<p>(Try entering a non-numeric character here, then hit save.)</p><br/><br/>
<apex:commandButton action="{!save}" value="Save New Account Name"/>
</apex:pageBlock>
</apex:form>
</apex:page>

Note: The ID of a valid account record must be specified as a query parameter in the URL for this page to render. For example,
[Link]

113

Custom Controllers and Controller Extensions

Using the transient Keyword

You need to write a custom controller like the following:


public class MyController {
Account account;
public PageReference save() {
try{
update account;
}
catch(DmlException ex){
[Link](ex);
}
return null;
}
public String getName() {
return 'MyController';
}
public Account getAccount() {
if(account == null)
account = [select id, name, numberoflocations__c from Account
where id = :[Link]().getParameters().get('id')];
return account;
}
}

When the user saves the page, if a validation error is triggered, the exception is caught and displayed on the page as they are for a
standard controller.

Using the transient Keyword


Use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view state
for a Visualforce page. For example:
Transient Integer currentTotal;

You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions, or classes
that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that define the types
of fields declared in the serializable classes.
Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a Visualforce
page that is needed only for the duration of a page request, but should not be part of the page's view state and would use too many
system resources to be recomputed many times during a request.
Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view state. These
objects include the following:
PageReferences
XmlStream classes
Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient, such as
a collection of Savepoints
Most of the objects generated by system methods, such as [Link].

114

Custom Controllers and Controller Extensions

Using the transient Keyword

JSONParser class instances.


Static variables also don't get transmitted through the view state.
The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page causes the
transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date continues to have
its original value, which has been deserialized from the view state, so it remains the same.
<apex:page controller="ExampleController">
T1: {!t1} <br/>
T2: {!t2} <br/>
<apex:form>
<apex:commandLink value="refresh"/>
</apex:form>
</apex:page>
public class ExampleController {
DateTime t1;
transient DateTime t2;
public String getT1() {
if (t1 == null) t1 = [Link]();
return '' + t1;
}
public String getT2() {
if (t2 == null) t2 = [Link]();
return '' + t2;
}
}

115

CHAPTER 8

Advanced Examples

The examples in the quick start tutorial are considered beginning examples, and primarily use only Visualforce markup. Advanced
examples use [Link] Apex code in addition to Visualforce markup.

Creating Your First Custom Controller


Up through this point, all of the examples in this tutorial have used the standard Account controller to define the underlying logic of
each page. Visualforce, however, allows you to add your own logic and navigation controls to a page by defining a custom controller.
The following topics walk through the basics of creating a custom controller class and defining class methods that can interact with
Visualforce markup:
Creating a Custom Controller Class
Defining Getter Methods
Defining Action Methods
Defining Navigation Methods
Mass-Updating Records with a Custom List Controller
Note: You can add, edit, or delete Apex using the Salesforce user interface only in a Developer Edition, a Salesforce Enterprise
Edition trial organization, or a sandbox organization. In a Salesforce production organization, you can only make changes to Apex
using either the [Link] Migration Tool or the [Link] API compileAndTest call.

Creating a Custom Controller Class


A custom controller is simply an Apex class. For example, the following code is a valid, though ineffective, controller class:
public class MyController {
}

You can create a controller class and add it to your page in two different ways:
Add the controller attribute to your page and use a quick fix to create the controller class on the fly:
1. In the page editor, add the controller attribute to the <apex:page> tag. For example:
<apex:page controller="MyController">
<apex:pageBlock title="Hello {!$[Link]}!">
This is your new page.
</apex:pageBlock>
</apex:page>

2. Use the quick fix option to automatically create a new Apex class named MyController.
Create and save the controller class in the Apex editor of your choice, and then reference it in your page:

116

Advanced Examples

Defining Getter Methods

1. In the application, from Setup, enter Apex Classes in the Quick Find box, then select Apex Classes and click New to
create a new class.
2. Return to your page and add the controller attribute to the <apex:page> tag as described in the example above.
Note: A page can only reference one controller at a time. You cant use both the standardController attribute and the
controller attribute in an <apex:page> tag.
As soon as you save a page that references a valid custom controller, a second Controller editor tab is available next to the Page Editor.
This editor allows you to toggle back and forth between your page markup and the Apex that defines the pages logic.
The Custom Controller Editor

Defining Getter Methods


One of the primary tasks for a Visualforce controller class is to give developers a way of displaying database and other computed values
in page markup. Methods that enable this type of functionality are called getter methods, and are typically named getIdentifier,
where Identifier is the name for the records or primitive values returned by the method.
For example, the following controller has a getter method for returning the name of the controller as a string:
public class MyController {
public String getName() {
return 'MyController';
}
}

To display the results of a getter method in a page, use the name of the getter method without the get prefix in an expression. For
example, to display the result of the getName method in page markup, use {!name}:
<apex:page controller="MyController">
<apex:pageBlock title="Hello {!$[Link]}!">
This is your new page for the {!name} controller.
</apex:pageBlock>
</apex:page>

117

Advanced Examples

Defining Getter Methods

In earlier examples that used the standard Account controller, the pages displayed values from an account record specified in the URL
(with the id query string parameter) by using an {!account.<fieldName>} expression. This was possible because the Account
standard controller includes a getter method named getAccount that returns the specified account record. We can mimic this
functionality in a custom controller with the following code:
public class MyController {
public String getName() {
return 'MyController';
}
public Account getAccount() {
return [select id, name from Account
where id = :[Link]().getParameters().get('id')];
}
}

Note: For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For
example, if 001D000000IRt53 is the account ID, the resulting URL should be:
[Link]

The getAccount method uses an embedded SOQL query to return the account specified by the id parameter in the URL of the
page. To access id, the getAccount method uses the ApexPages namespace:
First the currentPage method returns the PageReference instance for the current page. PageReference returns a
reference to a Visualforce page, including its query string parameters.
Using the page reference, use the getParameters method to return a map of the specified query string parameter names and
values.
Then a call to the get method specifying id returns the value of the id parameter itself.
A page that uses the MyController controller can display either the account name or id fields with an {![Link]} or
{![Link]} expression, respectively. Only those fields are available to the page because those were the only fields returned
by the SOQL query in the controller.
To more closely mimic the standard Account controller, we can add the tabStyle attribute to the <apex:page> tag to give the
page the same styling as other account pages. The markup for the page now looks like this:
<apex:page controller="MyController" tabStyle="Account">
<apex:pageBlock title="Hello {!$[Link]}!">
This is your new page for the {!name} controller. <br/>
You are viewing the {![Link]} account.
</apex:pageBlock>
</apex:page>

118

Advanced Examples

Defining Action Methods

Using a Custom Controller to Display Values on a Page

Defining Action Methods


Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of
the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following
tags:
<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as onclick, onmouseover, and so on) on another, named component, call
an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
For example, in the sample page described in Using Input Components in a Page on page 24, a command button is bound to the
save method in the Account standard controller. We can adapt that previous example so that it now uses the MyController custom
controller:
<apex:page controller="MyController" tabStyle="Account">
<apex:form>
<apex:pageBlock title="Hello {!$[Link]}!">
You are viewing the {![Link]} account. <p/>
Change Account Name: <p/>
<apex:inputField value="{![Link]}"/> <p/>
<apex:commandButton action="{!save}" value="Save New Account Name"/>
</apex:pageBlock>
</apex:form>
</apex:page>

119

Advanced Examples

Defining Action Methods

Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
[Link]

Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
After saving the page above, the Visualforce editor offers a quick fix option to add the save method to the MyController class. If you
click the quick fix link, MyController now looks like this:
public class MyController {
public PageReference save() {
return null;
}
public String getName() {
return 'MyController';
}
public Account getAccount() {
return [select id, name from Account
where id = :[Link]().getParameters().get('id')];
}
}

The save method that is generated by the quick fix takes the standard signature for an action method: it is public, returns a PageReference,
and contains no arguments.
Ultimately, the save method definition must update the database with new account values, but first we must define a member variable
to save the account information that is retrieved from the database. Without a member variable for the account, the record retrieved
from the database does not persist after its values are used to render the page, and the user's updates to the record cannot be saved.
To introduce this member variable, two parts of the controller code need to change:
The member variable must be added to the class
The member variable must be set when getAccount performs the initial query
public class MyController {
Account account;
public PageReference save() {
return null;
}
public String getName() {
return 'MyController';
}
public Account getAccount() {
if(account == null)
account = [select id, name, site from Account
where id = :[Link]().getParameters().get('id')];
return account;
}
}

120

Advanced Examples

Defining Navigation Methods

Now that the member variable is in place, all that the save method needs to do is update the database:
public class MyController {
Account account;
public PageReference save() {
update account;
return null;
}
public String getName() {
return 'MyController';
}
public Account getAccount() {
if(account == null)
account = [select id, name, site from Account
where id = :[Link]().getParameters().get('id')];
return account;
}
}

A more robust solution for save might catch various exceptions, look for duplicates, and so on. Since this is meant to be a simple
example, those details have been left out.
To test this page, change the value in the Change Account Name field and click Save New Account Name. As with the standard
Account controller example, the page simply refreshes with the new account name. In the next example, we will extend the save action
so that instead of refreshing the current page, it navigates the user to a different confirmation page.
Note: For the page to render properly, you must specify a valid account ID in the URL. For example, if 001D000000HRgU6 is
the account ID, use the following URL:
[Link]

Defining Navigation Methods


In addition to performing database updates and other computations, custom controller action methods can navigate users to a different
page by returning a PageReference object.
A PageReference is a reference to an instantiation of a page. Among other attributes, PageReferences consist of a URL and a set of query
parameter names and values.
In a custom controller or controller extension, you can refer to or instantiate a PageReference in one of the following ways:

121

Advanced Examples

Defining Navigation Methods

[Link]

Refers to a PageReference for a Visualforce page that has already been saved in your organization. By referring to a page in this way,
the platform recognizes that this controller or controller extension is dependent on the existence of the specified page and will
prevent the page from being deleted while the controller or extension exists.

PageReference pageRef = new PageReference('partialURL');

Creates a PageReference to any page that is hosted on the [Link] platform. For example, setting 'partialURL' to
'/apex/HelloWorld' refers to the Visualforce page located at
[Link] Likewise, setting 'partialURL' to '/' + 'recordID'
refers to the detail page for the specified record.
This syntax is less preferable for referencing other Visualforce pages than [Link] because the PageReference
is constructed at runtime, rather than referenced at compile time. Runtime references are not available to the referential integrity
system. Consequently, the platform doesn't recognize that this controller or controller extension is dependent on the existence of
the specified page and won't issue an error message to prevent user deletion of the page.

PageReference pageRef = new PageReference('fullURL');

Creates a PageReference for an external URL. For example:


PageReference pageRef = new PageReference('[Link]

For this example, suppose you want to redirect a user to another page with a new URL after he or she clicks Save. To do this, first create
a second page named mySecondPage by navigating to the following URL and using the quick fix:
[Link]

Then add the following markup to mySecondPage. For simplicity, just use the following standard-controller-based page that was defined
earlier in the tutorial:
<apex:page standardController="Account">
Hello {!$[Link]}!
<p>You are viewing the {![Link]} account.</p>
</apex:page>

Now return to the original page that you built in Defining Action Methods on page 119 and make sure that you have specified an account
id query parameter in the URL. Edit the save method in the controller so that it returns a PageReference to the new page you just
created, mySecondPage:
public class MyController {
Account account;
public PageReference save() {
update account;
PageReference secondPage = [Link];
[Link](true);
return secondPage;
}
public String getName() {
return 'MyController';
}

122

Advanced Examples

Creating a Wizard

public Account getAccount() {


if(account == null)
account = [select id, name, site from Account
where id = :[Link]().getParameters().get('id')];
return account;
}
}

Notice in the code above that the redirect attribute for the PageReference is set to true. If this attribute is not set, the PageReference
is returned to the browser, but no navigation occursthe URL for the original page remains the same. If you want to change the URL
as a result of navigation, you have to set the redirect attribute.
If you test the page now, clicking Save New Account Name navigates to mySecondPage, but the data context is lostthat is, no value
is available for {![Link]}. The reason for this is that when a redirect occurs the controller clears the context state. Consequently
we need to reset the id query string parameter in the PageReference's parameter map:
public class MyUpdatedController {
Account account;
public PageReference save() {
update account;
PageReference secondPage = [Link];
[Link](true);
[Link]().put('id',[Link]);
return secondPage;
}
public String getName() {
return 'MyController';
}
public Account getAccount() {
if(account == null)
account = [select id, name, site from Account
where id = :[Link]().getParameters().get('id')];
return account;
}
}

Creating a Wizard
Having learned about the essential features of Visualforce markup and controllers, this final example shows how they can be used
together to create a custom, three-step wizard that allows users to create an opportunity at the same time as a related contact, account,
and contact role:
The first step captures information related to the account and contact
The second step captures information related to the opportunity
The final step shows which records will be created and allows the user to save or cancel
To implement this wizard, we must define three pages for each of the three steps in the wizard, plus a single custom controller that sets
up navigation between each of the pages and tracks the data that the user enters.

123

Advanced Examples

Creating a Wizard

Important: Data that's used across several Visualforce pages must be defined within the first page, even if that page isn't using
the data. For example, if a field is necessary on pages two and three of a three-step process, page one must also contain the field.
You can hide this field from the user by setting the rendered attribute of the field to false.
The code for each of these components is included in the sections below, but first you need to understand the best procedure for
creating them because each of the three pages references the controller, and the controller references each of the three pages. In what
appears to be a conundrum, you cannot create the controller without the pages, but the pages have to exist to refer to them in the
controller.
We can work out of this problem by first defining pages that are completely empty, then creating the controller, and then adding markup
to the pages. Consequently, the best procedure for creating the wizard pages and controller is as follows:
1. Navigate to the URL for the first page, [Link] and click Create Page
opptyStep1.
2. Repeat the step above for the other pages in the wizard, opptyStep2 and opptyStep3.
3. Create the newOpportunityController controller by adding it as an attribute to the <apex:page> tag on one of your
pages (for example, <apex:page controller="newOpportunityController">, and clicking Create Apex
controller newOpportunityController. Paste in all of the controller code and click Save.
4. Now return to the editors for the three pages that you created and copy in their code. The wizard should now work as expected.
Note: Although you can create an empty page, the reverse is not truein order for a page to refer to a controller, the controller
has to exist with all of its methods and properties.

The Opportunity Wizard Controller


The following Apex class is the controller for all three pages in the New Customer Opportunity wizard:
public class newOpportunityController {
// These four member variables maintain the state of the wizard.
// When users enter data into the wizard, their input is stored
// in these variables.
Account account;
Contact contact;
Opportunity opportunity;
OpportunityContactRole role;

// The next four methods return one of each of the four member
// variables. If this is the first time the method is called,
// it creates an empty record for the variable.
public Account getAccount() {
if(account == null) account = new Account();
return account;
}
public Contact getContact() {
if(contact == null) contact = new Contact();
return contact;
}
public Opportunity getOpportunity() {
if(opportunity == null) opportunity = new Opportunity();

124

Advanced Examples

Creating a Wizard

return opportunity;
}
public OpportunityContactRole getRole() {
if(role == null) role = new OpportunityContactRole();
return role;
}

// The next three methods control navigation through


// the wizard. Each returns a PageReference for one of the three pages
// in the wizard. Note that the redirect attribute does not need to
// be set on the PageReference because the URL does not need to change
// when users move from page to page.
public PageReference step1() {
return Page.opptyStep1;
}
public PageReference step2() {
return Page.opptyStep2;
}
public PageReference step3() {
return Page.opptyStep3;
}

// This method cancels the wizard, and returns the user to the
// Opportunities tab
public PageReference cancel() {
PageReference opportunityPage = new [Link](opportunity).view();
[Link](true);
return opportunityPage;
}
// This method performs the final save for all four objects, and
// then navigates the user to the detail page for the new
// opportunity.
public PageReference save() {
// Create the account. Before inserting, copy the contact's
// phone number into the account phone number field.
[Link] = [Link];
insert account;
// Create the contact. Before inserting, use the id field
// that's created once the account is inserted to create
// the relationship between the contact and the account.
[Link] = [Link];
insert contact;
// Create the opportunity. Before inserting, create
// another relationship with the account.
[Link] = [Link];

125

Advanced Examples

Creating a Wizard

insert opportunity;
// Create the junction contact role between the opportunity
// and the contact.
[Link] = [Link];
[Link] = [Link];
insert role;
// Finally, send the user to the detail page for
// the new opportunity.

PageReference opptyPage = new [Link](opportunity).view();


[Link](true);
return opptyPage;
}
}

Step One of the Opportunity Wizard


The following code defines the first page of the wizard (opptyStep1) in which data about the associated contact and account is
gathered from the user:
<apex:page controller="newOpportunityController" tabStyle="Opportunity">
<script>
function confirmCancel() {
var isCancel = confirm("Are you sure you wish to cancel?");
if (isCancel) return true;
return false;
}
</script>
<apex:sectionHeader title="New Customer Opportunity" subtitle="Step 1 of 3"/>
<apex:form>
<apex:pageBlock title="Customer Information" mode="edit">
<!-- The pageBlockButtons tag defines the buttons that appear at the top
and bottom of the pageBlock. Like a facet, it can appear anywhere in
a pageBlock, but always defines the button areas.-->
<!-- The Next button contained in this pageBlockButtons area
calls the step2 controller method, which returns a pageReference to
the next step of the wizard. -->
<apex:pageBlockButtons>
<apex:commandButton action="{!step2}" value="Next"/>
<apex:commandButton action="{!cancel}" value="Cancel"
onclick="return confirmCancel()" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Account Information">
<!-- Within a pageBlockSection, inputFields always display with their
corresponding output label. -->

126

Advanced Examples

Creating a Wizard

<apex:inputField id="accountName" value="{![Link]}"/>


<apex:inputField id="accountSite" value="{![Link]}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Contact Information">
<apex:inputField id="contactFirstName" value="{![Link]}"/>
<apex:inputField id="contactLastName" value="{![Link]}"/>
<apex:inputField id="contactPhone" value="{![Link]}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Notice the following about the markup for the first page of the wizard:
The <apex:pageBlock> tag can take an optional <apex:pageBlockButtons> child element that controls the buttons
that appear in the header and footer of the component. The order in which the <apex:pageBlockButtons> tag appears
in the <apex:pageBlock> body does not matter. In this page of the wizard, the <apex:pageBlockButtons> tag
includes the Next button that appears in the footer of the page block area.
The wizard relies on JavaScript code to display a dialog box asking if a user wants to navigate away when clicking the Cancel button.
Although the example includes the JavaScript directly in the markup for simplicity, it is a better practice to put JavaScript code in a
static resource and reference that resource instead.
In this page of the wizard, the Next button calls the step2 method in the controller, which returns a PageReference to the
next step of the wizard:
<apex:pageBlockButtons>
<apex:commandButton action="{!step2}" value="Next"/>
</apex:pageBlockButtons>

Command buttons must appear in a form, because the form component itself is responsible for refreshing the page display based
on the new PageReference.
An <apex:pageBlockSection> tag organizes a set of data for display. Similar to a table, an <apex:pageBlockSection>
consists of one or more columns, each of which spans two cellsone for a field's label, and one for its value. Each component found
in the body of an <apex:pageBlockSection> tag is placed into the next cell in a row until the number of columns is reached.
At that point, the next component wraps to the next row and is placed in the first cell.
Some components, including <apex:inputField>, automatically span both cells of a page block section column at once,
filling in both a field's label and value. For example, in the Contact Information area of this page, the First Name field is in the
first column, the Last Name field is in the second column, and the Phone field wraps to the first column of the next row:
<apex:pageBlockSection title="Contact Information">
<apex:inputField id="contactFirstName" value="{![Link]}"/>
<apex:inputField id="contactLastName" value="{![Link]}"/>
<apex:inputField id="contactPhone" value="{![Link]}"/>
</apex:pageBlockSection>

The value attribute on the first <apex:inputField> tag in the preceding code excerpt assigns the user's input to the
firstName field of the contact record that's returned by the getContact method in the controller.
Your page should look like this:

127

Advanced Examples

Creating a Wizard

Step 1 of the New Customer Opportunity Wizard

Step Two of the Opportunity Wizard


The following code defines the second page of the wizard (opptyStep2) in which data about the opportunity is gathered from the
user:
<apex:page controller="newOpportunityController" tabStyle="Opportunity">
<script>
function confirmCancel() {
var isCancel = confirm("Are you sure you wish to cancel?");
if (isCancel) return true;
return false;
}
</script>
<apex:sectionHeader title="New Customer Opportunity" subtitle="Step 2 of 3"/>
<apex:form>
<apex:pageBlock title="Opportunity Information" mode="edit">
<apex:pageBlockButtons>
<apex:commandButton action="{!step1}" value="Previous"/>
<apex:commandButton action="{!step3}" value="Next"/>
<apex:commandButton action="{!cancel}" value="Cancel"
onclick="return confirmCancel()" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Opportunity Information">
<apex:inputField id="opportunityName" value="{![Link]}"/>
<apex:inputField id="opportunityAmount" value="{![Link]}"/>
<apex:inputField id="opportunityCloseDate" value="{![Link]}"/>
<apex:inputField id="opportunityStageName" value="{![Link]}"/>
<apex:inputField id="contactRole" value="{![Link]}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Notice that although the markup for placing the Close Date, Stage, and Role for Contact fields on the form is the same
as the other fields, the <apex:inputField> tag examines the data type of each field to determine how to display it. For example,
clicking in the Close Date text box brings up a calendar from which users can select the date.

128

Advanced Examples

Creating a Wizard

Your page should look like this:


Step 2 of the New Customer Opportunity Wizard

Step Three of the Opportunity Wizard


The last block of code defines the third page of the wizard (opptyStep3) in which all inputted data is displayed. The user can decide
to save the operation or return to the previous step:
<apex:page controller="newOpportunityController" tabStyle="Opportunity">
<script>
function confirmCancel() {
var isCancel = confirm("Are you sure you wish to cancel?");
if (isCancel) return true;
return false;
}
</script>
<apex:sectionHeader title="New Customer Opportunity" subtitle="Step 3 of 3"/>
<apex:form>
<apex:pageBlock title="Confirmation">
<apex:pageBlockButtons>
<apex:commandButton action="{!step2}" value="Previous"/>
<apex:commandButton action="{!save}" value="Save"/>
<apex:commandButton action="{!cancel}" value="Cancel"
onclick="return confirmCancel()" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Account Information">
<apex:outputField value="{![Link]}"/>
<apex:outputField value="{![Link]}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Contact Information">
<apex:outputField value="{![Link]}"/>
<apex:outputField value="{![Link]}"/>
<apex:outputField value="{![Link]}"/>
<apex:outputField value="{![Link]}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Opportunity Information">
<apex:outputField value="{![Link]}"/>
<apex:outputField value="{![Link]}"/>

129

Advanced Examples

Advanced Visualforce Dashboard Components

<apex:outputField value="{![Link]}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Notice that the third page of the wizard simply writes text to the page with <apex:outputField> tags.
Your final page should look like this:
Step 3 of the New Customer Opportunity Wizard

Advanced Visualforce Dashboard Components


Visualforce pages can be used as dashboard components. A dashboard shows data from source reports as visual components, which
can be charts, gauges, tables, metrics, or Visualforce pages. The components provide a snapshot of key metrics and performance indicators
for your organization. Each dashboard can have up to 20 components.
Visualforce pages that use the Standard Controller cant be used in dashboards. To be included in a dashboard, a Visualforce page must
have either no controller, use a custom controller, or reference a page bound to the StandardSetController Class. If a Visualforce page
does not meet these requirements, it does not appear as an option in the dashboard component Visualforce Page drop-down
list.
The following example shows a Visualforce page that can be used within a dashboard and that uses a custom list controller. It displays
all of the open cases associated with a contact named Babara Levy:
<apex:page controller="retrieveCase" tabStyle="Case">
<apex:pageBlock>
{!contactName}'s Cases
<apex:pageBlockTable value="{!cases}" var="c">
<apex:column value="{![Link]}"/>
<apex:column value="{![Link]}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

130

Advanced Examples

Integrating Visualforce and Google Charts

This code shows the custom list controller associated with the page:
public class retrieveCase {
public String getContactName() {
return 'Babara Levy';
}
public List<Case> getCases() {
return [SELECT status, subject FROM Case
WHERE [Link] = 'Babara Levy' AND status != 'Closed' limit 5];
}
}

Sample of a Visualforce Page Running in a Dashboard

SEE ALSO:
Creating Visualforce Dashboard Components

Integrating Visualforce and Google Charts


Google Charts provides a way to dynamically render data through different visualizations. Combined with Visualforce, the Google Charts
can offer more flexibility and distribution potential than using a dashboard. Since the charts are generated through a URL, the visualizations
can be shared and embedded wherever images are permitted.
There are two prerequisites before using the Google Charts API. The first is to determine how to encode the data. The Google Charts API
has three data encoding typestext, simple, and extended. For this example, we'll only use the simple encoding. The second is to
decide what type of chart to use. For this example, a user will choose between a bar graph or a line chart.
The custom controller has two important functionsinit() and create()that correspond to the requirements above:
The function init() takes a numeric value and converts it to Google Chart's simple data encoding type. For more information,
see Simple Encoding Data Format in the Google Charts API documentation.
The function create() constructs the URL that makes the request to the Google Charts API.
The following code represents the controller for the Visualforce page:
/* This class contains the encoding algorithm for use with the
Google chartAPI. */
public class GoogleDataEncoding {
// Exceptions to handle any erroneous data
public class EncodingException extends Exception {}
public class UnsupportedEncodingTypeException
extends Exception {}

131

Advanced Examples

Integrating Visualforce and Google Charts

/* The encoding map which takes an integer key and returns the
respective encoding value as defined by Google.
This map is initialized in init() */
private Map<Integer, String> encodingMap { get; set; }
/* The maximum encoding value supported for the given encoding
type. This value is set during init() */
private Integer encodingMax { get; set; }
/* The minimum encoding value supported for the given encoding
type. This value is set during init() */
private Integer encodingMin { get; set; }
/* The encoding type according to Google's API. Only SIMPLE
is implemented. */
public enum EncodingType { TEXT, SIMPLE, EXTENDED }
/* The minimum value to use in the generation of an encoding
value. */
public Integer min { get; private set; }
/* The maximum value to use in the generation of an encoding
value. */
public Integer max { get; private set; }
// The encoding type according to the API defined by Google
public EncodingType eType { get; private set; }
// Corresponds to the data set provided by the page
public String dataSet { get; set; }
// Corresponds to the type of graph selected on the page
public String graph { get; set; }
// The URL that renders the Google Chart
public String chartURL { get; set; }
// Indicates whether the chart should be displayed
public Boolean displayChart { get; set; }
public GoogleDataEncoding() {
min = 0;
max = 61;
eType = [Link];
displayChart = false;
init();
}
public PageReference create() {
String[] dataSetList = [Link](',', 0);
String mappedValue = 'chd=s:';
chartURL = '[Link]
+ '&amp;chtt=Time+vs|Distance&amp;chxt=x,y,x,y'

132

Advanced Examples

Integrating Visualforce and Google Charts

+ '&amp;chxr=0,0,10,1|1,0,65,5'
+ '&amp;chxl=2:|Seconds|3:|Meters';
if ([Link]('barChart') == 0)
{
chartURL += '&amp;cht=bvs';
}
else if ([Link]('lineChart') == 0)
{
chartURL += '&amp;cht=ls';
}
else
{
throw new EncodingException('An unsupported chart type'
+ 'was selected: ' + graph + ' does not exist.');
}
for(String dataPoint : dataSetList)
{
mappedValue +=
getEncode([Link]([Link]()));
}
chartURL += '&amp;' + mappedValue;
displayChart = true;
return null;
}

/* This method returns the encoding type parameter value that


matches the specified encoding type. */
public static String getEncodingDescriptor(EncodingType t) {
if(t == [Link]) return 't';
else if(t == [Link]) return 's';
else if(t == [Link]) return 'e';
else return '';
}
/* This method takes a given number within the declared
range of the encoding class and encodes it according to the
encoding type. If the value provided fall outside of the
declared range, an EncodingException is thrown. */
public String getEncode(Integer d) {
if(d > max || d < min) {
throw new EncodingException('Value provided ' + d
+ ' was outside the declared min/max range ('
+ min + '/' + max + ')');
}
else {
return [Link](d);
}
}
/* This method initializes the encoding map which is then

133

Advanced Examples

Integrating Visualforce and Google Charts

stored for expected repetitious use to minimize statement


invocation. */
private void init() {
if(eType == [Link]) {
encodingMax = 61;
encodingMin = 0;
encodingMap = new Map<Integer, String>();
[Link](0,'A');
[Link](1,'B');
[Link](2,'C');
[Link](3,'D');
[Link](4,'E');
[Link](5,'F');
[Link](6,'G');
[Link](7,'H');
[Link](8,'I');
[Link](9,'J');
[Link](10,'K');
[Link](11,'L');
[Link](12,'M');
[Link](13,'N');
[Link](14,'O');
[Link](15,'P');
[Link](16,'Q');
[Link](17,'R');
[Link](18,'S');
[Link](19,'T');
[Link](20,'U');
[Link](21,'V');
[Link](22,'W');
[Link](23,'X');
[Link](24,'Y');
[Link](25,'Z');
[Link](26,'a');
[Link](27,'b');
[Link](28,'c');
[Link](29,'d');
[Link](30,'e');
[Link](31,'f');
[Link](32,'g');
[Link](33,'h');
[Link](34,'i');
[Link](35,'j');
[Link](36,'k');
[Link](37,'l');
[Link](38,'m');
[Link](39,'n');
[Link](40,'o');
[Link](41,'p');
[Link](42,'q');
[Link](43,'r');
[Link](44,'s');
[Link](45,'t');
[Link](46,'u');

134

Advanced Examples

Integrating Visualforce and Google Charts

[Link](47,'v');
[Link](48,'w');
[Link](49,'x');
[Link](50,'y');
[Link](51,'z');
[Link](52,'0');
[Link](53,'1');
[Link](54,'2');
[Link](55,'3');
[Link](56,'4');
[Link](57,'5');
[Link](58,'6');
[Link](59,'7');
[Link](60,'8');
[Link](61,'9');
}
}
}

The Visualforce page needs two input elements: one for the chart type, and one for the data set. Below is a sample page that constructs
the form to collect this information:
<apex:page controller="GoogleDataEncoding">
<apex:form >
<apex:pageBlock
title="Create a Google Chart for Time and Distance">
<apex:outputLabel
value="Enter data set, separated by commas: "
for="dataInput"/><br/>
<apex:inputTextArea
id="dataInput" title="First Data Point"
value="{!dataSet}" rows="3" cols="50"/><br/>
<apex:selectRadio value="{!graph}"
layout="pageDirection">
<apex:selectOption itemValue="barChart"
itemLabel="Horizontal Bar Chart"/>
<apex:selectOption itemValue="lineChart"
itemLabel="Line Chart"/>
</apex:selectRadio>
<apex:commandButton action="{!create}"
value="Create"/>
</apex:pageBlock>
</apex:form>
<apex:image url="{!chartURL}" alt="Sample chart"
rendered="{!displayChart}"/>
</apex:page>

For a sample, enter the following sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. Your page should render
the following:

135

Advanced Examples

Mass-Updating Records with a Custom List Controller

Mass-Updating Records with a Custom List Controller


To create pages that perform mass updates, use the prototype object contained in the StandardSetController class.
The list controller tracks two sets of records: a primary list containing all the records selected by the filter, and a secondary list containing
those records the user selected. The secondary list is usually established on a standard listview page where the user can check boxes to
select the records. The user can then click on a custom list button that navigates to your custom mass update page, which uses the
prototype object to apply new field values to the user's selection. The prototype object operates on all the records in the user's selection.
To retrieve the prototype object in your custom controller, use the StandardSetController's getRecord method. For example, to
enable mass updates for Opportunities, use the singular term for its associated object (Opportunity) to set field values for all records
in the selection:
1. Create a Visualforce page called massupdatestages.
2. Provide the following controller:
public class selectedSizeWorkaround {
[Link] setCon;
public selectedSizeWorkaround([Link] controller) {
setCon = controller;
}
public integer getMySelectedSize() {
return [Link]().size();
}
public integer getMyRecordsSize() {
return [Link]().size();
}
}

136

Advanced Examples

Mass-Updating Records with a Custom List Controller

3. Provide the following markup:


<apex:page
standardController="Opportunity"
recordSetVar="opportunities"
extensions="selectedSizeWorkaround"
showHeader="false"
id="muopp"
>
<apex:form id="muform">
<apex:pageMessage
summary="Selected Collection Size: {!mySelectedSize}"
severity="info"
id="mupms"
/>
<apex:pageMessage
summary="Record Set Size: {!myRecordsSize}"
severity="info"
id="mupmr"
/>
<apex:pageBlock title="Opportunity Mass-Update" mode="edit" id="mub1">
<apex:pageMessages />
<apex:pageBlockSection id="mus1">
<apex:inputField value="{![Link]}" id="stagename">
<apex:actionSupport event="onchange" rerender="muselectedlist"/>
</apex:inputField>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom" id="mubut">
<apex:commandButton value="Save" action="{!save}" id="butsav"/>
<apex:commandButton value="Cancel" action="{!cancel}" id="butcan"/>
</apex:pageBlockButtons>
</apex:pageBlock>
<apex:pageBlock title="Selected Opportunities" id="muselectedlist">
<apex:pageBlockTable value="{!selected}" var="opp" id="mutab">
<apex:column value="{![Link]}" id="oppname"/>
<apex:column value="{![Link]}" id="oppstage"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

4. From the object management settings for opportunities, go to Buttons, Links, and Actions.
5. Click New Button or Link.
6. Set the Button Label to Mass Update Stages, and set the Name to MassUpdateStages.
7. Set the Display Type to List Button and ensure that Display Checkboxes (for Multi-Record
Selection) is checked. Set the Behavior to Display in existing window with sidebar, and set the Content
Source to Visualforce Page. Click the name of the page you just created to associate it with this button.
8. Click Save.
9. From the object management settings for opportunities, go to Search Layouts. Then click Edit next to Opportunities List View.
10. Under Custom Buttons, move the Mass Update Stages button to the Selected Buttons list.
11. Click Save.

137

Advanced Examples

Mass-Updating Records with a Custom List Controller

12. Click the Opportunities tab. Select or create a filter that displays some existing opportunities you would like to change.
13. You will see checkboxes next to each of the results. Click any number of checkboxes and click the Mass Update Stages button to
change the selected stages to any value you wish.
14. Click Save.
While this example shows you how to update one field, any number of fields in the prototype object can be referenced and applied to
the user's selection; any field in the prototype object that the user doesn't set doesn't affect the selected records. Remember that
properties of fields, such as their requiredness, are maintained in the prototype object. For example, if you include an input field on the
page for a required field such as [Link], the user must enter a value for the field.
Note: You only need selectedSizeWorkaround if you want your page to either display or reference the sizes of the user
selection or filtered set. Such a display is helpful since it gives the user information about the set that will be modified by the mass
update.
SEE ALSO:
Salesforce Help: Find Object Management Settings

138

CHAPTER 9

Overriding Buttons, Links, and Tabs with Visualforce

You can override the behavior of standard buttons on record detail pages. You can also override the tab home page that displays when
a user clicks a standard, custom, or external object tab.
To override a standard button or a tab home page:
1. Click Edit next to the button or tab home page you want to override.
2. Pick Visualforce Page as an override type.
3. Select the Visualforce page you want to run when users click the button or tab.
When overriding buttons with a Visualforce page, you must use the standard controller for the object on which the button appears.
For example, if you want to use a page to override the Edit button on accounts, the page markup must include the
standardController="Account" attribute on the <apex:page> tag:
<apex:page standardController="Account">
<!-- page content here -->
</apex:page>

When overriding tabs with a Visualforce page, you can select only Visualforce pages that use the standard list controller for that tab,
pages with a custom controller, or pages with no controller.
When overriding lists with a Visualforce page, you can select only Visualforce pages that use a standard list controller.
When overriding the New button with a Visualforce page, you have the option to skip the record type selection page. If you choose
this option, new records you create arent forwarded to the record type selection page. Salesforce assumes that your Visualforce
page is already handling record types.
Tip: Use a controller extension when you need to add extra functionality to Visualforce page that you are using as an override.
4. Optionally, enter any comments to note the reason for this change.
5. Click Save.
To remove an override:
1. From the appropriate objects management settings, go to Buttons, Links, and Actions.
2. Click Edit next to the override.
3. Select No Override (default behavior).
4. Click OK.
SEE ALSO:
Salesforce Help: Find Object Management Settings

139

Overriding Buttons, Links, and Tabs with Visualforce

Overriding Tabs Using a Standard List Controller

Overriding Tabs Using a Standard List Controller


Pages that use standard list controllers can be used to override tabs. For example, if you create a page named overrideAccountTab
that is associated with the Account standard list controller:
<apex:page standardController="Account" recordSetVar="accounts" tabStyle="account">
<apex:pageBlock >
<apex:pageBlockTable value="{!accounts}" var="a">
<apex:column value="{![Link]}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

Then, you can override the Account tab to display that page instead of the standard Account home page.
1. From the object management settings for accounts, go to Buttons, Links, and Actions.
2. Click Edit for the Accounts Tab.
3. From the Visualforce Page drop-down list, select the overrideAccountTab page.
4. Click Save.
Note: Make sure you have made this page available to all your users by setting the page level security appropriately.

SEE ALSO:
Salesforce Help: Find Object Management Settings

Defining Custom Buttons and Links for Visualforce


Before creating a custom button or link, determine what action you want to occur when a user clicks it.
1. From the management settings for the appropriate object, go to Buttons, Links, and Actions. Custom buttons are not available on
the user object or custom home pages.
Custom buttons and links are available for activities in the object management settings for tasks and events. However, you can
override a button that applies to both tasks and events from the object management settings for activities.
2. Click the button for creating a new button or link.
3. Enter the following attributes.
Attribute Name

Description

Label

Text that displays on user pages for the custom button or link.

Name

The unique name for the button or link used when referenced from a merge [Link] name can
contain only underscores and alphanumeric characters, and must be unique in your org. It must
begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive
underscores.

Namespace Prefix

In a packaging context, a namespace prefix is a one to 15-character alphanumeric identifier that


distinguishes your package and its contents from packages of other developers on AppExchange.
Namespace prefixes are case-insensitive. For example, ABC and abc are not recognized as unique.

140

Overriding Buttons, Links, and Tabs with Visualforce

Attribute Name

Defining Custom Buttons and Links for Visualforce

Description
Your namespace prefix must be globally unique across all Salesforce organizations. It keeps your
managed package under your control exclusively.

Protected
Component

Protected components cant be linked to or referenced by components created in a subscriber org.


A developer can delete a protected component in a future release without worrying about failing
installations. However, once a component is marked as unprotected and is released globally, the
developer cant delete it.

Description

Text that distinguishes the button or link and is displayed when an administrator is setting up buttons
and links.

Display Type

Determines where the button or link is available on page layouts.


Detail Page Link
Select this option to add the link to the Custom Links section of your page layouts.
Detail Page Button
Select this option to add the custom button to a records detail page. You can add detail page
buttons to the Button section of a page layout only.
List Button
Select this option to add the custom button to a list view, search result layout, or related list.
You can add list buttons to the Related List section of a page layout or the List View and Search
Result layouts only.
For list buttons, Salesforce automatically selects a Display Checkboxes (for Multi-Record
Selection) option that includes a checkbox next to each record in the list, allowing users to
select the records they want applied to the action on the list button. Deselect this option if your
custom button does not require the user to select records. For example, a button that navigates
to another page.

Behavior

Choose the outcome of clicking the button or link.


When applicable, some settings have default values. For example, if you choose Display in
new window, the default height of a new window is 600 pixels.

Content Source

To use a Visualforce page, select Visualforce Page, and choose the page from the drop-down list.
Visualforce pages cannot be used as custom links on the home page.

4. Click Save when you are finished.


Click Quick Save to save and continue editing.
To view the specified URL, click Preview.
To quit without saving your content, click Cancel.
5. Edit the page layout for the appropriate tab or search layout to display the new button or link.
If you add a custom link for users, it is automatically added to the Custom Links section of the user detail page. Detail page buttons
can be added to the Button section of a page layout only.

141

Overriding Buttons, Links, and Tabs with Visualforce

Adding Custom List Buttons using Standard List Controllers

6. Optionally, set the window properties to open the button or link using settings other than the users default browser settings.
SEE ALSO:
Salesforce Help: Find Object Management Settings

Adding Custom List Buttons using Standard List Controllers


In addition to overriding standard buttons and links, you can also create custom list buttons that link to pages that use a standard list
controller. These list buttons can be used on a list page, search results, and any related list for the object and allow you to take actions
on a group of selected records. To indicate the set of records that have been selected, use the {!selected} expression.
For example, to add a custom button to a related list for opportunities that allows you to edit and save the opportunity stage and close
date on selected records:
1. Create the following Apex class:
public class tenPageSizeExt {
public tenPageSizeExt([Link] controller) {
[Link](10);
}
}

2. Create the following page and call it oppEditStageAndCloseDate:


<apex:page standardController="Opportunity" recordSetVar="opportunities"
tabStyle="Opportunity" extensions="tenPageSizeExt">
<apex:form >
<apex:pageBlock title="Edit Stage and Close Date" mode="edit">
<apex:pageMessages />
<apex:pageBlockButtons location="top">
<apex:commandButton value="Save" action="{!save}"/>
<apex:commandButton value="Cancel" action="{!cancel}"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!selected}" var="opp">
<apex:column value="{![Link]}"/>
<apex:column headerValue="Stage">
<apex:inputField value="{![Link]}"/>
</apex:column>
<apex:column headerValue="Close Date">
<apex:inputField value="{![Link]}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

3. Make the page available to all users.


a. From Setup, enter Visualforce Pages in the Quick Find box, then select Visualforce Pages.
b. Click Security for the oppEditStageAndCloseDate page.
c. Add the appropriate profiles to the Enabled Profiles list.

142

Overriding Buttons, Links, and Tabs with Visualforce

Adding Custom List Buttons using Standard List Controllers

d. Click Save.
4. Create a custom button on opportunities.
a. From the object management settings for opportunities, go to Buttons, Links, and Actions.
b. Click the button for creating a new button or link.
c. Set the Label to Edit Stage & Date.
d. Set the Display Type to List Button.
e. Set the Content Source to Visualforce Page.
f. From the Content drop-down list, select oppEditStageAndCloseDate.
g. Click Save.
h. A warning will display notifying you that the button will not be displayed until you have updated page layouts. Click OK.
5. Add the custom button to an account page layout.
a. From the object management settings for accounts, go to Page Layouts.
b. Click Edit for the appropriate page layout.
c. In the Related List Section, click on Opportunities, then click

to edit the properties.

d. In the Custom Buttons section, select Edit Stage & Date in the Available Buttons list and add it to the Selected Buttons list.
e. Click OK.
f. Click Save.
Now, when you visit the account page, there is a new button in the opportunities related list.
Example of New Button

When you select an opportunity and click Edit Stage & Date, you are taken to your custom edit page.
Example of Custom Edit Page

SEE ALSO:
Salesforce Help: Find Object Management Settings

143

Overriding Buttons, Links, and Tabs with Visualforce

Displaying Record Types

Displaying Record Types


Visualforce pages with a Salesforce API version equal to or greater than 20.0 support record types. Record types let you offer different
business processes, picklist values, and page layouts to different users.
After creating a record type in Setup, enabling support for it in Visualforce requires no additional actions on your part. Visualforce pages
for objects that use record types respect your settings. Record type field is named RecordTypeId.
Your record type definitions affect the rendering of <apex:inputField> tags in the following ways:
If the <apex:inputField> tag refers to a picklist field that's filtered by a record type:
The rendered <apex:inputField> component only displays options compatible with that record type.
If the <apex:inputField> component is bound to a dependent picklist with a rendered and editable controlling field,
only options compatible with both the record type and the controlling field value display.
If the <apex:inputField> tag refers to a record type field:
If the user can change the fields record type, or select a record type for the new field, the <apex:inputField> component
renders as a drop-down list. Otherwise, it renders as read-only text.
It's the developer's responsibility to either refresh the page or rerender filtered picklists when the list changes.
In addition, the <apex:outputField> tag's support for record types is identical to a read-only implementation of the
<apex:inputField> behavior.
When overriding the New button with a Visualforce page, you have the option to skip the record type selection page. If you choose this
option, new records you create arent forwarded to the record type selection page. Salesforce assumes that your Visualforce page is
already handling record types.

144

CHAPTER 10 Using Static Resources


Static resources allow you to upload content that you can reference in a Visualforce page, including archives (such as .zip and .jar files),
images, style sheets, JavaScript, and other files.
Using a static resource is preferable to uploading a file to the Documents tab because:
You can package a collection of related files into a directory hierarchy and upload that hierarchy as a .zip or .jar archive.
You can reference a static resource by name in page markup by using the $Resource global variable instead of hard coding
document IDs.
Tip: In addition, using static resources to refer to JavaScript or cascading style sheets (CSS) is preferable to including the markup
inline. Managing this kind of content using static resources allows you to have a consistent look and feel for all your pages and a
shared set of JavaScript functionality.
A single static resource can be up to 5 MB in size, and an organization can have up to 250 MB of static resources, total.
IN THIS SECTION:
Creating a Static Resource
Referencing a Static Resource in Visualforce Markup

Creating a Static Resource


To create a static resource:
1. From Setup, enter Static Resources in the Quick Find box, then select Static Resources.
2. Click New.
3. In the Name text box, enter the text that should be used to identify the resource in Visualforce markup. This name can contain only
underscores and alphanumeric characters, and must be unique in your org. It must begin with a letter, not include spaces, not end
with an underscore, and not contain two consecutive underscores.
Note: If you reference a static resource in Visualforce markup and then change the name of the resource, the Visualforce
markup is updated to reflect that change.
4. In the Description text area, specify an optional description of the resource.
5. Next to the File text box, click Browse to navigate to a local copy of the resource that you want to upload.
A single static resource can be up to 5 MB in size, and an organization can have up to 250 MB of static resources, total.
6. Set the Cache Control:
Private specifies that the static resource data cached on the Salesforce server shouldnt be shared with other users. The static
resource is only stored in cache for the current users session.

145

Using Static Resources

Referencing a Static Resource in Visualforce Markup

Note: Cache settings on static resources are set to private when accessed via a [Link] site whose guest user's profile
has restrictions based on IP range or login hours. Sites with guest user profile restrictions cache static resources only within
the browser. Also, if a previously unrestricted site becomes restricted, it can take up to 45 days for the static resources to
expire from the Salesforce cache and any intermediate caches.
Public specifies that the static resource data cached on the Salesforce server be shared with other users in your organization
for faster load times.
The W3C specifications on Header Field Definitions has more technical information about cache-control.
Note: This feature only works for Sitesenabled organizations that use the static resource.
7. Click Save.
Warning: If you are using WinZip be sure to install the most recent version. Older versions of WinZip may cause a loss of data.

Referencing a Static Resource in Visualforce Markup


The way you reference a static resource in Visualforce markup depends on whether you want to reference a stand-alone file, or whether
you want to reference a file that is contained in an archive (such as a .zip or .jar file):
To reference a stand-alone file, use $Resource.<resource_name> as a merge field, where <resource_name> is the
name you specified when you uploaded the resource. For example:
<apex:image url="{!$[Link]}" width="50" height="50"/>

or
<apex:includeScript value="{!$[Link]}"/>

To reference a file in an archive, use the URLFOR function. Specify the static resource name that you provided when you uploaded
the archive with the first parameter, and the path to the desired file within the archive with the second. For example:
<apex:image url="{!URLFOR($[Link],
'images/[Link]')}" width="50" height="50"/>

or
<apex:includeScript value="{!URLFOR($[Link], '/base/subdir/[Link]')}"/>

You can use relative paths in files in static resource archives to refer to other content within the archive. For example, in your CSS
file, named [Link], you have the following style:
table { background-image: url('img/[Link]') }

When you use that CSS in a Visualforce page, you need to make sure the CSS file can find the image. To do that, create an archive
(such as a zip file) that includes [Link] and img/[Link]. Make sure that the path structure is preserved in
the archive. Then upload the archive file as a static resource named style_resources. Then, in your page, add the following component:
<apex:stylesheet value="{!URLFOR($Resource.style_resources, '[Link]')}"/>

Since the static resource contains both the style sheet and the image, the relative path in the style sheet resolves and the image is
displayed.

146

Using Static Resources

Referencing a Static Resource in Visualforce Markup

Through a custom controller, you can dynamically refer to the contents of a static resource using the <apex:variable> tag.
First, create the custom controller:
global class MyController {
public String getImageName() {
return '[Link]';//this is the name of the image
}
}

Then, refer to the getImageName method in your <apex:variable> tag:


<apex:page renderAs="pdf" controller="MyController">
<apex:variable var="imageVar" value="{!imageName}"/>
<apex:image url="{!URLFOR($[Link], imageVar)}"/>
</apex:page>

If the name of the image changes in the zip file, you can just change the returned value in getImageName.

147

CHAPTER 11 Creating and Using Custom Components


Salesforce provides a library of standard, pre-built components, such as <apex:relatedList> and <apex:dataTable>,
that can be used to develop Visualforce pages. In addition, you can build your own custom components to augment this library. This
chapter provides an overview of custom components and how to create them:
What are Custom Components?
Custom Component Markup
Using Custom Components in a Visualforce Page
Custom Component Attributes
Custom Component Controllers
Defining Custom Components

What are Custom Components?


Similar to the way you can encapsulate a piece of code in a method and then reuse that method several times in a program, you can
encapsulate a common design pattern in a custom component and then reuse that component several times in one or more Visualforce
pages.
For example, suppose you want to create a photo album using Visualforce pages. Each photo in the album has its own border color,
and a text caption that displays beneath it. Rather than repeating the Visualforce markup required for displaying every photo in the
album, you can define a custom component named singlePhoto that has attributes for image, border color, and caption, and then
uses those attributes to display the image on the page. Once defined, every Visualforce page in your organization can leverage the
singlePhoto custom component in the same way as a page can leverage standard components such as <apex:dataTable>
or <apex:relatedList>.
Unlike page templates, which also enable developers to reuse markup, custom components provide more power and flexibility because:
Custom components allow developers to define attributes that can be passed in to each component. The value of an attribute can
then change the way the markup is displayed on the final page, and the controller-based logic that executes for that instance of the
component. This behavior differs from that of templates, which do not have a way of passing information from the page that uses
a template to the template's definition itself.
Custom component descriptions are displayed in the application's component reference dialog alongside standard component
descriptions. Template descriptions, on the other hand, can only be referenced through the Setup area of Salesforce because they
are defined as pages.
SEE ALSO:
Defining Custom Components
Using Custom Components in a Visualforce Page

148

Creating and Using Custom Components

Defining Custom Components

Defining Custom Components


To define a custom component for use in a Visualforce page:
1. In Salesforce from Setup, enter Components in the Quick Find box, then select VisualforceComponents.
2. Click New.
3. In the Label text box, enter the text that should be used to identify the custom component in Setup tools.
4. In the Name text box, enter the text that should identify this custom component in Visualforce markup. This name can contain only
underscores and alphanumeric characters, and must be unique in your org. It must begin with a letter, not include spaces, not end
with an underscore, and not contain two consecutive underscores.
5. In the Description text box, enter a text description of the custom component. This description appears in the component
reference with other standard component descriptions as soon as you click Save.
6. In the Body text box, enter Visualforce markup for the custom component definition. A single component can hold up to 1 MB of
text, or approximately 1,000,000 characters.
7. Click Version Settings to specify the version of Visualforce and the API used with this component. You can also specify versions for
any managed packages installed in your organization.
8. Click Save to save your changes and view the custom components detail screen, or click Quick Save to save your changes and
continue editing your component. Your Visualforce markup must be valid before you can save your component.
Note: You can also create a custom component in Visualforce development mode by adding a reference to a custom component
that does not yet exist to Visualforce page markup. After saving the markup, a quick fix link appears that allows you to create a
new component definition (including any specified attributes) based on the name that you provided for the component.
For example, if you havent yet defined a custom component named myNewComponent and insert <c:myNewComponent
myNewAttribute="foo"/> into existing page markup, after clicking Save a quick fix allows you to define a new custom
component named myNewComponent with the following default definition:
<apex:component>
<apex:attribute name="myattribute" type="String" description="TODO: Describe me"/>
<!-- Begin Default Content REMOVE THIS -->
<h1>Congratulations</h1>
This is your new Component: mynewcomponent
<!-- End Default Content REMOVE THIS -->
</apex:component>

You can modify this definition from Setup by entering Components in the Quick Find box, then selecting
VisualforceComponents, and then clicking Edit next to the myNewComponent custom component.
Once your component has been created, you can view it at
[Link] where the value of
mySalesforceInstance is the host name of your Salesforce instance (for example, [Link]) and the value
of nameOfNewComponent is the value of the Name field on the custom component definition.

The component is displayed as if its a Visualforce page. Consequently, if your component relies on attributes or on the content of the
component tags body, this URL may generate results that you dont expect. To more accurately test a custom component, add it to a
Visualforce page and then view the page.

149

Creating and Using Custom Components

Custom Component Markup

Custom Component Markup


All markup for a custom component is defined within an <apex:component> tag. This tag must be the top-level tag in a custom
component definition. For example:
<apex:component>
<b>
<apex:outputText value="This is my custom component."/>
</b>
</apex:component>

Notice that the markup can be a combination of Visualforce and HTML tags, just like other Visualforce pages.
For a more complex example, you could use a custom component to create a form that is used across multiple Visualforce pages. Create
a new custom component named recordDisplay and copy the following code:
<apex:component>
<apex:attribute name="record" description="The type of record we are viewing."
type="Object" required="true"/>
<apex:pageBlock title="Viewing {!record}">
<apex:detail />
</apex:pageBlock>
</apex:component>

Next, create a page called displayRecords and use the following code:
<apex:page >
<c:recordDisplay record="Account" />
</apex:page>

For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if
001D000000IRt53 is the account ID, the resulting URL should be:
[Link]

You should see a page with details about the account you passed in as an ID.
Now, replace the code in displayRecords with the following sample:
<apex:page>
<c:recordDisplay record="Contact" />
</apex:page>

Again, pass in the ID of a contact before refreshing the page. You should see the page display information about your Contact.
Custom Component Attributes contains more information on using the <apex:attribute> component.

Using Custom Components in a Visualforce Page


The body of an <apex:component> tag is the markup that is added to a standard Visualforce page whenever the component is
included. For example, the following Visualforce page uses the component defined in Custom Component Markup on page 150 (in this
example, the component was saved with the name myComponent):
<apex:page standardController="Account">
This is my <i>page</i>. <br/>

150

Creating and Using Custom Components

Managing Version Settings for Custom Components

<c:myComponent/>
</apex:page>

It results in the following output:


This is my page.
This is my custom component.

To use a custom component in a Visualforce page you must prefix the component's name with the namespace in which the component
was defined. For example, if a component named myComponent is defined in a namespace called myNS, the component can be
referenced in a Visualforce page as <myNS:myComponent>.
For ease of use, a component that is defined in the same namespace as an associated page can also use the c namespace prefix.
Consequently, if the page and component from the sample above are defined in the same namespace, you can reference the component
as <c:myComponent>.
If you want to insert content into a custom component, use the <apex:componentBody> tag.
SEE ALSO:
What are Custom Components?
Defining Custom Components

Managing Version Settings for Custom Components


To set the Salesforce API and Visualforce version for a Visualforce page or custom component:
1. Edit a Visualforce page or component and click Version Settings.
Note: You can only modify the version settings for a page or custom component on the Version Settings tab when editing
the page or component in Setup.
2. Select the Version of the Salesforce API. This is also the version of Visualforce used with the page or component.
3. Click Save.
SEE ALSO:
How is Visualforce Versioned?
Managing Package Version Settings for Visualforce Pages and Components

Custom Component Attributes


Apart from standard Visualforce markup, the body of an <apex:component> tag can also specify the attributes that can be passed
in to the custom component when its used in a Visualforce page. The values of such attributes can then be used directly in the component,
or within the components controller, if applicable.
Attributes are defined with the <apex:attribute> tag. For example, the following custom component definition specifies two
required attributes named value and borderColor. Values for these attributes are referenced in the custom component definition
using standard {! } Visualforce expression language syntax:
<apex:component>
<!-- Attribute Definitions -->

151

Creating and Using Custom Components

Custom Component Attributes

<apex:attribute name="myValue" description="This is the value for the component."


type="String" required="true"/>
<apex:attribute name="borderColor" description="This is color for the border."
type="String" required="true"/>
<!-- Component Definition -->
<h1 style="border:{!borderColor};"/>
<apex:outputText value="{!myValue}"/>
</h1>
</apex:component>

Use this component in a Visualforce page with the following markup:


<c:myComponent myValue="My value" borderColor="red"/>

An <apex:attribute> tag requires values for the name, description, and type attributes:
The name attribute defines how the custom attribute can be referenced in Visualforce pages. names for attributes must be unique
within a component.
The description attribute defines the help text for the attribute that appears in the component reference library once the
custom component has been saved. The custom component is listed in the reference library with the standard components that
are also available.
The type attribute defines the Apex data type of the attribute. Only the following data types are allowed as values for the type
attribute:
Primitives, such as String, Integer, or Boolean.
sObjects, such as Account, My_Custom_Object__c, or the generic sObject type.
One-dimensional lists, specified using array-notation, such as String[], or Contact[].
Maps, specified using type="map". You dont need to specify the maps specific data type.
Custom Apex classes.
For information on additional <apex:attribute> attributes, see apex:attribute on page 362.

Default Custom Component Attributes


Two attributes are always generated for custom components. These attributes dont need to be included in your component definition:
id

An identifier that allows the custom component to be referenced by other components in the page. If not specified, a unique identifier
is generated automatically.
rendered

A Boolean value that specifies whether the custom component is rendered on the page. If not specified, this value defaults to true.
SEE ALSO:
Best Practices for Accessing Component IDs

152

Creating and Using Custom Components

Custom Component Controllers

Custom Component Controllers


Similar to standard Visualforce pages, custom components can be associated with a controller written in Apex. This association is made
by setting the controller attribute on the component to your custom controller. You can use the controller to perform additional
logic before returning the component's markup to the associated page.

Accessing Custom Component Attributes in a Controller


To access the value of a custom component attribute in an associated custom component controller:
1. Define a property in the custom component controller to store the value of the attribute.
2. Define a getter and setter method for the property. For example:
public class myComponentController {
public String controllerValue;
public void setControllerValue (String s) {
controllerValue = [Link]();
}
public String getControllerValue() {
return controllerValue;
}
}

Notice that the setter modifies the value.


3. In the <apex:attribute> tag in your component definition, use the assignTo attribute to bind the attribute to the class
variable you just defined. For example:
<apex:component controller="myComponentController">
<apex:attribute name="componentValue" description="Attribute on the component."
type="String" required="required" assignTo="{!controllerValue}"/>
<apex:pageBlock title="My Custom Component">
<p>
<code>componentValue</code> is "{!componentValue}"
<br/>
<code>controllerValue</code> is "{!controllerValue}"
</p>
</apex:pageBlock>
Notice that the controllerValue has been upper cased using an Apex method.
</apex:component>

Note that when using the assignTo attribute, getter and setter methods, or a property with get and set values, must be
defined.
4. Add the component to a page. For example,
<apex:page>
<c:simpleComponent componentValue="Hi there, {!$[Link]}"/>
</apex:page>

The output of the page will look something like the following:

153

Creating and Using Custom Components

Custom Component Controllers

Notice that the Apex controller method changes controllerValue so that it is displayed with uppercase characters.

154

CHAPTER 12 Dynamic Visualforce Bindings


Dynamic Visualforce bindings are a way of writing generic Visualforce pages that display information about records without necessarily
knowing which fields to show. In other words, fields on the page are determined at run time, rather than compile time. This allows a
developer to design a single page that renders differently for various audiences, based on their permissions or preferences. Dynamic
bindings are useful for Visualforce pages included in managed packages since they allow for the presentation of data specific to each
subscriber with very little coding.
Dynamic Visualforce binding is supported for standard and custom objects. Dynamic bindings take the following general form:
reference[expression]

where
reference evaluates to either an sObject, an Apex class, or a global variable
expression evaluates to a string that is the name of a field, or a related object. If a related object is returned, it can be used to
recursively select fields or further related objects.
Dynamic bindings can be used anywhere formula expressions are valid. Use them on a page like this:
{!reference[expression]}

Optionally, you can add a fieldname to the end of the whole dynamic expression. If the dynamic expression resolves to an sObject,
the fieldname refers to a specific field on that object. If your reference is an Apex class, the field must be public or global.
For example:
{!myContact['Account'][fieldname]}

Your dynamic Visualforce pages should be designed to use a standard controller for the object on your page, and implement any further
customization through a controller extension.
You can use the Apex [Link] methods to get information for your dynamic references, in particular those that
access the fields of an object. For example, [Link]() returns a Map of the
names of the Account fields in a format that your Apex controllers and extensions can understand.
Important: Static references are checked for validity when you save a page, and an invalid reference will prevent you from saving
it. Dynamic references, by their nature, can only be checked at run time, and if your page contains a dynamic reference that is
invalid when the page is viewed, the page fails. Its possible to create references to custom fields or global variables which are
valid, but if that field or global value is later deleted, the page will fail when it is next viewed.

Defining Relationships
Both reference and expression can be complex expressions, such as those that evaluate to object relationships. For example,
suppose that an object called Object1__c has a relationship to another object called Object2__c. The name of the relationship between
these two objects is called Relationship__r.
If Object2__c has a field called myField, then the following dynamically-cast lookups all return a reference to the same field:

155

Dynamic Visualforce Bindings

Using Dynamic References with Standard Objects

Object1__c.Object2__c['myField']
Object1__c['Object2__c.myField']
Object1__c['Object2__c']['myField']
Object1__c.Relationship__r[myField]
Object1__c[Relationship__r.myField]
Object1__c[Relationship__r][myField]
SEE ALSO:
Dynamic References to Global Variables
Global Variables

Using Dynamic References with Standard Objects


Use dynamic Visualforce bindings to construct simple, reusable pages with a known set of fields you want to access. This approach has
the advantage of easily customizing which fields are pertinent for a user to work with.
The next two examples are deliberately simple for instructional purposes. See Using Dynamic References for a User-Customizable Page
for a more advanced example that makes fuller use of dynamic Visualforce.

A Simple Dynamic Form


The following example demonstrates the simplest way to construct a Visualforce page that uses dynamic references.
First, create a controller extension that provides a dynamic list of fields to display:
public class DynamicAccountFieldsLister {
public DynamicAccountFieldsLister([Link] controller) {
[Link](editableFields);
}
public List<String> editableFields {
get {
if (editableFields == null) {
editableFields = new List<String>();
[Link]('Industry');
[Link]('AnnualRevenue');
[Link]('BillingCity');
}
return editableFields ;
}
private set;
}
}

Next, create a page called DynamicAccountEditor that uses the above controller extension:
<apex:page standardController="Account"
extensions="DynamicAccountFieldsLister">
<apex:pageMessages /><br/>

156

Dynamic Visualforce Bindings

Using Dynamic References with Standard Objects

<apex:form>
<apex:pageBlock title="Edit Account" mode="edit">
<apex:pageBlockSection columns="1">
<apex:inputField value="{![Link]}"/>
<apex:repeat value="{!editableFields}" var="f">
<apex:inputField value="{!Account[f]}"/>
</apex:repeat>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Notice whats going on in this sample:


The DynamicAccountFieldsLister controller extension creates a list of strings called editableFields. Each string
maps to a field name in the Account object.
The editableFields list is hard-coded, but you can determine them from a query or calculation, read them from a custom
setting, or otherwise providing a more dynamic experience. This is what makes dynamic references powerful.
DynamicAccountEditor markup uses an <apex:repeat> tag to loop through the strings returned by
editableFields.
The <apex:inputField> tag displays each field in editableFields by referencing the f iteration element, which
represents the name of a field on Account. The dynamic reference {!Account[f]} actually displays the value on the page.

Ensuring that Fields in Dynamic References are Loaded by a Standard


Controller
Visualforce automatically optimizes the SOQL query performed by a pages StandardController (or
StandardSetController), loading only the fields which are actually used on a page. When you create a Visualforce page with
static references to objects and fields, the fields and objects can be known in advance. When the page is saved, Visualforce is able to
determine and save which objects and fields need to be added to the SOQL query that the StandardController will perform
later, when the page is requested.
Dynamic references are evaluated at runtime, after the SOQL query is run by the StandardController. If a field is only used via
a dynamic reference, it wont be automatically loaded. When that dynamic reference is later evaluated, it will resolve to data which is
missing, the result of which is a SOQL error. You must provide some extra information to the controller, so that it knows what fields and
related objects to load.
You can add any number of additional fields to a StandardController query, by using the addFields() method on the
page controller to pass in the list of additional fields to load. In the prior example, this is done in the controller extensions constructor:
public DynamicAccountFieldsLister([Link] controller) {
[Link](editableFields);
}

The constructor uses the same property that the page markup does, editableFields, to add more fields to the controllers list of
fields to load.
This works well for pages when the complete list of fields to load can be known when the controller extension is instantiated. If the list
of fields cant be determined until later in the request processing, you can call reset() on the controller and then add the fields. This
will cause the controller to send the revised query. Using Dynamic References for a User-Customizable Page provides an example of this
technique.

157

Dynamic Visualforce Bindings

Using Dynamic References with Standard Objects

Note: Adding fields to a controller is only required if youre using the default query for a StandardController or
StandardSetController. If your controller or controller extension performs its own SOQL query, using addFields()
is unnecessary and has no effect.
For more information on these methods, see the StandardController documentation.

Dynamic References to Related Objects


This example creates a Visualforce page for a case record, with certain fields that are editable. Some of the fields displayed are from a
related object, showing how you can use dynamic references to traverse relationships.
First, create an Apex controller extension called DynamicCaseLoader:
public class DynamicCaseLoader {
public final Case caseDetails { get; private set; }
// SOQL query loads the case, with Case fields and related Contact fields
public DynamicCaseLoader([Link] controller) {
String qid = [Link]().getParameters().get('id');
String theQuery = 'SELECT Id, ' + joinList(caseFieldList, ', ') +
' FROM Case WHERE Id = :qid';
[Link] = [Link](theQuery);
}
// A list of fields to show on the Visualforce page
public List<String> caseFieldList {
get {
if (caseFieldList == null) {
caseFieldList = new List<String>();
[Link]('CaseNumber');
[Link]('Origin');
[Link]('Status');
[Link]('[Link]'); // related field
[Link]('[Link]'); // related field
[Link]('[Link]'); // related field
}
return caseFieldList;
}
private set;
}
// Join an Apex list of fields into a SELECT fields list string
private static String joinList(List<String> theList, String separator) {
if (theList == null) {
return null;
}
if (separator == null) {
separator = '';
}
String joined = '';
Boolean firstItem = true;

158

Dynamic Visualforce Bindings

Using Dynamic References with Standard Objects

for (String item : theList) {


if(null != item) {
if(firstItem){
firstItem = false;
}
else {
joined += separator;
}
joined += item;
}
}
return joined;
}
}

The corresponding page, DynamicCaseEditor, uses this extension to retrieve information about a particular case and its associated
contact:
<apex:page standardController="Case" extensions="DynamicCaseLoader">
<br/>
<apex:form >
<apex:repeat value="{!caseFieldList}" var="cf">
<h2>{!cf}</h2>
<br/>
<!-- The only editable information should be contact information -->
<apex:inputText value="{!caseDetails[cf]}"
rendered="{!IF(contains(cf, "Contact"), true, false)}"/>
<apex:outputText value="{!caseDetails[cf]}"
rendered="{!IF(contains(cf, "Contact"), false, true)}"/>
<br/><br/>
</apex:repeat>
</apex:form>
</apex:page>

Access this page with the ID of a valid case record specified as the id query parameter. For example,
[Link] Your page will display a

form similar to this one:

There are a number of things to note about this example:

159

Dynamic Visualforce Bindings

Using Dynamic References with Standard Objects

In the controller extension, the constructor performs its own SOQL query for the object to display. Here its because the pages
StandardController doesnt load related fields by default, but there are many different use cases for needing a customized
SOQL query. The query result is made available to the page through the property caseFieldList. Theres no requirement to
perform the query in the constructorit can just as easily be in the propertys get method.
The SOQL query specifies the fields to load, so its not necessary to use addFields() which was needed in A Simple Dynamic
Form.
The SOQL query is constructed at run time. A utility method converts the list of field names into a string suitable for use in a SOQL
SELECT statement.
In the markup, the form fields are displayed by iterating through the field names using <apex:repeat>, and using the field
name variable cf in a dynamic reference to get the field value. Each field is potentially written by two
components<apex:outputText> and <apex:inputText>. The render attribute on these tags controls which of the
two actually displays: if the field name contains the string Contact, then the information is rendered in an <apex:inputText>
tag, and if it doesnt, its rendered in an <apex:outputText>.

Using Dynamic References for a User-Customizable Page


The full potential of Visualforce dynamic bindings is in building pages without knowing which fields are available on an object. The
following example demonstrates this capability with a list of accounts that can be customized without knowing any of the fields on the
Account object, except for the Name field required on all objects. This is made possible by using the
[Link]() to retrieve the list of fields that exist on the object, and Visualforce
dynamic references.
The functionality provided by this example is simple. The main list view initially displays only the account name, but a Customize List
button allows the user to select which fields theyd like to add to the list. When they save their preferences, they return to the list view
and will see a dynamically generated Visualforce page that presents those fields in additional columns.
Note: You can also build a page without knowing the fields using dynamic references with Field Sets on page 170.
First, create a controller extension called DynamicCustomizableListHandler:
public class DynamicCustomizableListHandler {
// Resources we need to hold on to across requests
private [Link] controller;
private PageReference savePage;
// This
private
private
private

is the state for the list "app"


Set<String> unSelectedNames = new Set<String>();
Set<String> selectedNames = new Set<String>();
Set<String> inaccessibleNames = new Set<String>();

public DynamicCustomizableListHandler([Link] controller) {


[Link] = controller;
loadFieldsWithVisibility();
}
// Initial load of the fields lists
private void loadFieldsWithVisibility() {
Map<String, [Link]> fields =
[Link]();
for (String s : [Link]()) {
if (s != 'Name') { // name is always displayed

160

Dynamic Visualforce Bindings

Using Dynamic References with Standard Objects

[Link](s);
}
if (![Link](s).getDescribe().isAccessible()) {
[Link](s);
}
}
}
// The fields to show in the list
// This is what we generate the dynamic references from
public List<String> getDisplayFields() {
List<String> displayFields = new List<String>(selectedNames);
[Link]();
return displayFields;
}
// Nav: go to customize screen
public PageReference customize() {
savePage = [Link]();
return [Link];
}
// Nav: return to list view
public PageReference show() {
// This forces a re-query with the new fields list
[Link]();
[Link](getDisplayFields());
return savePage;
}
// Create the select options for the two select lists on the page
public List<SelectOption> getSelectedOptions() {
return selectOptionsFromSet(selectedNames);
}
public List<SelectOption> getUnSelectedOptions() {
return selectOptionsFromSet(unSelectedNames);
}
private List<SelectOption> selectOptionsFromSet(Set<String> opts) {
List<String> optionsList = new List<String>(opts);
[Link]();
List<SelectOption> options = new List<SelectOption>();
for (String s : optionsList) {
[Link](new
SelectOption(s, decorateName(s), [Link](s)));
}
return options;
}
private String decorateName(String s) {
return [Link](s) ? '*' + s : s;
}
// These properties receive the customization form postback data

161

Dynamic Visualforce Bindings

Using Dynamic References with Standard Objects

// Each time the [<<] or [>>] button is clicked, these get the contents
// of the respective selection lists from the form
public transient List<String> selected
{ get; set; }
public transient List<String> unselected { get; set; }
// Handle the actual button clicks. Page gets updated via a
// rerender on the form
public void doAdd() {
moveFields(selected, selectedNames, unSelectedNames);
}
public void doRemove() {
moveFields(unselected, unSelectedNames, selectedNames);
}
private void moveFields(List<String> items,
Set<String> moveTo, Set<String> removeFrom) {
for (String s: items) {
if( ! [Link](s)) {
[Link](s);
[Link](s);
}
}
}
}

Note: When you save the class, you may be prompted about a missing Visualforce page. This is because of the page reference
in the customize() method. Click the quick fix link to create the pageVisualforce markup from a later block of code will
be pasted into it.
Some things to note about this class:
The standard controller methods addFields() and reset() are used in the show() method, which is the method that
returns back to the list view. They are necessary because the list of fields to display may have changed, and so the query that loads
data for display needs to be re-executed.
Two action methods, customize() and show(), navigate from the list view to the customization form and back again.
Everything after the navigation action methods deals with the customization form. These methods are broadly broken into two
groups, noted in the comments. The first group provides the List<SelectOption> lists used by the customization form, and
the second group handles the two buttons that move items from one list to the other.
Now, create a Visualforce page called DynamicCustomizableList with the following markup:
<apex:page standardController="Account" recordSetVar="accountList"
extensions="DynamicCustomizableListHandler">
<br/>
<apex:form >
<!-- View selection widget, uses StandardController methods -->
<apex:pageBlock>
<apex:outputLabel value="Select Accounts View: " for="viewsList"/>
<apex:selectList id="viewsList" size="1" value="{!filterId}">
<apex:actionSupport event="onchange" rerender="theTable"/>
<apex:selectOptions value="{!listViewOptions}"/>
</apex:selectList>
</apex:pageblock>

162

Dynamic Visualforce Bindings

Using Dynamic References with Standard Objects

<!-- This list of accounts has customizable columns -->


<apex:pageBlock title="Accounts" mode="edit">
<apex:pageMessages />
<apex:panelGroup id="theTable">
<apex:pageBlockTable value="{!accountList}" var="acct">
<apex:column value="{![Link]}"/>
<!-- This is the dynamic reference part -->
<apex:repeat value="{!displayFields}" var="f">
<apex:column value="{!acct[f]}"/>
</apex:repeat>
</apex:pageBlockTable>
</apex:panelGroup>
</apex:pageBlock>
<br/>
<apex:commandButton value="Customize List" action="{!customize}"/>
</apex:form>
</apex:page>

This page presents a list of accounts in your organization. The <apex:pageBlock> at the top provides a standard drop-down list
of the views defined for accounts, the same views users see on standard Salesforce account pages. This view widget uses methods
provided by the StandardSetController.
The second <apex:pageBlock> holds a <apex:pageBlockTable> that has columns added in a <apex:repeat>. All
columns in the repeat component use a dynamic reference to account fields, {!acct[f]}, to display the users custom-selected
fields.
The last piece to this mini app is the customization form. Create a page called CustomizeDynamicList. You may have already
created this page, when creating the controller extension. Paste in the following:
<apex:page standardController="Account" recordSetVar="ignored"
extensions="DynamicCustomizableListHandler">
<br/>
<apex:form >
<apex:pageBlock title="Select Fields to Display" id="selectionBlock">
<apex:pageMessages />
<apex:panelGrid columns="3">
<apex:selectList id="unselected_list" required="false"
value="{!selected}" multiselect="true" size="20" style="width:250px">
<apex:selectOptions value="{!unSelectedOptions}"/>
</apex:selectList>
<apex:panelGroup >
<apex:commandButton value=">>"
action="{!doAdd}" rerender="selectionBlock"/>
<br/>
<apex:commandButton value="<<"
action="{!doRemove}" rerender="selectionBlock"/>
</apex:panelGroup>
<apex:selectList id="selected_list" required="false"
value="{!unselected}" multiselect="true" size="20" style="width:250px">
<apex:selectOptions value="{!selectedOptions}"/>
</apex:selectList>
</apex:panelGrid>

163

Dynamic Visualforce Bindings

Using Dynamic References with Standard Objects

<em>Note: Fields marked <strong>*</strong> are inaccessible to your account</em>


</apex:pageBlock>
<br/>
<apex:commandButton value="Show These Fields" action="{!show}"/>
</apex:form>
</apex:page>

This simple preferences page presents two lists, and the user moves fields from the list of available fields on the left to the list of fields
to display on the right. Clicking Show These Fields returns to the list itself.
Here are a few things to note about this markup:
This page uses the same standard controller as the list view, even though no accounts are being displayed. This is required to maintain
the view state, which contains the list of fields to display. If this form saved the users preferences to something permanent, like a
custom setting, this wouldnt be necessary.
The first list is populated by a call to the getUnSelectedOptions() method, and when the form is submitted (via either of
the two <apex:commandButton> components), the values in the list that are selected at time of form submission are saved
into the selected property. Corresponding code handles the other list.
These delta lists of fields to move are processed by the doAdd() or doRemove() method, depending on which button was
clicked.
When you assemble the controller extension and these pages, and navigate to /apex/DynamicCustomizableList in your
organization, youll see a sequence similar to the following:
1. View the customizable list in the default state, with only the account name field displayed.

Click Customize List.


2. The display preferences screen is shown.

164

Dynamic Visualforce Bindings

Using Dynamic References with Custom Objects and


Packages

Move some fields into the list on the right, and click Show These Fields.
3. The customized list view is displayed.

Using Dynamic References with Custom Objects and Packages


Package developers can use dynamic Visualforce binding to list only the fields a user can access. This situation might occur when youre
developing a managed package with a Visualforce page that displays fields on an object. Since the package developer doesnt know
which fields a subscriber can access, he or she can define a dynamic page that renders differently for each subscriber. The following
example uses a custom object packaged with a page layout using a Visualforce page to demonstrate how different subscribing users
view the same page.
1. Create a custom object called Book with the following fields and data types:
Title: Text(255)
Author: Text(255)
ISBN: Text(13)
Price: Currency(4, 2)
Publisher: Text(255)
By default creating a new custom object will create a layout for that object. Call the layout Book Layout.

165

Dynamic Visualforce Bindings

Using Dynamic References with Custom Objects and


Packages

2. Modify the layout so it displays the custom fields above and removes the standard fields such as Created By, Last Modified By, Owner,
and Name.
3. Create a new custom object tab. Set the object to Book, and the tab style to Books.
4. Switch to the Book tab and create a few Book objects. For this tutorial, the data inside the fields doesnt actually matter.
5. Create a controller extension called bookExtension with the following code:
public with sharing class bookExtension {
private [Link] controller;
private Set<String> bookFields = new Set<String>();
public bookExtension ([Link] controller) {
[Link] = controller;
Map<String, [Link]> fields =
[Link].Book__c.[Link]();
for (String s : [Link]()) {
// Only include accessible fields
if ([Link](s).getDescribe().isAccessible() &&
[Link](s).getDescribe().isCustom()) {
[Link](s);
}
}
}
public List<String> availableFields {
get {
[Link]();
[Link](new List<String>(bookFields));
return new List<String>(bookFields);
}
}
}

6. Create a Visualforce page called booksView that uses the controller extension to show the values of the Book object:
<apex:page standardController="Book__c" extensions="bookExtension" >
<br/>
<apex:pageBlock title="{!Book__c.Name}">
<apex:repeat value="{!availableFields}" var="field">
<h2><apex:outputText
value="{!$ObjectType['Book__c'].Fields[field].Label}"/></h2>
<br/>
<apex:outputText value="{!Book__c[field]}" /><br/><br/>
</apex:repeat>
</apex:pageBlock>
</apex:page>

166

Dynamic Visualforce Bindings

Using Dynamic References with Custom Objects and


Packages

7. Since the controller extension is going to be packaged, youll need to create a test for the Apex class. Create an Apex class called
bookExtensionTest with this basic code to get you started:
public with sharing class bookExtension {
private [Link] controller;
private Set<String> bookFields = new Set<String>();
public bookExtension ([Link] controller) {
[Link] = controller;
Map<String, [Link]> fields =
[Link].Book__c.[Link]();
for (String s : [Link]()) {
// Only include accessible fields
if ([Link](s).getDescribe().isAccessible() &&
[Link](s).getDescribe().isCustom()) {
[Link](s);
}
}
[Link](new List<String>(bookFields));
}
public List<String> availableFields {
get {
[Link]();
[Link](new List<String>(bookFields));
return new List<String>(bookFields);
}
}
}

Note: This Apex test is only meant to be a sample. When creating tests that are included into packages, validate all behavior,
including positive and negative results.
8. Create a package called bookBundle, and add the custom object, the Visualforce page, and the bookExtensionTest Apex
class. The other referenced elements are included automatically.
9. Install the bookBundle package into a subscriber organization.
10. After the package is installed, from the object management settings for books, add a new field called Rating.
11. Create a new Book object. Again, the values for the record dont actually matter.
12. Navigate to the booksView page with the package namespace and book ID appended to the URL. For example, if GBOOK is the
namespace, and a00D0000008e7t4 is the book ID, the resulting URL should be
[Link]
When the page is viewed from the subscribing organization, it should include all the packaged Book fields, plus the newly created Rating
field. Different users and organizations can continue to add whatever fields they want, and the dynamic Visualforce page will adapt and
show as appropriate.
SEE ALSO:
Salesforce Help: Find Object Management Settings

167

Dynamic Visualforce Bindings

Referencing Apex Maps and Lists

Referencing Apex Maps and Lists


Visualforce pages that use dynamic bindings can reference the Apex Map and List data types in their markup.
For example, if an Apex List is defined as follows:
public List<String> people {
get {
return new List<String>{'Winston', 'Julia', 'Brien'};
}
set;
}
public List<Integer> iter {
get {
return new List<Integer>{0, 1, 2};
}
set;
}

It can be accessed in a Visualforce page like this:


<apex:repeat value="{!iter}" var="pos">
<apex:outputText value="{!people[pos]}" /><br/>
</apex:repeat>

Similarly, if you have the following Apex Map:


public Map<String,String> directors {
get {
return new Map<String, String> {
'Kieslowski' => 'Poland',
'del Toro' => 'Mexico',
'Gondry' => 'France'
};
}
set;
}

Your Visualforce page can show the values like this:


<apex:repeat value="{!directors}" var="dirKey">
<apex:outputText value="{!dirKey}" /> -<apex:outputText value="{!directors[dirKey]}" /><br/>
</apex:repeat>

Use dynamic references to lists and maps in an <apex:inputText> tag to create forms using data that isnt in your organizations
custom objects. Working with a single map can be much simpler than creating a series of instance variables in an Apex controller or
creating a custom object just for the form data.
Heres a Visualforce page that uses a map to hold form data for processing by a custom controller:
<apex:page controller="ListsMapsController">
<apex:outputPanel id="box" layout="block">
<apex:pageMessages/>
<apex:form >

168

Dynamic Visualforce Bindings

Referencing Apex Maps and Lists

<apex:repeat value="{!inputFields}" var="fieldKey">


<apex:outputText value="{!fieldKey}"/>:
<apex:inputText value="{!inputFields[fieldKey]}"/><br/>
</apex:repeat>
<apex:commandButton action="{!submitFieldData}"
value="Submit" id="button" rerender="box"/>
</apex:form>
</apex:outputPanel>
</apex:page>

And heres a simple controller that works with the form:


public class ListsMapsController {
public Map<String, String> inputFields { get; set; }
public ListsMapsController() {
inputFields = new Map<String, String> {
'firstName' => 'Jonny', 'lastName' => 'Appleseed', 'age' => '42' };
}
public PageReference submitFieldData() {
doSomethingInterestingWithInput();
return null;
}
public void doSomethingInterestingWithInput() {
[Link]('age', ([Link]([Link]('age')) + 10).format());
}
}

A Map can contain references to sObjects or sObject fields. To update those items, reference a field name in the input field:
public with sharing class MapAccCont {
Map<Integer, Account> mapToAccount = new Map<Integer, Account>();
public MapAccCont() {
Integer i = 0;
for (Account a : [SELECT Id, Name FROM Account LIMIT 10]) {
[Link](i, a);
i++;
}
}
public Map<Integer, Account> getMapToAccount() {
return mapToAccount;
}
}
<apex:page controller="MapAccCont">
<apex:form>
<apex:repeat value="{!mapToAccount}" var="accNum">

169

Dynamic Visualforce Bindings

Working with Field Sets

<apex:inputField value="{!mapToAccount[accNum].Name}" />


</apex:repeat>
</apex:form>
</apex:page>

Unresolved Dynamic References


Keep in mind the following issues that can arise at run time if a dynamic reference doesnt resolve:
If there isnt a value mapped to a particular key, the Visualforce page returns an error message. For example, with this controller:
public class ToolController {
public Map<String, String> toolMap { get; set; }
public String myKey { get; set; }
public ToolController() {
Map<String, String> toolsMap = new Map<String, String>();
[Link]('Stapler', 'Keeps things organized');
}
}

This page causes an error at run time:


<apex:page controller="ToolController">
<!-- This renders an error on the page -->
<apex:outputText value="{!toolMap['Paperclip']}" />
</apex:page>

If the key is null, the Visualforce page renders an empty string. For example, using the same controller as above, this page shows
an empty space:
<apex:page controller="ToolController">
<!-- This renders a blank space -->
<apex:outputText value="{!toolMap[null]}" />
</apex:page>

Working with Field Sets


You can use dynamic bindings to display field sets on your Visualforce pages. A field set is a grouping of fields. For example, you could
have a field set that contains fields describing a user's first name, middle name, last name, and business title. If the page is added to a
managed package, administrators can add, remove, or reorder fields in a field set to modify the fields presented on the Visualforce page
without modifying any code. Field sets are available for Visualforce pages on API version 21.0 or above. You can have up to 50 field sets
referenced on a single page.

170

Dynamic Visualforce Bindings

Working with Field Sets

Working with Field Sets Using Visualforce


Field sets can be directly referenced in Visualforce by combining the $ObjectType global variable with the keyword FieldSets.
For example, if your Contact object has a field set called properNames that displays three fields, your Visualforce page can reference
the field data through the following iteration:
<apex:page standardController="Contact">
<apex:repeat value="{!$[Link]}" var="f">
<apex:outputText value="{!Contact[f]}" /><br/>
</apex:repeat>
</apex:page>

You can also choose to render additional information, such as field labels and data types, through the following special properties on
the fields in the field set:
Property Name

Description

DBRequired

Indicates whether the field is required for the object

FieldPath

Lists the fields spanning info

Label

The UI label for the field

Required

Indicates whether the field is required in the field set

Type

The data type for the field

For example, you can access the labels and data types for the fields in properNames like this:
<apex:page standardController="Contact">
<apex:pageBlock title="Fields in Proper Names">
<apex:pageBlockTable value="{!$[Link]}" var="f">
<apex:column value="{!f}">
<apex:facet name="header">Name</apex:facet>
</apex:column>
<apex:column value="{![Link]}">
<apex:facet name="header">Label</apex:facet>
</apex:column>
<apex:column value="{![Link]}" >
<apex:facet name="header">Data Type</apex:facet>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>

If this Visualforce page is added to a managed package and distributed, subscribers can edit the properNames field set. The logic
for generating the Visualforce page remains the same, while the presentation differs based on each subscribers implementation. To
reference a field set from a managed package, you must prepend the field set with the organizations namespace. Using the markup
above, if properNames comes from an organization called Spectre, the field set is referenced like this:
{!$[Link].Spectre__properNames}

171

Dynamic Visualforce Bindings

Working with Field Sets

Working with Field Sets Using Apex


Fields in a field set are automatically loaded when your Visualforce page uses a standard controller. When using a custom controller,
you need to add the required fields to the SOQL query for the page. Apex provides two Schema objects that allow you to discover field
sets and the fields they contain, [Link] and [Link]. For information about these two system
classes, see FieldSet Class in the [Link] Apex Code Developer's Guide.
Sample: Displaying a Field Set on a Visualforce Page
This sample uses [Link] and [Link] methods to dynamically get all the fields in the
Dimensions field set for the Merchandise custom object. The list of fields is then used to construct a SOQL query that ensures those fields
are available for display. The Visualforce page uses the MerchandiseDetails class as its controller.
public class MerchandiseDetails {
public Merchandise__c merch { get; set; }
public MerchandiseDetails() {
[Link] = getMerchandise();
}
public List<[Link]> getFields() {
return SObjectType.Merchandise__c.[Link]();
}
private Merchandise__c getMerchandise() {
String query = 'SELECT ';
for([Link] f : [Link]()) {
query += [Link]() + ', ';
}
query += 'Id, Name FROM Merchandise__c LIMIT 1';
return [Link](query);
}
}

The Visualforce page using the above controller is simple:


<apex:page controller="MerchandiseDetails">
<apex:form >
<apex:pageBlock title="Product Details">
<apex:pageBlockSection title="Product">
<apex:inputField value="{![Link]}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Dimensions">
<apex:repeat value="{!fields}" var="f">
<apex:inputField value="{!merch[[Link]]}"
required="{!OR([Link], [Link])}"/>
</apex:repeat>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

172

Dynamic Visualforce Bindings

Dynamic References to Global Variables

One thing to note about the above markup is the expression used to determine if a field on the form should be indicated as being a
required field. A field in a field set can be required by either the field set definition, or the fields own definition. The expression handles
both cases.

Field Set Considerations


Fields added to a field set can be in one of two categories:
If a field is marked as Available for the Field Set, it exists in the field set, but the developer hasnt presented it on
the packaged Visualforce page. Administrators can display the field after the field set is deployed by moving it from the Available
column to the In the Field Set column.
If a field is marked as In the Field Set, the developer has rendered the field on the packaged Visualforce page by default.
Administrators can remove the field from the page after the field set is deployed by removing it from the In the Field Set
column.
The order in which a developer lists displayed fields determines their order of appearance on a Visualforce page.
As a package developer, keep the following best practices in mind:
Subscribers with installed field sets can add fields that your page didnt account for. There is no way to conditionally omit some fields
from a field set iteration, so make sure that any field rendered through your field set works for all field types.
We recommend that you add only non-essential fields to your field set. This ensures that even if a subscriber removes all fields in
the field set, Visualforce pages that use that field set still function.
Note: Field sets are available for Visualforce pages on API version 21.0 or above.

SEE ALSO:
$FieldSet
Object Schema Details Available Using $ObjectType

Dynamic References to Global Variables


Visualforce pages can use dynamic bindings to reference global variables in their markup. Global variables allow you to access information
about the current user, your organization, and schema details about your data. The list of global variables is available in the Global
Variables, Functions, and Expression Operators appendix.
Referencing a global variable is the same as referencing sObjects and Apex classesyou use the same basic pattern, where reference
is a global variable:
reference[expression]

SEE ALSO:
Global Variables

Dynamic References to Static Resources Using $Resource


Dynamic references to static resources can be very useful for providing support for themes or other visual preferences.

173

Dynamic Visualforce Bindings

Dynamic References to Static Resources Using $Resource

To reference a static resource using the $Resource global variable, provide the name of the static resource in an expression: {!
$Resource[StaticResourceName] }. For example, if you have a getCustomLogo method that returns the name of an image
uploaded as a static resource, reference it like this: <apex:image value="{!$Resource[customLogo]}"/>.
This example illustrates how to switch between two different visual themes. First, create a controller extension named ThemeHandler
with the following code:
public class ThemeHandler {
public ThemeHandler([Link] controller) { }
public static Set<String> getAvailableThemes() {
// You must have at least one uploaded static resource
// or this code will fail. List their names here.
return(new Set<String> {'Theme_Color', 'Theme_BW'});
}
public static List<SelectOption> getThemeOptions() {
List<SelectOption> themeOptions = new List<SelectOption>();
for(String themeName : getAvailableThemes()) {
[Link](new SelectOption(themeName, themeName));
}
return themeOptions;
}
public String selectedTheme {
get {
if(null == selectedTheme) {
// Ensure we always have a theme
List<String> themeList = new List<String>();
[Link](getAvailableThemes());
selectedTheme = themeList[0];
}
return selectedTheme;
}
set {
if(getAvailableThemes().contains(value)) {
selectedTheme = value;
}
}
}
}

Notes about this class:


It has an empty constructor, because theres no default constructor for controller extensions.
Add the name of your uploaded static resource files theme to the getAvailableThemes method. Using Static Resources on
page 145 provides details of how to create and upload static resources, in particular, zipped archives containing multiple files.
The last two methods provide the list of themes and the selected theme for use in the Visualforce form components.
Now create a Visualforce page that uses this controller extension:
<apex:page standardController="Account"
extensions="ThemeHandler" showHeader="false">
<apex:form >

174

Dynamic Visualforce Bindings

Dynamic References to Static Resources Using $Resource

<apex:pageBlock id="ThemePreview" >


<apex:stylesheet
value="{!URLFOR($Resource[selectedTheme], 'styles/[Link]')}"/>
<h1>Theme Viewer</h1>
<p>You can select a theme to use while browsing this site.</p>
<apex:pageBlockSection >
<apex:outputLabel value="Select Theme: " for="themesList"/>
<apex:selectList id="themesList" size="1" value="{!selectedTheme}">
<apex:actionSupport event="onchange" rerender="ThemePreview"/>
<apex:selectOptions value="{!themeOptions}"/>
</apex:selectList>
</apex:pageBlockSection>
<apex:pageBlockSection >
<div class="custom" style="padding: 1em;"><!-- Theme CSS hook -->
<h2>This is a Sub-Heading</h2>
<p>This is standard body copy. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Quisque neque arcu, pellentesque in vehicula vitae, dictum
id dolor. Cras viverra consequat neque eu gravida. Morbi hendrerit lobortis
mauris, id sollicitudin dui rhoncus nec.</p>
<p><apex:image
value="{!URLFOR($Resource[selectedTheme], 'images/[Link]')}"/></p>
</div><!-- End of theme CSS hook -->
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

Note the following about this markup:


The page uses the Account standard controller, but has nothing to do with accounts. You have to specify a controller to use a
controller extension.
The first <apex:pageBlockSection> contains the theme selection widget. Using <apex:actionSupport>, changes
to the selection menu re-render the whole <apex:pageBlock>. This is so that the <apex:stylesheet> tag gets the
updated selectedTheme for its dynamic reference.
The theme preference selected here is only preserved in the view state for the controller, but you could easily save it to a custom
setting instead, and make it permanent.
The zip files that contain the graphics and style assets for each theme need to have a consistent structure and content. That is. there
needs to be an images/[Link] in each theme zip file, and so on.
There are only two dynamic references to the $Resource global variable on this page, but they show how to access both stylesheet
and graphic assets. You could use a dynamic reference in every <apex:image> tag on a page and completely change the look and
feel.
$Label and $Setup are similar to $Resource, in that they allow you to access text values or saved settings that your organization

administrator or users themselves can set in Salesforce:

175

Dynamic Visualforce Bindings

Dynamic References to Action Methods Using $Action

Custom labels allow you to create text messages that can be consistently used throughout your application. Label text can also be
translated and automatically displayed in a users default language. To learn more about how to use custom labels see Custom
Labels.
Custom settings allow you to create settings for your application, which can be updated by administrators or by users themselves.
They can also be hierarchical, so that user-level settings override role- or organization-level settings. To learn more about how to
use custom settings see Custom Settings.
SEE ALSO:
Using Static Resources
$Resource

Dynamic References to Action Methods Using $Action


The $Action global variable allows you to dynamically reference valid actions on an object type, or on a specific record. The most
likely way to make use of this is to create a URL to perform that action.
For example, you can use the expression {!URLFOR($Action[objectName].New)} in an <apex:outputLink>, with
a controller method getObjectName() that provides the name of the sObject.
Heres an example that does exactly that. The controller extension queries the system to learn the names of all the custom objects
accessible to the user, and presents a list of them, along with links to create a new record. First, create a controller extension named
DynamicActionsHandler:
public with sharing class DynamicActionsHandler {
public List<CustomObjectDetails> customObjectDetails { get; private set; }
public DynamicActionsHandler([Link] cont) {
[Link]();
}
public void loadCustomObjects() {
List<CustomObjectDetails> cObjects = new List<CustomObjectDetails>();
// [Link]() returns lightweight tokens with minimal metadata
Map<String, [Link]> gd = [Link]();
for(String obj : [Link]()) {
if([Link]('__c')) {
// Get the full metadata details only for custom items
[Link] objD = [Link](obj).getDescribe();
if( ! [Link]()) {
// Save details for custom objects, not custom settings
CustomObjectDetails objDetails = new CustomObjectDetails(
obj, [Link](), [Link]());
[Link](objDetails);
}
}
}
[Link]();
[Link] = cObjects;
}

176

Dynamic Visualforce Bindings

Dynamic References to Action Methods Using $Action

public class CustomObjectDetails implements Comparable {


public String nameStr
{ get; set; }
public String labelStr { get; set; }
public Boolean creatable { get; set; }
public CustomObjectDetails(String aName, String aLabel, Boolean isCreatable) {
[Link] = aName;
[Link] = aLabel;
[Link] = isCreatable;
}
public Integer compareTo(Object objToCompare) {
CustomObjectDetails cod = (CustomObjectDetails)objToCompare;
return([Link]([Link]));
}
}
}

There are a few things of interest in this extension:


The loadCustomObjects method uses Apex schema methods to get metadata information about available custom objects.
The [Link] method is a lightweight operation to get a small set of metadata about available objects
and custom settings. The method scans the collection looking for items with names that end in __c, which indicates they are
custom objects or settings. These items are more deeply inspected using getDescribe, and selected metadata is saved for the
custom objects.
Using if([Link]('__c')) to test whether an item is a custom object or not may feel like a hack, but the alternative
is to call [Link]().isCustom(), which is expensive, and there is a governor limit on the number of calls to
getDescribe. Scanning for the __c string as a first pass on a potentially long list of objects is more efficient.
This metadata is saved in an inner class, CustomObjectDetails, which functions as a simple structured container for the
fields to be saved.
CustomObjectDetails implements the Comparable interface, which makes it possible to sort a list of custom objects details
by an attribute of each object, in this case, the custom objects name.
Now create a Visualforce page with the following markup:
<apex:page standardController="Account"
extensions="DynamicActionsHandler">
<br/>
<apex:dataTable value="{!customObjectDetails}" var="coDetails">
<apex:column >
<apex:facet name="header">Custom Object</apex:facet>
<apex:outputText value="{![Link]}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Actions</apex:facet>
<apex:outputLink value="{!URLFOR($Action[[Link]].New)}"
rendered="{![Link]}">[Create]</apex:outputLink><br/>
<apex:outputLink value="{!URLFOR($Action[[Link]].List,
$ObjectType[[Link]].keyPrefix)}">[List]</apex:outputLink>
</apex:column>
</apex:dataTable>
</apex:page>

177

Dynamic Visualforce Bindings

Dynamic References to Schema Details Using $ObjectType

On a page that hasnt been assigned a specific record, the only two useful actions available are New and List. On a page that queries
for a record, the $Action global variable provides methods such as View, Clone, Edit, and Delete. Certain standard objects
have additional actions that make sense for their data types.
SEE ALSO:
$Action
Valid Values for the $Action Global Variable

Dynamic References to Schema Details Using $ObjectType


The $ObjectType global variable provides access to a variety of schema information about the objects in your organization. Use it
to reference names, labels, and data types of fields on an object, for example.
$ObjectType is a deep global variable, and offers the opportunity to use it in a double dynamic reference, like so:
$ObjectType[sObjectName].fields[fieldName].Type

Heres an example that uses dynamic globals to provide a general object viewer. First, create a new controller (not extension) named
DynamicObjectHandler:
public class DynamicObjectHandler {
// This class acts as a controller for the DynamicObjectViewer component
private String objType;
private List<String> accessibleFields;
public sObject obj {
get;
set {
setObjectType(value);
discoverAccessibleFields(value);
obj = reloadObjectWithAllFieldData();
}
}
// The sObject type as a string
public String getObjectType() {
return([Link]);
}
public String setObjectType(sObject newObj) {
[Link] = [Link]().getDescribe().getName();
return([Link]);
}
// List of accessible fields on the sObject
public List<String> getAccessibleFields() {
return([Link]);
}
private void discoverAccessibleFields(sObject newObj) {
[Link] = new List<String>();
Map<String, [Link]> fields =

178

Dynamic Visualforce Bindings

Dynamic References to Schema Details Using $ObjectType

[Link]().getDescribe().[Link]();
for (String s : [Link]()) {
if ((s != 'Name') && ([Link](s).getDescribe().isAccessible())) {
[Link](s);
}
}
}
private sObject reloadObjectWithAllFieldData() {
String qid = [Link]().getParameters().get('id');
String theQuery = 'SELECT ' + joinList(getAccessibleFields(), ', ') +
' FROM ' + getObjectType() +
' WHERE Id = :qid';
return([Link](theQuery));
}
// Join an Apex List of fields into a SELECT fields list string
private static String joinList(List<String> theList, String separator) {
if (theList == null)
{ return null; }
if (separator == null) { separator = ''; }
String joined = '';
Boolean firstItem = true;
for (String item : theList) {
if(null != item) {
if(firstItem){ firstItem = false; }
else { joined += separator; }
joined += item;
}
}
return joined;
}
}

Theres a number of things that are worth noting in this controller:


Visualforce components cant use controller extensions, so this class is written as a controller instead. There is no constructor defined,
so the class uses the default constructor.
To collect metadata for an object, the controller must know the object. Visualforce constructors cant take arguments so there is no
way to know what the object of interest is at the time of instantiation. Instead, the metadata discovery is triggered by the setting of
the public property obj.
Several of the methods in this class use system schema discovery methods, in slightly different ways than prior examples.
The next piece is a Visualforce component that displays schema information about an object, as well as the specific values of the record
that is queried. Create a new Visualforce component named DynamicObjectViewer with the following code:
<apex:component controller="DynamicObjectHandler">
<apex:attribute name="rec" type="sObject" required="true"
description="The object to be displayed." assignTo="{!obj}"/>
<apex:form >
<apex:pageBlock title="{!objectType}">
<apex:pageBlockSection title="Fields" columns="1">
<apex:dataTable value="{!accessibleFields}" var="f">

179

Dynamic Visualforce Bindings

Dynamic References to Schema Details Using $ObjectType

<apex:column >
<apex:facet name="header">Label</apex:facet>
<apex:outputText value="{!$ObjectType[objectType].fields[f].Label}"/>
</apex:column>
<apex:column >
<apex:facet name="header">API Name</apex:facet>
<apex:outputText value="{!$ObjectType[objectType].fields[f].Name}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Type</apex:facet>
<apex:outputText value="{!$ObjectType[objectType].fields[f].Type}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Value</apex:facet>
<apex:outputText value="{!obj[f]}"/>
</apex:column>
</apex:dataTable>
</apex:pageBlockSection>
<apex:pageBlockSection columns="4">
<apex:commandButton value="View"
action="{!URLFOR($Action[objectType].View, [Link])}"/>
<apex:commandButton value="Edit"
action="{!URLFOR($Action[objectType].Edit, [Link])}"/>
<apex:commandButton value="Clone"
action="{!URLFOR($Action[objectType].Clone, [Link])}"/>
<apex:commandButton value="Delete"
action="{!URLFOR($Action[objectType].Delete, [Link])}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:component>

Notice the following:


Any page that uses this component must look up a record. To do so, use the standard controller for that object, and specify the Id
of the record in the URL. For example,
[Link]
The selected record is immediately passed into the components obj attribute. This parameter is used for all of the object metadata
discovery.
The three double dynamic references, which start with $ObjectType[objectType].fields[f], display the metadata
for each field, while the normal dynamic reference displays the actual value of the field.
For the data value, the value is {!obj[f]}, using a getter method in the controller, not the perhaps more natural {!rec[f]},
which is the parameter to the component. The reason is simple, the obj attribute has been updated to load data for all of the fields,
while rec has remained unchanged from what was loaded by the standard controller, and so only has the Id field loaded.

180

Dynamic Visualforce Bindings

Dynamic References to Schema Details Using $ObjectType

Finally, the new component can be used to create any number of simple Visualforce pages that use the component to display a record
detail and schema info page, such as these two pages:
<apex:page standardController="Account">
<c:DynamicObjectViewer rec="{!account}"/>
</apex:page>
<apex:page standardController="Contact">
<c:DynamicObjectViewer rec="{!contact}"/>
</apex:page>

SEE ALSO:
$ObjectType
Field Schema Details Available Using $ObjectType
Object Schema Details Available Using $ObjectType

181

CHAPTER 13 Dynamic Visualforce Components


Visualforce is primarily intended to be a static, markup-driven language that lets developers create a user interface that matches the
Salesforce look-and-feel. However, there are occasions when its necessary to programmatically create a page. Usually, this is to achieve
complicated user interface behavior thats difficult or impossible with standard markup.
Dynamic Visualforce components offer a way to create Visualforce pages that vary the content or arrangement of the component tree
according to a variety of states, such as a users permissions or actions, user or organization preferences, the data being displayed, and
so on. Rather than using standard markup, dynamic Visualforce components are designed in Apex.
A dynamic Visualforce component is defined in Apex like this:
Component.Component_namespace.Component_name

For example, <apex:dataTable> becomes [Link].


Note: The Standard Component Reference contains the dynamic representation for all valid Visualforce components.
Visualforce components that are dynamically represented in Apex behave like regular classes. Every attribute that exists on a standard
Visualforce component is available as a property in the corresponding Apex representation with get and set methods. For example, you
could manipulate the value attribute on an <apex:outputText> component as follows:
[Link] outText = new [Link]();
[Link] = 'Some dynamic output text.';

Consider using dynamic Visualforce components in the following scenarios:


You can use dynamic Visualforce components inside complex control logic to assemble components in combinations that would
be challenging or impossible to create using equivalent standard Visualforce. For example, with standard Visualforce components,
you typically control the visibility of components using the rendered attribute with the global IF() formula function. By writing
your control logic in Apex, you can choose to display components dynamically with a more natural mechanism.
If you know that youll be iterating over objects with certain fields, but not specifically which objects, dynamic Visualforce components
can plug in the object representation by using a generic sObject reference. For more information, see Example Using a Related
List on page 188.
Warning: Dynamic Visualforce components are not intended to be the primary way to create new Visualforce pages in your
organization. Existing Visualforce pages shouldnt be rewritten in a dynamic manner and, for most use cases, standard Visualforce
components are acceptable and preferred. You should only use dynamic Visualforce components when the page must adapt
itself to user state or actions in ways that cant be elegantly coded into static markup.

Dynamic Components Restrictions


Not every feature of Visualforce makes sense in a dynamic context, so some components arent available dynamically.
The following standard Visualforce components dont have corresponding dynamic representations in Apex:
<apex:attribute>

182

Dynamic Visualforce Components

Creating and Displaying Dynamic Components

<apex:component>
<apex:componentBody>
<apex:composition>
<apex:define>
<apex:dynamicComponent>
<apex:include>
<apex:insert>
<apex:param>
<apex:variable>
If a dynamic Visualforce component refers to a specific sObject field, and that field is later deleted, the Apex code for that field
reference will still compile, but the page will fail when it is viewed. Also, you can create references to global variables such as $Setup
or $Label, and then delete the referenced item, with similar results. Please verify such pages continue to work as expected.
Dynamic Visualforce pages and expressions check attribute types more strictly than static pages.
You cant set pass-through HTML attributes on dynamic components.

Creating and Displaying Dynamic Components


Note: The examples in this section are deliberately simple for instructional purposes. For a more complete example of when you
might benefit from dynamic Visualforce components, see Example Using a Related List on page 188.
There are two parts to embedding dynamic Visualforce components on your page:
1. Adding an <apex:dynamicComponent> tag somewhere on your page. This tag acts as a placeholder for your dynamic
component.
2. Developing a dynamic Visualforce component in your controller or controller extension.
The <apex:dynamicComponent> tag has one required attributecomponentValuethat accepts the name of an Apex
method that returns a dynamic component. For example, if you wanted to dynamically generate the title of a section header differently
if the deadline for a submitting form has passed, you could use the following markup and controller code:
<apex:page standardController="Contact" extensions="DynamicComponentExample">
<apex:dynamicComponent componentValue="{!headerWithDueDateCheck}"/>
<apex:form>
<apex:inputField value="{![Link]}"/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:form>
</apex:page>
public class DynamicComponentExample {
public DynamicComponentExample([Link] con) { }
public [Link] getHeaderWithDueDateCheck() {
date dueDate = [Link](2011, 7, 4);
boolean overdue = [Link]().daysBetween(dueDate) < 0;
[Link] sectionHeader = new [Link]();
if (overdue) {
[Link] = 'This Form Was Due On ' + [Link]() + '!';
return sectionHeader;
} else {

183

Dynamic Visualforce Components

Creating and Displaying Dynamic Components

[Link] = 'Form Submission';


return sectionHeader;
}
}
}

You can have multiple <apex:dynamicComponent> components on a single page.


Each dynamic component has access to a common set of methods and properties. You can review this list in the Apex Developer's Guide
in the chapter titled Component Class.

Dynamic Custom Components


Using custom components dynamically works exactly the same as the standard Visualforce components. Just change the namespace
to that of the custom component. Your custom components are in the c namespace, so you can create one dynamically like this:
[Link] myDy = new [Link]();

As a convenience for your own components, you can omit the namespace, like so:
[Link] myDy = new [Link]();

If you are using components provided by a third party in a package, use the namespace of the package provider:
[Link] usefulC = new [Link]();

Passing Attributes through the Constructor


Instead of setting component attributes via their properties, you can simply pass in a list of one or more attributes through the constructor:
[Link] dynDataList =
new [Link](id='myDataList', rendered=true);

If an attribute isnt defined in the constructor, the component's default values are used for that attribute.
There are two components that must have an attribute defined in the constructor, rather than through a property:
[Link] must have showChatter=true passed to its constructor if you want to display the Chatter
information and controls for a record. Otherwise, this attribute is always false.
[Link] must have multiSelect=true passed to its constructor if you want the user to be
able to select more than one option at a time. Otherwise, this value is always false.
These values are Booleans, not Strings; you dont need to enclose them in single quote marks.
Warning: You cant pass attributes through the class constructor if the attribute name matches an Apex keyword. For example,
[Link] cant pass list through the constructor, because List is a reserved keyword. Similarly,
[Link] cant define the for attribute in the constructor, because its also a keyword.

Defining Expressions and Arbitrary HTML


You can add expression language statements with the expressions property. Append expressions before a property name
to pass in an expression statement. As in static markup, expressions must be wrapped with the {! } syntax. Heres an example:
[Link] detail = new [Link]();
[Link] = '{![Link]}';

184

Dynamic Visualforce Components

Creating and Displaying Dynamic Components

[Link] = false;
[Link] = false;

Valid expressions include those that refer to fields on standard and custom objects. Global variables and functions are also available, as
demonstrated in this example:
[Link] head1 = new [Link]();
[Link] =
'{!IF(CONTAINS($[Link], "John"), "Hello John", "Hey, you!")}';

Passing in values through expressions is valid only for attributes that support them. Using {! } outside of the expressions
property will be interpreted literally, not as an expression.
If you want to include plain HTML, you can do so by setting the escape property on [Link] to
false:
[Link] head1 = new [Link]();
[Link] = false;
[Link] = '<h1>This header contains HTML</h1>';

Defining Facets
Similar to the way expressions are defined, facets act as a special property available to dynamic components. Heres an example:
[Link] myTable = new [Link](var='item');
[Link] = '{!items}';
[Link] header =
new [Link](value='This is My Header');
[Link] = header;

For more information on facets, see Best Practices for Using Component Facets on page 343.

Defining Child Nodes


You can add child nodes to a dynamic Visualforce component using the childComponents property. The childComponents
property acts as a reference to a List of [Link] objects.
Heres an example of how you can use childComponents to construct a <apex:form> with child input nodes:
public [Link] getDynamicForm() {
[Link] dynPageBlock = new [Link]();
// Create an input field for Account Name
[Link] theNameField = new [Link]();
[Link] = '{![Link]}';
[Link] = 'theName';
[Link] theNameLabel = new [Link]();
[Link] = 'Rename Account?';
[Link] = 'theName';
// Create an input field for Account Number
[Link] theAccountNumberField = new [Link]();
[Link] = '{![Link]}';
[Link] = 'theAccountNumber';
[Link] theAccountNumberLabel = new [Link]();

185

Dynamic Visualforce Components

Deferred Creation of Dynamic Components

[Link] = 'Change Account #?';


[Link] = 'theAccountNumber';
// Create a button to submit the form
[Link] saveButton = new [Link]();
[Link] = 'Save';
[Link] = '{!Save}';
// Assemble the form components
[Link](theNameLabel);
[Link](theNameField);
[Link](theAccountNumberLabel);
[Link](theAccountNumberField);
[Link](saveButton);
return dynPageBlock;
}

If your markup is defined as:


<apex:form>
<apex:dynamicComponent componentValue="{!dynamicForm}"/>
</apex:form>

Then your markup is equivalent to the following static markup:


<apex:form>
<apex:pageBlock>
<apex:outputLabel for="theName"/>
<apex:inputField value="{![Link]}" id="theName"/>
<apex:outputLabel for="theAccountNumber"/>
<apex:inputField value="{![Link]}" id="theAccountNumber"/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlock>
</apex:form>

Notice that the order of elements in the equivalent static markup is the order in which the dynamic components were added to
childComponents, not the order in which they were declared in the Apex code of the getDynamicForm method.

Deferred Creation of Dynamic Components


The Apex method that defines a dynamic component is by default executed at page load time, before any action method thats defined
for the page is run. Set the invokeAfterAction attribute of a dynamic component to true to wait for page actions to be
completed before the method that creates the dynamic component runs. This enables you to design dynamic components that change
depending on the result of, for example, a page initialization action or a callout.
Heres a page that has a single dynamic component, which is created after the pages action method, pageActionUpdateMessage,
is completed.
<apex:page controller="DeferredDynamicComponentController"
action="{!pageActionUpdateMessage}" showHeader="false">
<apex:dynamicComponent componentValue="{!dynamicComp}" invokeAfterAction="true"/>

186

Dynamic Visualforce Components

Deferred Creation of Dynamic Components

</apex:page>

Heres the associated controller that provides the dynamic component definition, and illustrates the effect of the invokeAfterAction
attribute.
public class DeferredDynamicComponentController {
private String msgText { get; set; }
public DeferredDynamicComponentController() {
[Link] = 'The controller is constructed.';
}
public [Link] getDynamicComp() {
// This is the component to return
[Link] dynOutPanel= new [Link]();
[Link] = 'block';
// Child component to hold the message text
[Link] msgOutput = new [Link]();
[Link] = [Link];
[Link](msgOutput);
return dynOutPanel;
}
public Object pageActionUpdateMessage() {
[Link]= 'The page action method has been run.';
return null;
}
}

With the default behavior for dynamic components, the msgText value thats set in the constructor is displayed by the dynamic
component. Setting invokeAfterAction="true" on the dynamic component changes that behavior. The page waits for the
pageActionUpdateMethod to be completed and then creates the dynamic component, and so the component displays the
value for msgText thats set in the pageActionUpdateMessage action method instead.
Note: The invokeAfterAction attribute is available for dynamic components in pages set to API version 31.0 or later.

Deferred Creation of Dynamic Components and Other Actions


invokeAfterAction="true" affects dynamic components immediately at page load time, because thats when page actions
run. Setting invokeAfterAction="true" reverses the order of component creation and any action method on the page. That
is, the order of execution is changed for action methods on all of the following components.

<apex:actionFunction>
<apex:actionPoller>
<apex:actionSupport>
<apex:commandButton>
<apex:commandLink>

187

Dynamic Visualforce Components

Example Using a Related List

<apex:page>
<apex:togglePanel>
When invokeAfterAction="false" is set on a dynamic component, the order of execution is as follows. This is the default
behavior for dynamic components.
1. Invoke the dynamic components creation method, which constructs the component.
2. Invoke the action method.
3. Rerender the page.
When invokeAfterAction="true" is set on a dynamic component, the order of execution is as follows.
1. Invoke the action method.
2. Invoke the dynamic components creation method, which constructs the component.
3. Rerender the page.
Note: In the second case, if the action method returns a PageReference, Visualforce will redirect the request to the new page,
and the dynamic components creation method wont be run. To avoid a possible order-of-execution bug, its a best practice that
methods that create dynamic components dont have side effects.

Example Using a Related List


Dynamic Visualforce components are best used when you dont know the type of object you want to reference, as opposed to dynamic
Visualforce bindings, which are best used when you dont know the fields you want to access.
The following scenario for using dynamic Visualforce constructs a simple, reusable page with a known set of fields you want to access.
The page and its custom object are placed into an unmanaged package and distributed throughout the same organization.
First, create a custom object called Classroom. Create two objectsone named Science 101 and another named Math 201,
as this figure shows:

Next, create two more custom objects called Student and Teacher. After you finish creating each object:
1. Click New under Custom Fields & Relationships.
2. Select Master-Detail Relationship, then click Next.
3. Select Classroom from the drop-down list, then click Next.
4. Continue to click Next, leaving all the default values intact.
Create the following objects and matching relationships:
A new Student named Johnny Walker, and a new Teacher named Mister Pibb, both assigned to Science 101.
Another new Student named Boont Amber, and a new Teacher named Doctor Pepper, both assigned to Math 201.

188

Dynamic Visualforce Components

Example Using a Related List

Now, create a new Apex page called DynamicClassroomList and paste the following code:
public class DynamicClassroomList {
private
private
private
private

[Link] controller;
PageReference savePage;
Set<String> unSelectedNames;
Set<String> selectedNames;

public List<String> selected { get; set; }


public List<String> unselected { get; set; }
public String objId { get; set; }
public List<String> displayObjs {
get; private set;
}
boolean idIsSet = false;
public DynamicClassroomList() {
init();
}
public DynamicClassroomList([Link] con) {
[Link] = con;
init();
}
private void init() {
savePage = null;
unSelectedNames = new Set<String>();
selectedNames = new Set<String>();
if (idIsSet) {
[Link]().getParameters().put('id', objId);
idIsSet = false;
}
}
public PageReference show() {
savePage = [Link];
[Link]().put('id', objId);
return savePage;
}
public List<SelectOption> displayObjsList {
get {
List<SelectOption> options = new List<SelectOption>();
List<Classroom__c> classrooms = [SELECT id, name FROM Classroom__c];
for (Classroom__c c: classrooms) {
[Link](new SelectOption([Link], [Link]));
}
return options;
}

189

Dynamic Visualforce Components

Example Using a Related List

}
public PageReference customize() {
savePage = [Link]();
[Link]().put('id', objId);
return [Link];
}
// The methods below are for constructing the select list
public List<SelectOption> selectedOptions {
get {
List<String> sorted = new List<String>(selectedNames);
[Link]();
List<SelectOption> options = new List<SelectOption>();
for (String s: sorted) {
[Link](new SelectOption(s, s));
}
return options;
}
}
public List<SelectOption> unSelectedOptions {
get {
[Link] R = Classroom__c.[Link]();
List<[Link]> C = [Link]();
List<SelectOption> options = new List<SelectOption>();
for ([Link] cr: C) {
String relName = [Link]();
// We're only interested in custom relationships
if (relName != null && [Link]('__r')) {
[Link](new SelectOption(relName, relName));
}
}
return options;
}
}

public void doSelect() {


for (String s: selected) {
[Link](s);
[Link](s);
}
}
public void doUnSelect() {
for (String s: unselected) {
[Link](s);
[Link](s);
}
}

190

Dynamic Visualforce Components

Example Using a Related List

public [Link] getClassroomRelatedLists() {


[Link] dynOutPanel= new [Link]();
for(String id: selectedNames) {
[Link] dynRelList = new [Link]();
[Link] = id;
[Link](dynRelList);
}
return dynOutPanel;
}
}

After trying to save, you may be prompted about a missing Visualforce page. Click the link to create the page: the next blocks of code
will populate it.
Create a Visualforce page called dynVFClassroom and paste the following code:
<apex:page standardController="Classroom__c" recordSetVar="classlist"
extensions="DynamicClassroomList">
<apex:dynamicComponent componentValue="{!ClassroomRelatedLists}"/>
<apex:form>
<apex:pageBlock title="Classrooms Available" mode="edit">
<apex:pageMessages/>
<apex:selectRadio value="{!objId}">
<apex:selectOptions value="{!displayObjsList}"/>
</apex:selectRadio>
</apex:pageBlock>
<apex:commandButton value="Select Related Items" action="{!Customize}"/>
</apex:form>
</apex:page>

Finally, create a page called DynamicClassroomList. If youve been following this tutorial from the beginning, you should have
already created this page when constructing your controller extension. Paste in the following code:
<apex:page standardController="Classroom__c" recordsetvar="listPageMarker"
extensions="DynamicClassroomList">
<apex:messages/><br/>
<apex:form>
<apex:pageBlock title="Select Relationships to Display" id="selectionBlock">
<apex:panelGrid columns="3">
<apex:selectList id="unselected_list" required="false"
value="{!selected}" multiselect="true" size="20"
style="width:250px">
<apex:selectOptions value="{!unSelectedOptions}"/>
</apex:selectList>
<apex:panelGroup>
<apex:commandButton value=">>" action="{!DoSelect}"
reRender="selectionBlock"/>
<br/>

191

Dynamic Visualforce Components

Example Using a Related List

<apex:commandButton value="<<" action="{!DoUnselect}"


reRender="selectionBlock"/>
</apex:panelGroup>
<apex:selectList id="selected_list" required="false"
value="{!unselected}" multiselect="true" size="20"
style="width:250px">
<apex:selectOptions value="{!selectedOptions}"/>
</apex:selectList>
</apex:panelGrid>
</apex:pageBlock>
<br/>
<apex:commandButton value="Show Related Lists" action="{!show}"/>
</apex:form>
</apex:page>

This is the page that presents the user with the option of selecting which object relationships to display. Notice that the selected and
unselected lists are populated through dynamic means.
After assembling the controller extension and these pages, navigate to /apex/dynVFClassroom in your organization. Youll see
a sequence similar to the following:

192

Dynamic Visualforce Components

Example Using a Related List

193

CHAPTER 14 Integrating Email with Visualforce


Visualforce can be used to send email to any of your contacts, leads, or other recipients. It is also possible to create reusable email
templates that take advantage of Visualforce's ability to iterate over your Salesforce records. The following topics explain how:
Sending an Email with Visualforce
Visualforce Email Templates

Sending an Email with Visualforce


It is possible to send email using Visualforce by creating a custom controller to deliver the message. The Apex
[Link] class handles the outbound email functionality available to Salesforce.
The following topics demonstrate a number of features available when sending email through Visualforce:
Creating a Custom Controller with the Messaging Class
Creating an Email Attachment

Creating a Custom Controller with the Messaging Class


At minimum, a custom controller that uses the Apex Messaging namespace needs a subject, a body, and a recipient for the email.
You will need a page that acts as a form to fill out the subject and body and deliver the email.
Create a new page called sendEmailPage and use the following code:
<apex:page controller="sendEmail">
<apex:messages />
<apex:pageBlock title="Send an Email to Your
{![Link]} Representatives">
<p>Fill out the fields below to test how you might send an email to a user.</p>
<br />
<apex:dataTable value="{![Link]}" var="contact" border="1">
<apex:column >
<apex:facet name="header">Name</apex:facet>
{![Link]}
</apex:column>
<apex:column >
<apex:facet name="header">Email</apex:facet>
{![Link]}
</apex:column>
</apex:dataTable>
<apex:form >
<br /><br />
<apex:outputLabel value="Subject" for="Subject"/>:<br />

194

Integrating Email with Visualforce

Creating a Custom Controller with the Messaging Class

<apex:inputText value="{!subject}" id="Subject" maxlength="80"/>


<br /><br />
<apex:outputLabel value="Body" for="Body"/>:<br />
<apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/>
<br /><br /><br />
<apex:commandButton value="Send Email" action="{!send}" />
</apex:form>
</apex:pageBlock>
</apex:page>

Notice in the page markup that the account ID is retrieved from the URL of the page. For this example to render properly, you must
associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the
resulting URL should be:
[Link]

Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
The following code creates a controller named sendEmail that implements the [Link] class,
and uses the contacts related to an account as recipients:
public class sendEmail {
public String subject { get; set; }
public String body { get; set; }
private final Account account;
// Create a constructor that populates the Account object
public sendEmail() {
account = [select Name, (SELECT [Link], [Link] FROM [Link])
from Account where id = :[Link]().getParameters().get('id')];
}
public Account getAccount() {
return account;
}
public PageReference send() {
// Define the email
[Link] email = new [Link]();
String addresses;
if ([Link][0].Email != null)
{
addresses = [Link][0].Email;
// Loop through the whole list of contacts and their emails
for (Integer i = 1; i < [Link](); i++)
{
if ([Link][i].Email != null)
{
addresses += ':' + [Link][i].Email;
}
}
}

195

Integrating Email with Visualforce

Creating a Custom Controller with the Messaging Class

String[] toAddresses = [Link](':', 0);


// Sets the paramaters of the email
[Link]( subject );
[Link]( toAddresses );
[Link]( body );
// Sends the email
[Link] [] r =
[Link](new [Link][] {email});
return null;
}
}

Notice in the controller that:


The subject and body of the email are set through a separate Visualforce page and passed into the controller.
The method that sends the email is called send(). This name must match the name of the action for the Visualforce button that
sends the email.
The recipients of the email, that is, the email addresses stored in toAddresses[], come from the addresses of the contacts
available in an associated account. When compiling a list of recipients from contacts, leads, or other records, it is a good practice to
loop through all the records to verify that an email address is defined for each. The account ID is retrieved from the URL of the page.

196

Integrating Email with Visualforce

Creating an Email Attachment

Example of the Form on sendEmailPage

SEE ALSO:
Apex Developer Guide: Outbound Email

Creating an Email Attachment


If you want to add an attachment to your email, you will need to add only a few lines of code to your custom controller. Email attachments
are Blob file types. To create an attachment, you need to use the Apex [Link] class. You must
define both the file name and the content of an EmailFileAttachment object.

Adding a PDF Attachment


The following example demonstrates how to transform a PageReference to a Visualforce page rendered as a PDF into an email
attachment. First, create a page called attachmentPDF:
<apex:page standardController="Account" renderAs="PDF">
<h1>Account Details</h1>

197

Integrating Email with Visualforce

Creating an Email Attachment

<apex:panelGrid columns="2">
<apex:outputLabel for="Name" value="Name"/>
<apex:outputText id="Name" value="{![Link]}"/>
<apex:outputLabel for="Owner" value="Account Owner"/>
<apex:outputText id="Owner" value="{![Link]}"/>
<apex:outputLabel for="AnnualRevenue" value="Annual Revenue"/>
<apex:outputText id="AnnualRevenue" value="{0,number,currency}">
<apex:param value="{![Link]}"/>
</apex:outputText>
<apex:outputLabel for="NumberOfEmployees" value="Employees"/>
<apex:outputText id="NumberOfEmployees" value="{![Link]}"/>
</apex:panelGrid>
</apex:page>

Note: See Best Practices for Rendering PDF Files on page 345 for details of which components are recommended for use in PDF
attachments.
Next, create the EmailFileAttachment object in the send() method of your custom controller. The following examples must
be placed before calling [Link]:
// Reference the attachment page, pass in the account ID
PageReference pdf = [Link];
[Link]().put('id',(String)[Link]);
[Link](true);
// Take the PDF content
Blob b = [Link]();
// Create the email attachment
[Link] efa = new [Link]();
[Link]('[Link]');
[Link](b);

If your SingleEmailMessage object is named email, then you associate the attachment like this:
[Link](new [Link][] {efa});

Defining a Custom Component as an Attachment


By creating a custom component and using it on the Visualforce email form and to render the PDF for the email, users can see a preview
of the content they are trying to send.
The following markup defines a custom component named attachment that represents the attachment for the email:
<apex:component access="global">
<h1>Account Details</h1>
<apex:panelGrid columns="2">

198

Integrating Email with Visualforce

Creating an Email Attachment

<apex:outputLabel for="Name" value="Name"/>


<apex:outputText id="Name" value="{![Link]}"/>
<apex:outputLabel for="Owner" value="Account Owner"/>
<apex:outputText id="Owner" value="{![Link]}"/>
<apex:outputLabel for="AnnualRevenue" value="Annual Revenue"/>
<apex:outputText id="AnnualRevenue" value="{0,number,currency}">
<apex:param value="{![Link]}"/>
</apex:outputText>
<apex:outputLabel for="NumberOfEmployees" value="Employees"/>
<apex:outputText id="NumberOfEmployees" value="{![Link]}"/>
</apex:panelGrid>
</apex:component>

Replace your attachmentPDF page like this:


<apex:page standardController="account" renderAs="PDF">
<c:attachment/>
</apex:page>

Then add the custom component to render at the bottom of your previous sendEmailPage:
<apex:pageBlock title="Preview the Attachment for {![Link]}">
<c:attachment/>
</apex:pageBlock>

If you want to make changes to both the attachment and the preview, the attachment custom component needs to be modified
in only one location.

Example: Sending an Email with an Attachment


The following example shows the previous sendEmail example with a custom component that adds a Visualforce page as an
attachment. First, the controller:
public class sendEmail {
public String subject { get; set; }
public String body { get; set; }
private final Account account;
// Create a constructor that populates the Account object
public sendEmail() {
account = [SELECT Name,
(SELECT [Link], [Link] FROM [Link])
FROM Account
WHERE Id = :[Link]().getParameters().get('id')];
}
public Account getAccount() {
return account;
}

199

Integrating Email with Visualforce

Creating an Email Attachment

public PageReference send() {


// Define the email
[Link] email = new [Link]();
// Reference the attachment page and pass in the account ID
PageReference pdf = [Link];
[Link]().put('id',(String)[Link]);
[Link](true);
// Take the PDF content
Blob b = [Link]();
// Create the email attachment
[Link] efa = new [Link]();
[Link]('[Link]');
[Link](b);
String addresses;
if ([Link][0].Email != null) {
addresses = [Link][0].Email;
// Loop through the whole list of contacts and their emails
for (Integer i = 1; i < [Link](); i++) {
if ([Link][i].Email != null) {
addresses += ':' + [Link][i].Email;
}
}
}
String[] toAddresses = [Link](':', 0);
// Sets the paramaters of the email
[Link]( subject );
[Link]( toAddresses );
[Link]( body );
[Link](new [Link][] {efa});
// Sends the email
[Link] [] r =
[Link](new [Link][] {email});
return null;
}
}

Next, the Visualforce page that sends the email:


<apex:page controller="sendEmail">
<apex:messages/>
<apex:pageBlock title="Send an Email to Your {![Link]} Representatives">
<p>Fill out the fields below to test how you might send an email to a user.</p>
<apex:dataTable value="{![Link]}" var="contact" border="1">
<apex:column>

200

Integrating Email with Visualforce

Visualforce Email Templates

<apex:facet name="header">Name</apex:facet>
{![Link]}
</apex:column>
<apex:column>
<apex:facet name="header">Email</apex:facet>
{![Link]}
</apex:column>
</apex:dataTable>
<apex:form><br/><br/>
<apex:outputLabel value="Subject" for="Subject"/>: <br/>
<apex:inputText value="{!subject}" id="Subject" maxlength="80"/>
<br/><br/>
<apex:outputLabel value="Body" for="Body"/>: <br/>
<apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/>
<br/><br/>
<apex:commandButton value="Send Email" action="{!send}"/>
</apex:form>
</apex:pageBlock>
<apex:pageBlock title="Preview the Attachment for {![Link]}">
<c:attachment/>
</apex:pageBlock>
</apex:page>

SEE ALSO:
Apex Developer Guide: EmailFileAttachment Class

Visualforce Email Templates


Developers and administrators can use Visualforce to create email templates. The advantage of using Visualforce over standard HTML
email templates is that Visualforce gives you the ability to perform advanced operations on data that is sent to a recipient.
Although Visualforce email templates use standard Visualforce components, they are not created in the same way. Visualforce email
templates always use components that are prefaced with the messaging namespace. In addition:
All Visualforce email templates must be contained within a single <messaging:emailTemplate> tag. This is analogous to
regular Visualforce pages being defined within a single <apex:page> tag.
The <messaging:emailTemplate> tag must contain either a single <messaging:htmlEmailBody> tag or a single
<messaging:plainTextEmailBody> tag.
Several standard Visualforce components are not available for use within <messaging:emailTemplate>. These include
<apex:detail>, <apex:pageBlock> and all related pageBlock components, and all input components such as
<apex:form>. If you attempt to save a Visualforce email template with these components, an error message displays.
The following topics provide more details:
Creating a Visualforce Email Template
Using a Custom Stylesheet in a Visualforce Email Template

201

Integrating Email with Visualforce

Creating a Visualforce Email Template

Adding Attachments
Using Custom Controllers within Visualforce Email Templates

Creating a Visualforce Email Template


1. Do one of the following:
If you have permission to edit public templates, from Setup, enter Email Templates in the Quick Find box, then
select Email Templates.
If you dont have permission to edit public templates, go to your personal settings. Enter Templates in the Quick Find
box, then select Email Templates or My Templateswhichever one appears.
2. Click New Template.
3. Choose Visualforce and click Next.
You cant send a mass email using a Visualforce email template.
4. Choose a folder in which to store the template.
5. To make the template available for use, select the Available For Use checkbox.
6. Enter a name in Email Template Name.
7. If necessary, change the Template Unique Name. This unique name refers to the component when you use the [Link]
API. In managed packages, this unique name prevents naming conflicts in package installations. This name can contain only
underscores and alphanumeric characters, and must be unique in your org. It must begin with a letter, not include spaces, not end
with an underscore, and not contain two consecutive underscores. With the Template Unique Name field, you can change
certain components names in a managed package and the changes are reflected in a subscribers organization.
8. If desired, choose a different character set from the Encoding drop-down list.
9. Enter a description for the template. Both template name and description are for your internal use only.
10. Enter a subject line for your template in Email Subject.
11. In the Recipient Type drop-down list, select the type of recipient to receive email created from the template.
12. If desired, in the Related To Type drop-down list, select the object from which the template retrieves merge field data.
13. Click Save.
14. On the Viewing Email Templates page, click Edit Template.
15. Enter markup text for your Visualforce email template.
Note: If you are including an image, we recommend uploading it to the Documents tab to reference the copy of the image
on our server. For example:
<apex:image id="Logo"
value="[Link]
id=015D0000000Dpwc&oid=00DD0000000FHaG&lastMod=127057656800"
height="64" width="64"/>

16. To specify the version of Visualforce and the API used with this email template, click Version Settings. If youve installed managed
packages from the AppExchange, you can also specify which version of each managed package to use with this email template.
Generally, use the default value for all versions, to associate the email template with the most recent version of Visualforce, the API,
and each managed package. To maintain specific behavior, you can specify an older version of Visualforce and the API. To access
components or functionality that differ from the most recent package version, you can specify an older version of a managed package.

202

Integrating Email with Visualforce

Creating a Visualforce Email Template

17. To view the details of the template, click Save. To continue editing your template, click Quick Save. Your Visualforce markup must
be valid before you can save your template.
Note: The maximum size of a Visualforce email template is 1 MB.
You cant send a mass email using a Visualforce email template. The {!Receiving_User.field_name} and
{!Sending_User.field_name} merge fields work only for mass email and are unavailable in Visualforce email
templates.
The following example shows how you can define a Visualforce email template that displays all the cases associated with a contact. The
example uses an <apex:repeat> tag to iterate through all the cases related to a contact and incorporate them into the body of
the template:
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {![Link]}"
language="{!recipient.language__c}"
replyTo="support@[Link]">
<messaging:htmlEmailBody>
<html>
<body>
<p>Dear {![Link]},</p>
<p>Below is a list of cases related to {![Link]}.</p>
<table border="0" >
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
</tr>
<apex:repeat var="cx" value="{![Link]}">
<tr>
<td><a href =
"[Link]
</a></td>
<td>{![Link]}</td>
<td>{![Link]}</td>
<td>{![Link]}</td>
</tr>
</apex:repeat>
</table>
<p/>
<center>
<apex:outputLink value="[Link]
For more detailed information login to [Link]
</apex:outputLink>
</center>
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>

Notice the following about the markup:

203

Integrating Email with Visualforce

Using a Custom Stylesheet in a Visualforce Email Template

The attributes recipientType and relatedToType act as controllers for the email template. With them you can access
the same merge fields that are available to other standard controllers. The recipientType attribute represents the recipient
of the email. The relatedToType attribute represents the record to associate with the email.
The <messaging:htmlEmailBody> component can include a mix of Visualforce markup and HTML. The
<messaging:plainTextEmailBody> component can only include Visualforce markup and plain text.
To translate Visualforce email templates based on recipients or related objects languages, use the
<messaging:emailTemplate> tag's language attribute (valid values: Salesforce supported language keys, for example,
en-US). The language attribute accepts merge fields from the email template's recipientType and relatedToType
attributes. You create custom language fields for use in the merge fields. The Translation Workbench is required to translate email
templates. The example uses a merge field to obtain a language attribute for the contact receiving the email.
SEE ALSO:
Using a Custom Stylesheet in a Visualforce Email Template

Using a Custom Stylesheet in a Visualforce Email Template


By default, Visualforce email templates always use the standard look and feel of other Salesforce components. However, you can extend
or overwrite these styles by defining your own stylesheet.
Unlike other Visualforce pages, Visualforce email templates cannot use referenced page styles or static resources. Although the CSS
appears to render in the email template preview pane, it does not appear the same to the recipients of your email. You must define your
style using CSS within <style> tags.
The following example changes the font of your email to Courier, adds a border to the table, and changes the color of the table rows:
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {![Link]}"
replyTo="support@[Link]">
<messaging:htmlEmailBody>
<html>
<style type="text/css">
body {font-family: Courier; size: 12pt;}
table {
border-width: 5px;
border-spacing: 5px;
border-style: dashed;
border-color: #FF0000;
background-color: #FFFFFF;
}
td {
border-width: 1px;
padding: 4px;
border-style: solid;
border-color: #000000;
background-color: #FFEECC;
}
th {

204

Integrating Email with Visualforce

Using a Custom Stylesheet in a Visualforce Email Template

color: #000000;
border-width: 1px ;
padding: 4px ;
border-style: solid ;
border-color: #000000;
background-color: #FFFFF0;
}
</style>
<body>
<p>Dear {![Link]},</p>
<table border="0" >
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
</tr>
<apex:repeat var="cx" value="{![Link]}">
<tr>
<td><a href =
"[Link]
</a></td>
<td>{![Link]}</td>
<td>{![Link]}</td>
<td>{![Link]}</td>
</tr>
</apex:repeat>
</table>
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>

205

Integrating Email with Visualforce

Using a Custom Stylesheet in a Visualforce Email Template

Example of the Rendered Visualforce Email Template

Defining Visualforce Stylesheets in a Custom Component


Although you cannot reference an external stylesheet in a Visualforce email template, you can place the style definitions within a custom
component that can be referenced in other places. For example, you can modify the previous example to place the style information in
a component named EmailStyle:
<apex:component access="global">
<style type="text/css">
body {font-family: Courier; size: 12pt;}
table {
border-width: 5px;
border-spacing: 5px;
border-style: dashed;
border-color: #FF0000;
background-color: #FFFFFF;
}
td {
border-width: 1px;
padding: 4px;
border-style: solid;
border-color: #000000;
background-color: #FFEECC;
}
th {
color: #000000;
border-width: 1px ;

206

Integrating Email with Visualforce

Adding Attachments

padding: 4px ;
border-style: solid ;
border-color: #000000;
background-color: #FFFFF0;
}
</style>
</apex:component>

Then, in the Visualforce email template, you can reference just that component:
<messaging:htmlEmailBody>
<html>
<c:EmailStyle />
<body>
<p>Dear {![Link]},</p>
...
</body>
</html>
</messaging:htmlEmailBody>

Note: Any <apex:component> tags used within a Visualforce email template must have an access level of global.

Adding Attachments
You have the ability to add attachments to your Visualforce email templates. Each attachment must be encapsulated within a single
<messaging:attachment> component. Code within <messaging:attachment> can be a combination of HTML and
Visualforce tags.
The previous example shows how to create a Visualforce email template by iterating through some data and displaying it to an email
recipient. This example shows how to modify that markup to display the data as an attachment:
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {![Link]}"
replyTo="support@[Link]">
<messaging:htmlEmailBody>
<html>
<body>
<p>Dear {![Link]},</p>
<p>Attached is a list of cases related to {![Link]}.</p>
<center>
<apex:outputLink value="[Link]
For more detailed information login to [Link]
</apex:outputLink>
</center>
</body>
</html>
</messaging:htmlEmailBody>
<messaging:attachment>
<apex:repeat var="cx" value="{![Link]}">
Case Number: {![Link]}
Origin: {![Link]}

207

Integrating Email with Visualforce

Adding Attachments

Creator Email: {![Link]}


Case Number: {![Link]}
</apex:repeat>
</messaging:attachment>
</messaging:emailTemplate>

This markup renders in an email as an attached data file, without any formatting. You can display the data in a more readable format by
using one of the following options:
Changing the Filename
Changing the renderAs Attribute
Adding Styles and Images

Changing the Filename


The <messaging:attachment> tag has an attribute called filename that defines the name of the attached file. While it is
good practice to define an easily identifiable name, it is not required. If you leave it undefined, Salesforce generates a name for you.
A filename without an extension defaults to a text file. You can render an attached file as a CSV:
<messaging:attachment filename="[Link]">
<apex:repeat var="cx" value="{![Link]}">
{![Link]}
{![Link]}
{![Link]}
{![Link]}
</apex:repeat>
</messaging:attachment>

You can also render the data as an HTML file:


<messaging:attachment filename="[Link]">
<html>
<body>
<table border="0" >
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
</tr>
<apex:repeat var="cx" value="{![Link]}">
<tr>
<td><a href =
"[Link]
</a></td>
<td>{![Link]}</td>
<td>{![Link]}</td>
<td>{![Link]}</td>
</tr>
</apex:repeat>
</table>
</body>
</html>
</messaging:attachment>

208

Integrating Email with Visualforce

Adding Attachments

Although you can only define one filename for every <messaging:attachment> component, you can attach multiple files to
an email.

Changing the renderAs Attribute


Similar to other Visualforce pages, setting the renderAs attribute to PDF on a <messaging:attachment> component renders
the attachment as a PDF. For example:
<messaging:attachment renderAs="PDF" filename="[Link]">
<html>
<body>
<p>You can display your {![Link]} cases as a PDF:</p>
<table border="0" >
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
</tr>
<apex:repeat var="cx" value="{![Link]}">
<tr>
<td><a href =
"[Link]
</a></td>
<td>{![Link]}</td>
<td>{![Link]}</td>
<td>{![Link]}</td>
</tr>
</apex:repeat>
</table>
</body>
</html>
</messaging:attachment>

Limitations of the Visualforce PDF rendering service include the following.


PDF is the only supported rendering service.
The PDF rendering service renders PDF version 1.4.
Rendering a Visualforce page as a PDF file is intended for pages designed and optimized for print.
A Visualforce page rendered as a PDF file displays either in the browser or is downloaded, depending on the browsers settings.
Specific behavior depends on the browser, version, and user settings, and is outside the control of Visualforce.
The PDF rendering service renders the markup and data on your page, but it might not render formatting contained within the
contents of rich text area fields added to the page.
Long lines of text that dont have break points, such as a space or dash, cant be wrapped by the PDF rendering service. This most
commonly happens with very long URLs, registry entries, and so on. When these lines are wider than the page, they increase the
width of the pages content beyond the edge of the PDF page. This causes content to flow off the side of the page, cutting it off.
Dont use standard components that arent easily formatted for print, or form elements such as inputs or buttons, or any component
that requires JavaScript to be formatted.
PDF rendering doesnt support JavaScript-rendered content.
PDF rendering isnt supported for pages in Salesforce1.
The font used on the page must be available on the Visualforce PDF rendering service. Web fonts arent supported.

209

Integrating Email with Visualforce

Adding Attachments

If the PDF file fails to display all the pages text, particularly multibyte characters such as Japanese or accented international characters,
adjust your CSS to use a font that supports them. For example:
<apex:page showHeader="false" applyBodyTag="false" renderAs="pdf">
<head>
<style>
body { font-family: 'Arial Unicode MS'; }
</style>
</head>
<body>

<br/>
This is a sample page: API version 28.0
</body>
</apex:page>

Arial Unicode MS is the only font supported for extended character sets that include multibyte characters.
If you use inline CSS styles, set the API version to 28.0 or later. Also set <apex:page applyBodyTag="false">, and add
static, valid <head> and <body> tags to your page, as in the previous example.
The maximum response size when creating a PDF file must be less than 15 MB before being rendered as a PDF file. This limit is the
standard limit for all Visualforce requests.
The maximum file size for a generated PDF file is 60 MB.
The maximum total size of all images included in a generated PDF is 30 MB.
PDF rendering doesnt support images encoded in the data: URI scheme format.
The following components dont support double-byte fonts when rendered as PDF.
<apex:pageBlock>
<apex:sectionHeader>
These components arent recommended for use in pages rendered as PDF.
If an <apex:dataTable> or <apex:pageBlockTable> has no <apex:column> components that are rendered,
rendering the page as PDF fails. To work around this issue, set the table components rendered attribute to false if none of
its child <apex:column> components are rendered.

Adding Styles and Images


Attachments can also use stylesheets to change the way your data is presented. Styles are associated with attachments the same way
as they are in Visualforce email templates, either as inline code, or by using a custom component.
Attachments rendered as PDFs can reference static resources through the $Resource global variable. This enables you to refer to an
image or stylesheet within the body of the PDF.
For example, the following attachment includes a logo in the PDF:
<messaging:attachment renderAs="PDF" filename="[Link]">
<html>
<body>
<img src = "{!$[Link]}" />
...
</body>
</html>
</messaging:attachment>

210

Integrating Email with Visualforce

Using Custom Controllers within Visualforce Email Templates

This attachment references a stylesheet you have saved as a static resource:


<messaging:attachment renderAs="PDF">
<html>
<link rel='stylesheet' type='text/css' href='{!$[Link]}' />
<body>
...
</body>
</html>
</messaging:attachment>

Warning: Referencing static resources on a remote server can increase the time it takes to render a PDF attachment. You cant
reference remote resources when creating PDF attachments in an Apex trigger; doing so will result in an exception.

Using Custom Controllers within Visualforce Email Templates


Visualforce email templates can leverage custom controllers to render highly customized content. To do so, include a custom component
in a Visualforce email template that uses that custom controller.
For example, suppose you want to display a list of all accounts beginning with the word Smith in an email template. To do this, first
write a custom controller that uses a SOSL call to return a list of accounts that begin with Smith:
public class findSmithAccounts {
private final List<Account> accounts;
public findSmithAccounts() {
accounts = [select Name from Account where Name LIKE 'Smith_%'];
}
public List<Account> getSmithAccounts() {
return accounts;
}
}

Next, create a custom component named smithAccounts that uses this controller:
<apex:component controller="findSmithAccounts" access="global">
<apex:dataTable value="{!SmithAccounts}" var="s_account">
<apex:column>
<apex:facet name="header">Account Name</apex:facet>
{!s_account.Name}
</apex:column>
</apex:dataTable>
</apex:component>

Tip: Remember that all custom components used in Visualforce email templates must have an access level of global.
Finally, create a Visualforce email template that includes the smithAccounts component:
<messaging:emailTemplate subject="Embedding Apex Code" recipientType="Contact"
relatedToType="Opportunity">
<messaging:htmlEmailBody>
<p>As you requested, here's a list of all our Smith accounts:</p>
<c:smithAccounts/>
<p>Hope this helps with the {!relatedToType}.</p>

211

Integrating Email with Visualforce

Using Custom Controllers within Visualforce Email Templates

</messaging:htmlEmailBody>
</messaging:emailTemplate>

Notice that although the relatedToType attribute is required by the emailTemplate component, it does not have any effect
on this example. It has the value of "Opportunity" only to show that it can take an object value that is different than the object
used in the custom component.
Note: Sharing settings are enforced if your email templates use a standard controller. If your organization-wide default for the
user object is set to Private and you need to access user information such as name and email address in your Visualforce email
template, you can use a custom component or custom controller with the without sharing keywords.
For information about sharing for the user object, see User Sharing Overview in the Salesforce online help.

212

CHAPTER 15 Visualforce Charting


Visualforce charting is a collection of components that provide a simple and intuitive way to create charts in your Visualforce pages and
custom components.

What is Visualforce Charting?


Visualforce charting gives you an easy way to create customized business charts, based on data sets you create directly from SOQL
queries, or by building the data set in your own Apex code. By combining and configuring individual data series, you can compose charts
that display your data in ways meaningful to your organization.
Visualforce charts are rendered client-side using JavaScript. This allows charts to be animated and visually exciting, and chart data can
load and reload asynchronously, which can make the page feel more responsive.

Why Would You Use Visualforce Charting?


Use Visualforce charting when the standard Salesforce charts and dashboards are insufficient, or when you wish to compose custom
pages that combine charts and data tables in ways that are more useful to your organization.

Alternatives to Visualforce Charting


Salesforce provides a number of dashboards and reports, which support a variety of business charts. These charts can be simpler to
create and customize because they do not require programming in Visualforce or Apex. See Dashboards Help You Visualize Complex
Information for more details about built-in charting and reporting.
Visualforce charting is designed to be flexible, but also easy to use. It offers variations on bar, line, area, and pie charts commonly used
in business graphics, as well as radar, gauge, and scatter charts for more specialized charting. If you need different chart types, or want
to add advanced user or page interactions, you might want to investigate using a JavaScript charting library instead. This is more work,
but allows greater customization. For example, see Integrating Visualforce and Google Charts on page 131. Using JavaScript in Visualforce
Pages on page 299 provides more information about how to use JavaScript libraries with Visualforce.

Visualforce Charting Limitations and Considerations


This section lists considerations and known limitations for Visualforce Charting.
Visualforce charts only render in browsers which support scalable vector graphics (SVG). For more information, see WC3 SVG Working
Group.
Visualforce charting uses JavaScript to draw the charts. Visualforce charts wont display in pages rendered as PDFs.
Email clients do not usually support JavaScript execution in messages. Dont use Visualforce charting in email messages or email
templates.

213

Visualforce Charting

How Visualforce Charting Works

Visualforce charting sends errors and messages to the JavaScript console. Keep a JavaScript debugging tool, such as Firebug, active
during development.
Dynamic (Apex-generated) charting components are not supported at this time.

How Visualforce Charting Works


A Visualforce chart is defined using a series of charting components, which are then linked to a data source to be graphed on the chart.
Create a chart with Visualforce by doing the following:
1. Write an Apex method that queries for, calculates, and wraps your chart data to send to the browser.
2. Define your chart using the Visualforce charting components.
When the page containing the chart loads, the chart data is bound to a chart component, and the JavaScript that draws the chart is
generated. When the JavaScript executes, the chart is drawn in the browser.

A Simple Charting Example


A Visualforce chart requires that you create a chart container component, which encloses at least one data series component. You can
optionally add additional series components, chart axes, as well as labeling components such as a legend, chart labels, and tooltips for
data points.
Here is a simple pie chart and the markup that creates it:

<apex:page controller="PieChartController" title="Pie Chart">


<apex:chart height="350" width="450" data="{!pieData}">
<apex:pieSeries dataField="data" labelField="name"/>
<apex:legend position="right"/>
</apex:chart>
</apex:page>

The <apex:chart> component defines the chart container, and binds the component to the data source, the getPieData()
controller method. The <apex:pieSeries> describes the label and data fields to access in the returned data, to label and size
each data point.
Heres the associated controller:
public class PieChartController {
public List<PieWedgeData> getPieData() {

214

Visualforce Charting

Providing Chart Data

List<PieWedgeData> data = new List<PieWedgeData>();


[Link](new PieWedgeData('Jan', 30));
[Link](new PieWedgeData('Feb', 15));
[Link](new PieWedgeData('Mar', 10));
[Link](new PieWedgeData('Apr', 20));
[Link](new PieWedgeData('May', 20));
[Link](new PieWedgeData('Jun', 5));
return data;
}
// Wrapper class
public class PieWedgeData {
public String name { get; set; }
public Integer data { get; set; }
public PieWedgeData(String name, Integer data) {
[Link] = name;
[Link] = data;
}
}
}

This controller is deliberately simple; you normally issue one or more SOQL queries to collect your data.
These are the important points illustrated by the example:
The getPieData() method returns a List of simple objects, an inner class PieWedgeData used as a wrapper. Each element in
the list is used to create a data point.
The PieWedgeData class is just a set of properties, and is essentially used as a name=value store.
The chart series component <apex:pieSeries> defines which properties from the PieWedgeData class to use to determine
each point in the series. In this simple example theres no mystery, but in charts with multiple series and axes this convention allows
the efficient return of the entire data set in one List object.

Providing Chart Data


A Visualforce chart binds to the source of its data through the data attribute on the <apex:chart> component.
Data can be provided several different ways:
As an expression that represents a controller method reference
As a string representing a JavaScript function
As a string representing a JavaScript array
SEE ALSO:
Providing Chart Data via a Controller Method
Providing Chart Data Using a JavaScript Function
Providing Chart Data via a JavaScript Array
Chart Data Format

215

Visualforce Charting

Providing Chart Data

Providing Chart Data via a Controller Method


The most straightforward way to provide data to a chart is using a Visualforce expression that references a controller method. Simply
reference the controller in the <apex:chart> data attribute.
On the server side, write a controller method that returns a List of objects, which can be your own Apex wrapper objects as in A Simple
Charting Example on page 214, sObjects, or AggregateResult objects. The method is evaluated server-side, and the results serialized
to JSON. On the client, these results are used directly by <apex:chart>, with no further opportunity for processing.
To illustrate this technique with sObjects, here is a simple controller that returns a list of Opportunities, and a bar chart for their amounts:
public class OppsController {
// Get a set of Opportunities
public [Link] setCon {
get {
if(setCon == null) {
setCon = new [Link]([Link](
[SELECT name, type, amount, closedate FROM Opportunity]));
[Link](5);
}
return setCon;
}
set;
}
public List<Opportunity> getOpportunities() {
return (List<Opportunity>) [Link]();
}
}
<apex:page controller="OppsController">
<apex:chart data="{!Opportunities}" width="600" height="400">
<apex:axis type="Category" position="left" fields="Name" title="Opportunities"/>
<apex:axis type="Numeric" position="bottom" fields="Amount" title="Amount"/>
<apex:barSeries orientation="horizontal" axis="bottom"
xField="Name" yField="Amount"/>
</apex:chart>
<apex:dataTable value="{!Opportunities}" var="opp">
<apex:column headerValue="Opportunity" value="{![Link]}"/>
<apex:column headerValue="Amount" value="{![Link]}"/>
</apex:dataTable>
</apex:page>

216

Visualforce Charting

Providing Chart Data

There are two important things to notice about this example:


The Visualforce chart components access the data attributes from a List of Opportunity sObjects the same way as from the simple
Data object used in A Simple Charting Example on page 214.
The object field names used as data attributes are case-sensitive in JavaScript while field names in Apex and Visualforce are
case-insensitive. Be careful to use the precise field name in the fields, xField, and yField attributes of axes and data series
components, or your chart will silently fail.
SEE ALSO:
Chart Data Format
Refreshing Chart Data Using <apex:actionSupport>

Providing Chart Data Using a JavaScript Function


To access data using JavaScript remoting, or an external (non-Salesforce) data source, provide the <apex:chart> component with
the name of a JavaScript function that provides the data. That JavaScript function must be defined in or linked from your Visualforce
page.
This function has the opportunity to manipulate the results before passing it to <apex:chart>, or to perform other user interface
or page updates.
The JavaScript function must take a callback function as a parameter, and invoke the callback with the function's data result object. The
simplest working JavaScript function looks like this:
<apex:page>
<script>
function getRemoteData(callback) {
[Link](function(result, event) {
if([Link] && result && [Link] === Array) {
callback(result);
}
});
}
</script>
<apex:chart data="getRemoteData" ...></apex:chart>
</apex:page>

217

Visualforce Charting

Providing Chart Data

To support this chart, add the following controller method to the PieChartController class defined in A Simple Charting Example
on page 214:
@RemoteAction
public static List<PieWedgeData> getRemotePieData() {
List<PieWedgeData> data = new List<PieWedgeData>();
[Link](new PieWedgeData('Jan', 30));
[Link](new PieWedgeData('Feb', 15));
[Link](new PieWedgeData('Mar', 10));
[Link](new PieWedgeData('Apr', 20));
[Link](new PieWedgeData('May', 20));
[Link](new PieWedgeData('Jun', 5));
return data;
}

SEE ALSO:
Chart Data Format
JavaScript Remoting for Apex Controllers
Refreshing Chart Data Using JavaScript Remoting

Providing Chart Data via a JavaScript Array


You can use Visualforce charting with non-Salesforce data sources by building a JavaScript array, in your own JavaScript code in your
page, and providing the name of that array to <apex:chart>.
The following trivial code illustrates this technique:
<apex:page>
<script>
// Build the chart data array in JavaScript
var dataArray = new Array();
[Link]({'data1':33,'data2':66,'data3':80,'name':'Jan'});
[Link]({'data1':33,'data2':66,'data3':80,'name':'Feb'});
// ...
</script>
<apex:chart data="dataArray" ...></apex:chart>
</apex:page>

When using this technique, if your data is coming from a non-Salesforce source, you might not need any server-side Apex code at all.
SEE ALSO:
Chart Data Format

Chart Data Format


Data provided to a Visualforce chart must meet some specific requirements. Every element in the data collection must contain all fields
referenced in the <apex:chart> component hierarchy that is bound to that data source. If all fields arent provided, a client-side
JavaScript error is thrown, which you can view in a JavaScript console such as Firebug.
Chart data provided by an Apex method should be a List of uniform objects. These objects can be simple wrappers, sObjects, or
AggregateResult objects. Data fields can be made accessible as public member variables or properties.

218

Visualforce Charting

Building a Complex Chart with Visualforce Charting

Chart data provided by JavaScript methods should be a JavaScript array of arrays. Each inner array represents a record or data point. Data
fields are made accessible as name: value pairs. See Providing Chart Data via a JavaScript Array on page 218 for an example.
SEE ALSO:
Providing Chart Data via a JavaScript Array

Building a Complex Chart with Visualforce Charting


Use Visualforce charting to assemble a variety of chart components into a complex chart that represents multiple sets of related data.
The end result can be quite sophisticated and attention getting.

The Chart Controller


The examples later in this topic use the following controller, which is a modest expansion of the controller in A Simple Charting Example.
It includes more data, and methods that can be called by remote JavaScript invocation:
public class ChartController {
// Return a list of data points for a chart
public List<Data> getData() {
return [Link]();
}
// Make the chart data available via JavaScript remoting
@RemoteAction
public static List<Data> getRemoteData() {
return [Link]();
}
// The actual chart data; needs to be static to be
// called by a @RemoteAction method
public static List<Data> getChartData() {
List<Data> data = new List<Data>();
[Link](new Data('Jan', 30, 90, 55));
[Link](new Data('Feb', 44, 15, 65));
[Link](new Data('Mar', 25, 32, 75));
[Link](new Data('Apr', 74, 28, 85));
[Link](new Data('May', 65, 51, 95));
[Link](new Data('Jun', 33, 45, 99));
[Link](new Data('Jul', 92, 82, 30));
[Link](new Data('Aug', 87, 73, 45));
[Link](new Data('Sep', 34, 65, 55));
[Link](new Data('Oct', 78, 66, 56));
[Link](new Data('Nov', 80, 67, 53));
[Link](new Data('Dec', 17, 70, 70));
return data;
}
// Wrapper class
public class Data {
public String name { get; set; }
public Integer data1 { get; set; }

219

Visualforce Charting

Building a Complex Chart with Visualforce Charting

public Integer data2 { get; set; }


public Integer data3 { get; set; }
public Data(String name, Integer data1, Integer data2, Integer data3) {
[Link] = name;
this.data1 = data1;
this.data2 = data2;
this.data3 = data3;
}
}
}

Note: The @RemoteAction method isnt used in the chart examples in this topic, but it illustrates how you can re-use your
data generation method for both server-side and JavaScript remoting methods.

Creating a Simple Line Chart


Here is a simple line chart that graphs one of the three data series in the data set, Opportunities Closed-Won, over a calendar year:

<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
</apex:axis>
<apex:lineSeries axis="left" fill="true" xField="name" yField="data1"
markerType="cross" markerSize="4" markerFill="#FF0000"/>
</apex:chart>
</apex:page>

Things to note about this example:


Line and bar charts require you to define the X and Y axes for the chart.
The vertical axis is defined on the left side of the chart, and measures the dollar amount of the Opportunities closed in that month.
The horizontal axis is defined on the bottom of the chart, and represents the months of the calendar year.
The actual line chart, the <apex:lineSeries> component, is bound to a specific axis.

220

Visualforce Charting

Building a Complex Chart with Visualforce Charting

There are a number of marker attributes that you can use to differentiate each line in the chart.

Adding a Second Data Series


Adding a second data series with the same unit of measure is simple. Here, the Opportunities Closed-Lost data set is added as a second
line series:

<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1,data2"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
</apex:axis>
<apex:lineSeries axis="left" fill="true" xField="name" yField="data1"
markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries axis="left" xField="name" yField="data2"
markerType="circle" markerSize="4" markerFill="#8E35EF"/>
</apex:chart>
</apex:page>

The important thing to note is how both data1 and data2 fields are bound to the vertical <apex:axis> by the fields attribute
of that component. This allows the charting engine to determine appropriate scale and tick marks for the axis.

Adding a Bar Chart Series with a Second Axis


To add another data series, but charted against a different set of units, you need to add a second vertical axis. The following example
shows a data series, Revenue by Month, added as a bar chart:

221

Visualforce Charting

Building a Complex Chart with Visualforce Charting

<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1,data2"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Numeric" position="right" fields="data3"
title="Revenue (millions)"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year"/>
<apex:lineSeries axis="left" fill="true" xField="name" yField="data1"
markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries axis="left" xField="name" yField="data2"
markerType="circle" markerSize="4" markerFill="#8E35EF"/>
<apex:barSeries orientation="vertical" axis="right"
xField="name" yField="data3"/>
</apex:chart>
</apex:page>

Notice the following:


To add a data series with a new unit of measure, you need to add a second vertical axis on the right side of the chart.
You can have up to four different axes, one for each edge of the chart.
The bar chart is set to a vertical orientation and bound to the right axis. Bind a horizontal bar chart to the top or bottom axis.

Adding a Legend, Labels, and Chart Tips


You can improve the comprehensibility of the chart by adding a chart legend, series labels, and by making sure that chart labels are
readable:

222

Visualforce Charting

Building a Complex Chart with Visualforce Charting

<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:legend position="right"/>
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Numeric" position="right" fields="data3"
title="Revenue (millions)"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:barSeries title="Monthly Sales" orientation="vertical" axis="right"
xField="name" yField="data3">
<apex:chartTips height="20" width="120"/>
</apex:barSeries>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"
fill="true" markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries title="Closed-Lost" axis="left" xField="name" yField="data2"
markerType="circle" markerSize="4" markerFill="#8E35EF"/>
</apex:chart>
</apex:page>

Note the following about the additions:


The order of the data series components determines the layering of the chart elements when drawn. In the prior example, the bar
chart was in the foreground. In this example, the bar chart has been placed in the background because the <apex:barSeries>
component is before the two <apex:lineSeries> components.
The <apex:legend> component can be in any of four positions: left, right, top, or bottom. The legend is placed within the
boundary of the chart; in this example the legend has compressed the horizontal width of the chart itself.
Add legend titles using the data series component title attribute.
To rotate the labels for the bottom chart axis, the <apex:chartLabel> component is enclosed in the <apex:axis>
component it affects.

223

Visualforce Charting

Updating Charts with Refreshed Data

The <apex:chartTips> component enables rollover tool tips that provide additional information about each data point in
the series that encloses it.
SEE ALSO:
How Visualforce Charting Works

Updating Charts with Refreshed Data


Redraw a chart with new or updated data by using the <apex:actionSupport> component, or by using JavaScript remoting
and your own JavaScript code.
<apex:actionSupport> allows you to update the chart using only Visualforce. JavaScript remoting requires you to write some

JavaScript code, but provides more flexibility and smoother transitions.


IN THIS SECTION:
Refreshing Chart Data Using <apex:actionSupport>
Update a Visualforce chart in response to a users actions by adding the <apex:actionSupport> component to Visualforce
user interface elements that affect the charts data.
Refreshing Chart Data Using JavaScript Remoting
Update a Visualforce chart periodically, or in response to a users actions, using custom JavaScript. JavaScript code can respond to
complex user activity or timer events, and use JavaScript remoting to retrieve new chart data whenever required.

Refreshing Chart Data Using <apex:actionSupport>


Update a Visualforce chart in response to a users actions by adding the <apex:actionSupport> component to Visualforce user
interface elements that affect the charts data.
The following markup displays a pie chart that can be updated by choosing a new year from a menu next to the chart:
<apex:page controller="PieChartRemoteController">
<apex:pageBlock title="Charts">
<apex:pageBlockSection title="Standard Visualforce Charting">
<apex:outputPanel id="theChart">
<apex:chart height="350" width="450" data="{!pieData}">
<apex:pieSeries dataField="data" labelField="name"/>
<apex:legend position="right"/>
</apex:chart>
</apex:outputPanel>
<apex:form>
<apex:selectList value="{!chartYear}" size="1">
<apex:selectOptions value="{!chartYearOptions}"/>
<apex:actionSupport event="onchange" reRender="theChart"
status="actionStatusDisplay"/>
</apex:selectList>
<apex:actionStatus id="actionStatusDisplay"
startText="loading..." stopText=""/>
</apex:form>

224

Visualforce Charting

Refreshing Chart Data Using <apex:actionSupport>

</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

This markup attaches a chart component to its data source by setting the charts data attribute to the Visualforce expression
{!pieData}. The expression calls the getPieData() controller method, which returns the data. The chart is wrapped in an
<apex:outputPanel> with an id attribute of theChart.
An <apex:form> component is used to submit a new year back to the pages controller when the chart needs to be updated. The
<apex:selectList> tag displays the years available to chart, and a child <apex:actionSupport> tag submits the form
whenever the menu changes. The id of the charts <apex:outputPanel>, theChart, is used in the
<apex:actionSupport> reRender attribute to limit updating to the chart, instead of reloading the whole page. Finally, an
<apex:actionStatus> component provides a status message while the chart is refreshing. Its easy to replace the minimal text
message with an animated graphic or text effect.

PieChartRemoteController
The controller for this page is an expansion of the pie chart controller used in A Simple Charting Example on page 214.
public class PieChartRemoteController {
// The year to be charted
public String chartYear {
get {
if (chartYear == Null) chartYear = '2013';
return chartYear;
}
set;
}
// Years available to be charted, for <apex:selectList>
public static List<SelectOption> getChartYearOptions() {
List<SelectOption> years = new List<SelectOption>();
[Link](new SelectOption('2013','2013'));
[Link](new SelectOption('2012','2012'));
[Link](new SelectOption('2011','2011'));
[Link](new SelectOption('2010','2010'));
return years;
}
public List<PieWedgeData> getPieData() {
// Visualforce expressions can't pass parameters, so get from property
return [Link]([Link]);
}
@RemoteAction
public static List<PieWedgeData> getRemotePieData(String year) {
// Remoting calls can send parameters with the call
return [Link](year);
}
// Private data "generator"

225

Visualforce Charting

Refreshing Chart Data Using JavaScript Remoting

private static List<PieWedgeData> generatePieData(String year) {


List<PieWedgeData> data = new List<PieWedgeData>();
if([Link]('2013')) {
// These numbers are absolute quantities, not percentages
// The chart component will calculate the percentages
[Link](new PieWedgeData('Jan', 30));
[Link](new PieWedgeData('Feb', 15));
[Link](new PieWedgeData('Mar', 10));
[Link](new PieWedgeData('Apr', 20));
[Link](new PieWedgeData('May', 20));
[Link](new PieWedgeData('Jun', 5));
}
else {
[Link](new PieWedgeData('Jan', 20));
[Link](new PieWedgeData('Feb', 35));
[Link](new PieWedgeData('Mar', 30));
[Link](new PieWedgeData('Apr', 40));
[Link](new PieWedgeData('May', 5));
[Link](new PieWedgeData('Jun', 10));
}
return data;
}
// Wrapper class
public class PieWedgeData {
public String name { get; set; }
public Integer data { get; set; }
public PieWedgeData(String name, Integer data) {
[Link] = name;
[Link] = data;
}
}
}

This controller supports providing data to a Visualforce chart two different ways:
Using a Visualforce expression, {!pieData}, which calls the instance method getPieData().
Using JavaScript remoting, by calling the @RemoteAction static method getRemotePieData() from a JavaScript method.
SEE ALSO:
Refreshing Chart Data Using JavaScript Remoting
Providing Chart Data via a Controller Method
apex:actionSupport
apex:actionStatus

Refreshing Chart Data Using JavaScript Remoting


Update a Visualforce chart periodically, or in response to a users actions, using custom JavaScript. JavaScript code can respond to complex
user activity or timer events, and use JavaScript remoting to retrieve new chart data whenever required.

226

Visualforce Charting

Refreshing Chart Data Using JavaScript Remoting

The following markup displays a pie chart that can be updated by choosing a new year from a menu next to the chart:
<apex:page controller="PieChartRemoteController">
<script>
function retrieveChartData(callback) {
var year = [Link]('theYear').value;
[Link](
'{!$[Link]}',
year,
function(result, event) {
if([Link] && result && ([Link] === Array)) {
callback(result);
[Link]();
}
else if ([Link] === 'exception') {
[Link]("remoteResponseErrors").innerHTML = [Link]
+
'<br/>' + [Link];
}
else {
[Link]("remoteResponseErrors").innerHTML = [Link];
}
},
{ escape: true }
);
}
function refreshRemoteChart() {
var statusElement = [Link]('statusDisplay');
[Link] = "loading...";
retrieveChartData(function(statusElement){
return function(data){
[Link](data);
[Link] = '';
};
}(statusElement)
);
}
</script>
<apex:pageBlock title="Charts">
<apex:pageBlockSection title="Visualforce Charting + JavaScript Remoting">
<apex:chart height="350" width="450" data="retrieveChartData"
name="RemotingPieChart" hidden="true">
<apex:pieSeries dataField="data" labelField="name"/>
<apex:legend position="right"/>
</apex:chart>
<div>
<select id="theYear" onChange="refreshRemoteChart();">
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>

227

Visualforce Charting

Refreshing Chart Data Using JavaScript Remoting

<option value="2010">2010</option>
</select>
<span id="statusDisplay"></span>
<span id="remoteResponseErrors"></span>
</div>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

This markup attaches a chart component to its data source by setting the charts data attribute to the name of a JavaScript function,
retrieveChartData, which returns the data. The name of the function is provided as a string.
A static HTML <select> menu displays the years available to chart. The menu is not associated with a form element of any kind, and
its value is never submitted directly back to the controller. Instead, the <select> menus onChange attribute calls a JavaScript
function, refreshRemoteChart(), whenever the menu changes. There are two additional static HTML elements: two <span>
tags with IDs. The <span> tags are empty when the page loads, and are updated via JavaScript to display status and error messages
when necessary.
The two JavaScript functions that precede the Visualforce markup are the glue between the Visualforce chart and the @RemoteAction
controller method that provides the data. There are three links between the functions and the chart component:
1. The chart components data attribute is set to retrieveChartData, the name of the first JavaScript function. This tells the chart
component to use the JavaScript function to load its data. The chart component invokes retrieveChartData() directly
only once, when the chart is first created and the data is initially loaded.
2. Reloading happens when the second JavaScript function, refreshRemoteChart(), is called. This is the second link, from the
theYear menu. When the year menu changes, refreshRemoteChart() is invoked, and it re-invokes the
retrieveChartData() function to load a new set of data.
3. When refreshRemoteChart() invokes retrieveChartData(), it provides an anonymous function as a callback,
which handles the result of the @RemoteAction call when it returns. This callback updates the chart by calling
[Link](data). The chart itself is RemotingPieChart, named by setting the name attribute,
and reload() is a JavaScript function available on Visualforce charts once created, which accepts new data and then redraws
the chart.
This diagram illustrates these links between the different components of the page:

228

Visualforce Charting

Refreshing Chart Data Using JavaScript Remoting

The sequence for the initial loading of the chart is simple: the <apex:chart> named RemotePieChart calls
retrieveChartData() to get its initial data, and retrieveChartData() calls [Link]() when it
has the data. And, the chart appears.
Updates are more complicated. When a new year is chosen from the theYear menu, the menus onChange event fires, which calls
the refreshRemoteChart() function. refreshRemoteChart() in turn calls the retrieveChartData() function,
and when the @RemoteAction returns new data, retrieveChartData() (via the callback provided by
refreshRemoteChart()) calls [Link](). And, the chart updates.
Here are a couple of other items to note:
The <apex:chart> uses the hidden="true" attribute to prevent the chart from displaying before theres data to display.
The retrieveChartData() function calls [Link]() to display the chart once the chart data is
loaded. This and [Link]() provide for much smoother chart animations than can be achieved using
<apex:actionSupport>.
The refreshRemoteData() function sets the statusElement HTML <span> to a loading message before it
attempts to update the data by calling retrieveChartData(), and then the anonymous callback function sets it to an empty
string to hide the message once the data is returned and the chart updated. Its a bit more work than using
<apex:actionStatus>, for basically the same effect. You can easily show a busy animation or graphic using the same
technique.

PieChartRemoteController
The controller for this page is an expansion of the pie chart controller used in A Simple Charting Example on page 214.
public class PieChartRemoteController {
// The year to be charted
public String chartYear {
get {

229

Visualforce Charting

Refreshing Chart Data Using JavaScript Remoting

if (chartYear == Null) chartYear = '2013';


return chartYear;
}
set;
}
// Years available to be charted, for <apex:selectList>
public static List<SelectOption> getChartYearOptions() {
List<SelectOption> years = new List<SelectOption>();
[Link](new SelectOption('2013','2013'));
[Link](new SelectOption('2012','2012'));
[Link](new SelectOption('2011','2011'));
[Link](new SelectOption('2010','2010'));
return years;
}
public List<PieWedgeData> getPieData() {
// Visualforce expressions can't pass parameters, so get from property
return [Link]([Link]);
}
@RemoteAction
public static List<PieWedgeData> getRemotePieData(String year) {
// Remoting calls can send parameters with the call
return [Link](year);
}
// Private data "generator"
private static List<PieWedgeData> generatePieData(String year) {
List<PieWedgeData> data = new List<PieWedgeData>();
if([Link]('2013')) {
// These numbers are absolute quantities, not percentages
// The chart component will calculate the percentages
[Link](new PieWedgeData('Jan', 30));
[Link](new PieWedgeData('Feb', 15));
[Link](new PieWedgeData('Mar', 10));
[Link](new PieWedgeData('Apr', 20));
[Link](new PieWedgeData('May', 20));
[Link](new PieWedgeData('Jun', 5));
}
else {
[Link](new PieWedgeData('Jan', 20));
[Link](new PieWedgeData('Feb', 35));
[Link](new PieWedgeData('Mar', 30));
[Link](new PieWedgeData('Apr', 40));
[Link](new PieWedgeData('May', 5));
[Link](new PieWedgeData('Jun', 10));
}
return data;
}
// Wrapper class
public class PieWedgeData {

230

Visualforce Charting

Controlling the Appearance of Charts

public String name { get; set; }


public Integer data { get; set; }
public PieWedgeData(String name, Integer data) {
[Link] = name;
[Link] = data;
}
}
}

This controller supports providing data to a Visualforce chart two different ways:
Using a Visualforce expression, {!pieData}, which calls the instance method getPieData().
Using JavaScript remoting, by calling the @RemoteAction static method getRemotePieData() from a JavaScript method.
SEE ALSO:
Refreshing Chart Data Using <apex:actionSupport>
Providing Chart Data Using a JavaScript Function
JavaScript Remoting for Apex Controllers

Controlling the Appearance of Charts


Visualforce charts are highly customizable. You can combine various types of data series, control the colors of most elements in a chart,
and control the look of markers, lines, and so on.
You can customize the following:
Line and fill colors for data series elements.
Opacity of fill colors and lines.
Marker shape and color for data points.
Line width for connecting lines.
Highlighting for data elements.
Tick and grid line styles for axes.
Legends, labels, and tool tip-style rollover annotations.
Many of the components and attributes that provide this control are explained in the Standard Component Reference. Some effects
require combinations of attributes and components, and are explained more completely in this document.

Chart Colors
By default, chart colors match those of the built-in reporting and analytics charts so that you can create visually-consistent dashboards.
If you want to create your own color scheme you can customize the colors of most chart elements.
To provide a set of color definitions to draw data series elements (bars, pie wedges, and so on), use the colorSet attribute. Set
<apex:chart colorSet="..."> to specify the colors to be used for every data series in a chart. Set colorSet on a data
series component to specify colors for that series only.
A colorSet is a string that is a comma-delimited list of HTML-style hexadecimal color definitions. For example,
colorSet="#0A224E,#BF381A,#A0D8F1,#E9AF32,#E07628". Colors are used in sequence. When the end of the list
is reached, the sequence starts over at the beginning.

231

Visualforce Charting

Chart Layout and Annotation

Heres a pie chart that uses a custom color scheme for the pie wedge colors:

<apex:pageBlockSection title="Simple colorSet Demo">


<apex:chart data="{!pieData}" height="300" width="400" background="#F5F5F5">
<apex:legend position="left"/>
<apex:pieSeries labelField="name" dataField="data1"
colorSet="#37241E,#94B3C8,#4D4E24,#BD8025,#816A4A,#F0E68C"/>
</apex:chart>
</apex:pageBlockSection>

Use the background attribute to set a background color for the entire chart.
You can use a colorSet with all data series components except <apex:radarSeries>. Additional colorSet details and
further options for configuring colors of other chart elements are described for specific data series components.

Chart Layout and Annotation


To make your chart more understandable, add a legend, meaningful axes ranges and labels, and tips or labels on data elements.
By default all charts have a legend. To suppress the default legend, set <apex:chart legend="false">. To control the
placement of the legend and the spacing of legend entries, add an <apex:legend> component to the chart. Place the legend on
any of the four edges of a chart using the position attribute. Use the font attribute to control the text style used in the legend.
The font attribute is a string specifying a CSS-style shorthand font property. For example, <apex:legend position="left"
font="bold 24px Helvetica"/>.
Appropriate axis scaling and labeling can mean the difference between a chart that is illegible or misleading and one that is clear and
persuasive. By default, an <apex:axis type="Numeric"> component sets the scale automatically based on the data fields set
in the fields attribute. Automatic scaling ensures that all data fits on the chart but the chart might not begin or end with meaningful
numbers. Use the minimum and maximum attributes to override the automatic scaling. To set the interval for tick marks, use the
steps attribute. This attribute is an integer that specifies the number of steps between the two ends of the axis. Use the dashSize,
grid, and gridFill attributes to add lines or shading to the chart to make it easier to compare measurements to the scale.
You can apply chart labels to axes and data series. When <apex:chartLabel> is a child of <apex:axis>, the labels are drawn
on the outside of the axis. When <apex:chartLabel> is a child of a data series component, the labels are drawn on or near the
data elements on the chart. Use the field attribute to set the text for the label. Use the display attribute to set where the label
is drawn. Use the orientation and rotate attributes to adjust the text of the label so that it fits on the chart.
Note: The orientation attribute has no effect when a <apex:chartLabel> component is used with a
<apex:pieSeries> component.
This sample chart uses many of these components and attributes to create a meaningful visual design:

232

Visualforce Charting

Bar Charts

<apex:chart data="{!data}" height="400" width="500">


<apex:legend position="left" font="bold 14px Helvetica"/>
<apex:axis type="Numeric" position="left" title="Closed Won" grid="true"
fields="data1,data2,data3" minimum="0" maximum="225" steps="8" dashSize="2">
<apex:chartLabel />
</apex:axis>
<apex:axis type="Category" position="bottom" fields="name" title="2012">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:barSeries orientation="vertical" axis="left"
xField="name" yField="data1,data2,data3" stacked="true"/>
</apex:chart>

Bar Charts
Bar charts are one of several linear data series charts available in Visualforce. Linear series charts are charts plotted against a standard
rectangular grid.
Each data element in a linear series is described by an X,Y coordinate. The data series defines how to draw the coordinate on the grid.
The <apex:barSeries> charts draw bars stretching between an origin axis and the X,Y coordinates. The orientation
attribute determines whether the origin axis is the left axis (Y) or the bottom axis (X). Set <apex:barSeries
orientation="horizontal"> for bars that originate on the left side of the chart, and <apex:barSeries
orientation="vertical"> for a column chart with bars that rise from the bottom of the chart.
To plot multiple data points for each bar interval, group or stack the bars within a single <apex:barSeries> tag. Multiple
<apex:barSeries> tags in a single chart draw on top of each other, obscuring all but the last data series. To create a vertical
column chart, add all fields to be grouped or stacked to the yField attribute:
<apex:barSeries orientation="vertical" axis="left"
xField="name" yField="data1,data2,data3"/>

By default, data fields in an <apex:barSeries> are grouped on a chart. To stack them on top of each other, set stacked="true".

233

Visualforce Charting

Bar Charts

Use the gutter attribute to adjust spacing between grouped bars. Use the groupGutter attribute to adjust spacing between
groups. Use the xPadding and yPadding attributes to adjust the spacing between the chart axes and the bars themselves.
By default, legend titles for stacked or grouped bar charts use the names of fields in the yField attribute. In the previous example,
the default titles are data1, data2, and data3. To give the legend more meaningful titles, use the title attribute of the
<apex:barSeries> component. Use commas to separate items. For example, title="MacDonald,Promas,Worle":

<apex:chart data="{!data}" height="400" width="500">


<apex:legend position="left"/>
<apex:axis type="Numeric" position="left" title="Closed Won" grid="true"
fields="data1,data2,data3" dashSize="2">
<apex:chartLabel/>
</apex:axis>
<apex:axis type="Category" position="bottom" fields="name" title="Stacked Bars">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:barSeries orientation="vertical" axis="left" stacked="true"

234

Visualforce Charting

Other Linear Series Charts

xField="name" yField="data1,data2,data3" title="MacDonald,Promas,Worle"/>


</apex:chart>

SEE ALSO:
Chart Colors
Chart Layout and Annotation

Other Linear Series Charts


Other linear data series charts include <apex:areaSeries>, <apex:lineSeries>, and <apex:scatterSeries>.
You can combine linear data series charts on the same graph, but to create meaningful charts, keep the following in mind:
Data series charts draw on top of each other in the order you define them in Visualforce markup.
Define <apex:barSeries> charts first because they usually need to be in the background because they cant be transparent.
The <apex:areaSeries> components are similar to stacked bar charts, except that the chart is drawn as shaded areas defined
by a line connecting the points of the series instead of as individual bars. To combine <apex:areaSeries> with other data series,
use the opacity attribute to make the area chart partially transparent. The opacity attribute is a floating point number between
0.0 and 1.0, with 0.0 being fully transparent and 1.0 being fully opaque. Heres an area series combined with a bar series:

<apex:chart height="400" width="700" animate="true" data="{!data}">


<apex:legend position="left"/>
<apex:axis type="Numeric" position="left" title="Closed Won" grid="true"
fields="data1,data2,data3">
<apex:chartLabel />
</apex:axis>
<apex:axis type="Numeric" position="right" fields="data1"
title="Closed Lost" />
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:areaSeries axis="left" tips="true" opacity="0.4"
xField="name" yField="data1,data2,data3"/>

235

Visualforce Charting

Other Linear Series Charts

<apex:barSeries orientation="vertical" axis="right"


xField="name" yField="data1">
<apex:chartLabel display="insideEnd" field="data1" color="#333"/>
</apex:barSeries>
</apex:chart>

By default, legend titles for area charts use the names of fields in the yField attribute. In the previous example, the default titles are
data1, data2, and data3. To give the legend more meaningful titles, use the title attribute of the <apex:areaSeries>
component. Use commas to separate items. For example, title="MacDonald,Promas,Worle":

<apex:chart height="400" width="700" animate="true" data="{!data}">


<apex:legend position="left"/>
<apex:axis type="Numeric" position="left" fields="data1,data2,data3"
title="Closed Won" grid="true">
<apex:chartLabel />
</apex:axis>
<apex:axis type="Category" position="bottom" fields="name" title="2011">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:areaSeries axis="left" xField="name" tips="true"
yField="data1,data2,data3" title="MacDonald,Picard,Worlex" />
</apex:chart>

Like <apex:areaSeries> charts, <apex:lineSeries> charts use lines to connect a series of points. You can fill the area
under the line. Unlike <apex:areaSeries> charts, <apex:lineSeries>charts dont stack. When
<apex:lineSeries>charts arent filled, you might choose to put several series in the same chart. Line series can display markers
for the data points and you can define the color and size of both the markers and the connecting lines. Heres a chart that combines
three line series, one of which is filled:

236

Visualforce Charting

Pie Charts

<apex:chart height="400" width="700" animate="true" legend="true" data="{!data}">


<apex:legend position="left"/>
<apex:axis type="Numeric" position="left" title="Volatility" grid="true"
fields="data1,data2,data3">
<apex:chartLabel />
</apex:axis>
<apex:axis type="Category" position="bottom" title="Month" grid="true"
fields="name">
<apex:chartLabel />
</apex:axis>
<apex:lineSeries axis="left" xField="name" yField="data1"
strokeColor="#0000FF" strokeWidth="4"/>
<apex:lineSeries axis="left" fill="true" xField="name" yField="data2"
markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries axis="left" xField="name" yField="data3"
markerType="circle" markerSize="4" markerFill="#8E35EF">
<apex:chartTips height="20" width="120"/>
</apex:lineSeries>
</apex:chart>

Note: An <apex:lineSeries> component might not fill as expected if a Numeric axis doesnt increase in order as it moves
up and to the right. The solution is to set the axis to type="Category" and sort the values manually before passing the data
to the chart.
The <apex:scatterSeries> charts are like <apex:lineSeries> charts without the connecting lines. By varying the marker
size, type, and color, its easy to plot many scatter series on the same chart.
SEE ALSO:
Chart Colors
Chart Layout and Annotation

Pie Charts
The most common customizations to <apex:pieSeries> charts is to colors and labels. Use the colorSet attribute and the
<apex:chartLabel> component that were demonstrated in previous examples.

237

Visualforce Charting

Gauge Charts

To create a ring chart instead of a pie chart, set the donut attribute. The donut attribute is an integer between 0 and 100 and
represents the percentage of the radius of the hole. Heres a simple ring chart:

<apex:chart data="{!pieData}" height="400" width="500" background="#F5F5F5">


<apex:legend position="left"/>
<apex:pieSeries labelField="name" dataField="data1" donut="50">
<apex:chartLabel display="middle" orientation="vertical"
font="bold 18px Helvetica"/>
</apex:pieSeries>
</apex:chart>

SEE ALSO:
Chart Colors
Chart Layout and Annotation

Gauge Charts
Gauge charts show a single measurement against a defined axis or scale. Although it charts a single number, you can vary the axis and
chart colors to communicate what that number means.
Use the minimum and maximum attributes of the <apex:axis> tag to define the range of values. Use the colorSet attribute
of the <apex:gaugeSeries> tag to indicate whether the current value is good or bad. Heres a chart that indicates the metric is
well within an acceptable range:

238

Visualforce Charting

Radar Charts

<apex:chart height="250" width="450" animate="true" data="{!data}">


<apex:axis type="Gauge" position="gauge" title="Transaction Load"
minimum="0" maximum="100" steps="10"/>
<apex:gaugeSeries dataField="data1" donut="50" colorSet="#78c953,#ddd"/>
</apex:chart>

Note: Gauge charts dont support legends or labels.

SEE ALSO:
Chart Colors
Chart Layout and Annotation

Radar Charts
Radar charts are like line charts but they use a circular axis instead of a linear grid.
Use the markerType, markerSize, and markerFill attributes to set the style, size, and color of the markers. Use the
strokeColor and strokeWidth attributes to set the color and thickness of the connecting lines. Optionally, set fill=true
to fill the area enclosed by the series, and use opacity to make it transparent so that other series remain visible. The opacity
attribute is a floating point number between 0.0 and 1.0, with 0.0 being fully transparent and 1.0 being fully opaque.
Heres an example of a radar chart, and the markup that creates it:

239

Visualforce Charting

Radar Charts

<apex:chart height="530" width="700" legend="true" data="{!data}">


<apex:legend position="left"/>
<apex:axis type="Radial" position="radial">
<apex:chartLabel />
</apex:axis>
<apex:radarSeries xField="name" yField="data1" tips="true" opacity="0.4"/>
<apex:radarSeries xField="name" yField="data2" tips="true" opacity="0.4"/>
<apex:radarSeries xField="name" yField="data3" tips="true"
markerType="cross" strokeWidth="2" strokeColor="#f33" opacity="0.4"/>
</apex:chart>

SEE ALSO:
Chart Colors
Chart Layout and Annotation

240

CHAPTER 16 Creating Maps with Visualforce


Maps communicate information more clearly than mere location data. Visualforce mapping components make it simple to create maps
that use third-party mapping services. Visualforce maps are interactive, JavaScript-based maps, complete with zooming, panning, and
markers based on your Salesforce or other data. Create standalone map pages, maps that you can insert into page layouts, and even
mobile maps for Salesforce1.
Visualforce provides a set of related mapping components. The <apex:map> component defines the map canvas, including size,
type, center point, and initial zoom level. The <apex:mapMarker> child component defines the markers to place on the map by
address or geolocation (latitude and longitude). You can use the <apex:mapInfoWindow> component to add customizable
information panels that appear when a marker is clicked or tapped.
Note: Visualforce mapping components arent available in Developer Edition organizations.
Maps that you define in Visualforce markup generate JavaScript code to render onto the page. This JavaScript connects to a mapping
service and builds the map by fetching map tiles and placing markers. If your items to be mapped dont have a latitude and longitude,
Visualforce maps can geocode their addresses. After the map renders, your users can interact with the map by panning and zooming,
just like theyre used to with other map sites. The effect is as if you wrote your own custom JavaScript to interact with a third-party
mapping service, but without actually needing to write it. You define the map in Visualforce and get the mapping JavaScript for free.
Important: Visualforce mapping components add JavaScript to your page, and use third-party JavaScript code to draw the map.
JavaScript added by Visualforce uses industry-standard best practices to avoid conflicts with other JavaScript executing on the
same page. If your own JavaScript doesnt also use best practices, it could conflict with the mapping code.
Addresses that need geocodingthat is, locations that dont include values for latitude and longitudeare sent to a third-party
service for geocoding. These addresses arent associated with your organization, and no other data is sent other than what
you provide in your Visualforce markup. However, if your organization requires strict control of data shared outside of Salesforce,
dont use the geocoding feature of Visualforce maps.

IN THIS SECTION:
Creating Basic Maps
A basic map without markers requires only an <apex:map> component. This component defines the maps basic canvas, including
its dimensions, location, and initial zoom level.
Adding Location Markers to a Map
You can add markers to a map to represent specific locations using the <apex:mapMarker> component. You can include text
that displays when a pointer hovers over the marker.
Using Custom Marker Icons
The Visualforce map marker icon is functional but plain. To differentiate markers and add detail or style to your maps, use custom
map marker icons.
Adding Info Windows to Markers
Info windows allow you to show extra details on a map. Info windows appear when a user clicks or taps the marker.

241

Creating Maps with Visualforce

Creating Basic Maps

Example of Building Map Data in Apex


Construct your location data in Apex to perform a custom query, search for nearby locations, filter or transform results, or when you
cant use the results returned by a Visualforce standard controller.

Creating Basic Maps


A basic map without markers requires only an <apex:map> component. This component defines the maps basic canvas, including
its dimensions, location, and initial zoom level.
The center attribute defines the point around which the map is centered. You can provide center values in several formats.
A string that represents an address. For example, "1 Market Street, San Francisco, CA". The address is geocoded to determine its
latitude and longitude.
A string that represents a JSON object with latitude and longitude attributes that specify location coordinates. For example,
"{latitude: 37.794, longitude: -122.395}".
An Apex map object of type Map<String, Double>, with latitude and longitude keys to specify location coordinates.
If <apex:map> doesnt have child <apex:mapMarker> tags, the center attribute is required.
This simple street map displays the neighborhood around Salesforces San Francisco headquarters.
<apex:page >
<h1>Salesforce in San Francisco</h1>
<!-- Display the address on a map -->
<apex:map width="600px" height="400px" mapType="roadmap" zoomLevel="16"
center="One Market Street, San Francisco, CA">
</apex:map>
</apex:page>

This code produces the following map.

242

Creating Maps with Visualforce

Adding Location Markers to a Map

Notice the following in this example.


The mapped address has no marker. The <apex:map> component doesnt, by itself, display map markers, even for the center
point. To display up to 100 markers, add child <apex:mapMarker> components.
The maps center location value is provided as a street address, not a geolocation. The mapping service looks up the latitude
and longitude for the address. This process is called geocoding. You can include up to 10 geocoded addresses to a map, either as
center attributes or as markers added with <apex:mapMarker> components.
The mapType value is roadmap, a standard street map. Other options are satellite and hybrid.

Adding Location Markers to a Map


You can add markers to a map to represent specific locations using the <apex:mapMarker> component. You can include text that
displays when a pointer hovers over the marker.
To place a marker on a map, add an <apex:mapMarker> component as a child of the associated <apex:map>. You specify the
markers location with the position attribute. Optionally, use the title attribute to display text when the pointer hovers over the
marker.
You can add up to 100 markers to a map. Use an <apex:repeat> iteration component to add multiple markers from a collection
or list.
Note: Visualforce maps can be resource-intensive which can cause memory issues within mobile browsers and the Salesforce1
app. Maps with many markers or large images used as custom markers can further increase memory consumption. If you plan to
deploy Visualforce maps in pages that are used in mobile contexts, be sure to test those pages thoroughly.
The position attribute defines the point on the map to place the marker. You can provide position values in several formats.
A string that represents an address. For example, "1 Market Street, San Francisco, CA". The address is geocoded to determine its
latitude and longitude.
A string that represents a JSON object with latitude and longitude attributes that specify location coordinates. For example,
"{latitude: 37.794, longitude: -122.395}".

243

Creating Maps with Visualforce

Adding Location Markers to a Map

An Apex map object of type Map<String, Double>, with latitude and longitude keys to specify location coordinates.
Note: You can have up to 10 geocoded address lookups per map. Lookups for both the center attribute of the <apex:map>
component and the position attribute of the <apex:mapMarker> component count against this limit. To display more
markers, provide position values that dont require geocoding. Locations that exceed the geocoding limit are skipped.
Heres a page that shows a list of contacts for an account, centered on the accounts address.
<apex:page standardController="Account">
<!-- This page must be accessed with an Account Id in the URL. For example:
[Link] -->
<apex:pageBlock >
<apex:pageBlockSection title="Contacts For {! [Link] }">
<apex:dataList value="{! [Link] }" var="contact">
<apex:outputText value="{! [Link] }" />
</apex:dataList>
<apex:map width="600px" height="400px" mapType="roadmap"
center="{![Link]},{![Link]},{![Link]}">
<apex:repeat value="{! [Link] }" var="contact">
<apex:mapMarker title="{! [Link] }"
position="{![Link]},{![Link]},{![Link]}"
/>
</apex:repeat>
</apex:map>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

This code produces the following map.

244

Creating Maps with Visualforce

Using Custom Marker Icons

Notice the following in this example.


The center and position attributes are passed as a Visualforce expression that concatenates address elements to provide
an address string that can be geocoded.
Because this page uses geocoding for the addresses, it displays only the first nine contacts. The center attribute of <apex:map>
uses one geocoding lookup as part of the 10 allowed. (In the illustration, the account has only three contacts.)

Using Custom Marker Icons


The Visualforce map marker icon is functional but plain. To differentiate markers and add detail or style to your maps, use custom map
marker icons.
To customize a markers icon, set the icon attribute to an absolute or fully qualified URL to the graphic to use. You can reference any
image on the Web, for example, if your graphics are distributed in a CDN. You can also use graphics stored in a static resource. If you use
images from a static resource, use the URLFOR() function to obtain the image URL. For example:
<apex:mapMarker title="{! [Link] }"
position="{![Link]},{![Link]},{![Link]}"
icon="{! URLFOR($[Link], '[Link]') }" />

Use a common graphics format, such as PNG, GIF, or JPEG. The preferred marker size is 32 32 pixels. Other sizes are scaled, which
doesnt always produce ideal results.
Note: Visualforce maps can be resource-intensive which can cause memory issues within mobile browsers and the Salesforce1
app. Maps with many markers or large images used as custom markers can further increase memory consumption. If you plan to
deploy Visualforce maps in pages that are used in mobile contexts, be sure to test those pages thoroughly.
This complete page illustrates using a custom marker to indicate an accounts location, and standard markers for the accounts contacts.
<apex:page standardController="Account">
<!-- This page must be accessed with an Account Id in the URL. For example:
[Link] -->

245

Creating Maps with Visualforce

Using Custom Marker Icons

<apex:pageBlock >
<apex:pageBlockSection title="Contacts For {! [Link] }">
<apex:dataList value="{! [Link] }" var="contact">
<apex:outputText value="{! [Link] }" />
</apex:dataList>
<apex:map width="600px" height="400px" mapType="roadmap"
center="{![Link]},{![Link]},{![Link]}">
<!-- Add a CUSTOM map marker for the account itself -->
<apex:mapMarker title="{! [Link] }"
position="{![Link]},{![Link]},{![Link]}"
icon="{! URLFOR($[Link], '[Link]') }"/>
<!-- Add STANDARD markers for the account's contacts -->
<apex:repeat value="{! [Link] }" var="ct">
<apex:mapMarker title="{! [Link] }"
position="{! [Link] },{! [Link] },{! [Link] }">
</apex:mapMarker>
</apex:repeat>
</apex:map>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

This code produces the following map.

246

Creating Maps with Visualforce

Adding Info Windows to Markers

To use different icons for markers added inside an iteration like <apex:repeat>, use an expression related to the iteration variable
to define the URL. One simple way is to use icons named for a lookup field on a record. Another approach is to provide the icon name
in a custom formula field.
Heres the previous <apex:repeat> block with a variation that assumes the contact object has a custom field named ContactType__c
and that each contact type has a correspondingly named icon.
<!-- Add CUSTOM markers for the account's contacts -->
<apex:repeat value="{! [Link] }" var="ct">
<apex:mapMarker title="{! [Link] }"
position="{! [Link] },{! [Link] },{! [Link] }"
icon="{! URLFOR($[Link], ct.ContactType__c + '.png') }">
</apex:mapMarker>
</apex:repeat>

If you use a field to provide a critical part of the icons URL make sure that it always provides a usable value. For example, by making it a
required field, or by ensuring a formula field provides a sensible default value.

Adding Info Windows to Markers


Info windows allow you to show extra details on a map. Info windows appear when a user clicks or taps the marker.
The map marker title attribute lets you display a small amount of information when a user hovers over the marker. To display more
information or have more control over how its formatted, use an info window instead of or in addition to the title attribute.
For example, you can display complete details for a contacts address, formatted for optimal display. You can add a clickable telephone
link or even display a profile photo for objects that have one.
To add an info window to a map marker, add an <apex:mapInfoWindow> component as a child component of the associated
<apex:mapMarker>. The body of the <apex:mapInfoWindow> component is displayed in the info window when users click
or tap the marker, and can be Visualforce markup, HTML and CSS, or plain text.
This complete page uses Visualforce markup for the contents of the info window.
<apex:page standardController="Account">
<!-- This page must be accessed with an Account Id in the URL. For example:
[Link]
-->
<apex:pageBlock >
<apex:pageBlockSection title="Contacts For {! [Link] }">
<apex:dataList value="{! [Link] }" var="contact">
<apex:outputText value="{! [Link] }" />
</apex:dataList>
<apex:map width="600px" height="400px" mapType="roadmap"
center="{![Link]},{![Link]},{![Link]}">
<!-- Add markers for account contacts -->
<apex:repeat value="{! [Link] }" var="ct">
<apex:mapMarker title="{! [Link] }"
position="{! [Link] },{! [Link] },{! [Link] }">

247

Creating Maps with Visualforce

Adding Info Windows to Markers

<!-- Add info window with contact details -->


<apex:mapInfoWindow >
<apex:outputPanel layout="block" style="font-weight: bold;">
<apex:outputText>{! [Link] }</apex:outputText>
</apex:outputPanel>
<apex:outputPanel layout="block">
<apex:outputText>{! [Link] }</apex:outputText>
</apex:outputPanel>
<apex:outputPanel layout="block">
<apex:outputText>{! [Link] }, {! [Link] }</apex:outputText>
</apex:outputPanel>
<apex:outputPanel layout="block">
<apex:outputLink value="{! '[Link] + [Link] }">
<apex:outputText>{! [Link] }</apex:outputText>
</apex:outputLink>
</apex:outputPanel>
</apex:mapInfoWindow>
</apex:mapMarker>
</apex:repeat>
</apex:map>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

This code produces the following map.

248

Creating Maps with Visualforce

Example of Building Map Data in Apex

By default, only one info window displays at a time. When you click another marker, the first info window closes, and the new info
window opens. To display multiple info windows at once, set showOnlyActiveInfoWindow to false on the containing
<apex:map> component.
Note: Consider carefully the effect of displaying multiple info windows at once, because it can create a cluttered map.

Example of Building Map Data in Apex


Construct your location data in Apex to perform a custom query, search for nearby locations, filter or transform results, or when you cant
use the results returned by a Visualforce standard controller.
Apex code gives you complete control over the results that are returned and used for the map and markers. You can also use Apex to
return results that are from outside Salesforce.
This page displays up to 10 warehouses nearest the users location.
<apex:page controller="FindNearbyController" docType="html-5.0" >
<!-- JavaScript to get the user's current location, and pre-fill
the currentPosition form field. -->
<script type="text/javascript">
// Get location, fill in search field
function setUserLocation() {
if ([Link]) {
[Link](function(loc){
var latlon = [Link] + "," + [Link];
var el = [Link]("[Link]");
[Link] = latlon;
});
}
}
// Only set the user location once the page is ready
var readyStateCheckInterval = setInterval(function() {
if ([Link] === "interactive") {
clearInterval(readyStateCheckInterval);
setUserLocation();
}
}, 10);
</script>
<apex:pageBlock >
<!-- Form field to send currentPosition in request. You can make it
an <apex:inputHidden> field to hide it. -->
<apex:pageBlockSection >
<apex:form >
<apex:outputLabel for="currentPosition">Find Nearby</apex:outputLabel>
<apex:input size="30"
html-placeholder="Attempting to obtain your position..."
id="currentPosition" styleClass="currentPosition"
value="{!currentPosition}" />
<apex:commandButton action="{!findNearby}" value="Go!"/>
</apex:form>
</apex:pageBlockSection>

249

Creating Maps with Visualforce

Example of Building Map Data in Apex

<!-- Map of the results -->


<apex:pageBlockSection rendered="{!resultsAvailable}" title="Locations">
<apex:map width="600px" height="400px">
<apex:repeat value="{!locations}" var="pos">
<apex:mapMarker position="{!pos}"/>
</apex:repeat>
</apex:map>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>

This code produces the following map.

This page has three important sections.


The JavaScript block at the beginning illustrates how you can access the browsers built-in ability to ask for the users current location.
This code updates a visible form field. However, you can easily use a hidden form field instead to avoid showing the raw latitude
and longitude with its unlikely level of precision.
The first <apex:pageBlockSection> contains a short form for submitting the users location in the POSTBACK request. For
illustration purposes its visible and requires a click, but thats not required.
In the second <apex:pageBlockSection>, the map itself is simple, requiring only five lines of code. All the complexity is in
the {!locations} expression, which accesses a property in the Apex controller.

250

Creating Maps with Visualforce

Example of Building Map Data in Apex

Note the use of the rendered attribute, which takes the value of the {!resultsAvailable} expression. This expression
is another Apex property, and using it with the rendered attribute hides the map section when locations arent available to place
on the map.
Heres the Apex controller that supports the previous page.
public with sharing class FindNearbyController {
public List<Map<String,Double>> locations { get; private set; }
public String currentPosition {
get {
if ([Link](currentPosition)) {
currentPosition = '37.77493,-122.419416'; // San Francisco
}
return currentPosition;
}
set;
}
public Boolean resultsAvailable {
get {
if(locations == Null) {
return false;
}
return true;
}
}
public PageReference findNearby() {
String lat, lon;
// FRAGILE: You'll want a better lat/long parsing routine
// Format: "<latitude>,<longitude>" (must have comma, but only one comma)
List<String> latlon = [Link](',');
lat = latlon[0].trim();
lon = latlon[1].trim();
// SOQL query to get the nearest warehouses
String queryString =
'SELECT Id, Name, Location__longitude__s, Location__latitude__s ' +
'FROM Warehouse__c ' +
'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') < 20 ' +
'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') ' +
'LIMIT 10';
// Run the query
List <Warehouse__c> warehouses = [Link](queryString);
if(0 < [Link]()) {
// Convert to locations that can be mapped
locations = new List<Map<String,Double>>();
for (Warehouse__c wh : warehouses) {
[Link](
new Map<String,Double>{

251

Creating Maps with Visualforce

Example of Building Map Data in Apex

'latitude' => wh.Location__latitude__s,


'longitude' => wh.Location__longitude__s
}
);
}
}
else {
[Link]('No results. Query: ' + queryString);
}
return null;
}
}

Take a few minutes to learn more about this controller and how it works with the Visualforce page.
The locations property is a list of Map<String,Double> elements. This list holds the location data in a format thats
directly usable by the <apex:mapMarker> component.
The currentPosition property captures the position information thats submitted from the pages form. This property also
ensures that if the form submission is empty, a valid default value is provided. (A more robust implementation would do more error
checking on the form input.)
The resultsAvailable property, noted in the earlier description of the Visualforce markup.
The findNearby action method is called when the Go! <apex:commandButton> is pressed. This method does all the
work, executing a custom SOQL query and massaging the results into the locations property format.
If you want to use the title attribute of <apex:mapMarker> to provide additional information (for example, the name of the
warehouse), you have several options. If your method is returning sObjects, you can reference the appropriate fields in your Visualforce
markup. If youre creating new objects directly, as we are here, you can create an inner class that combines the location map object with
the title string. You then return a collection of the inner class objects to the page.

252

CHAPTER 17 Render Flows with Visualforce


The standard user interface for running a flow cant be customized by using Visual Workflow. However, once you embed a flow in a
Visualforce page, you can use Apex code and Visualforce markup to configure the flow at run timesuch as to pass values between
the Visualforce page and the flow or to customize the look and feel of the flow at run time.
A flow is an application, built with Visual Workflow, that collects, updates, edits, and creates Salesforce information.
The following topics demonstrate how to embed and configure flows in a Visualforce page.
IN THIS SECTION:
Embed Flows in Visualforce Pages
To customize a flows look and feel or enhance its functionality, embed it in a Visualforce page. If your org has flows enabled for sites
and portals, use the Visualforce page to deliver the flow to your [Link] site, portal, or community.
An Advanced Example of Using <flow:interview>
The <flow:interview> component is designed to make it easy to develop complex Visualforce interactions. You can access
additional features in your flow by creating a custom controller. With custom controllers, you can build a page with multiple
components that can interact with each other. Any flow within your organization can be individually referenced by its own Apex
type, and the variables in the flow can be accessed as member variables.
Set Flow Variable Values from a Visualforce Page
After you embed your flow in a Visualforce page, set the initial values of variables, sObject variables, collection variables, and sObject
collection variables through the <apex:param> component.
Get Flow Variable Values to a Visualforce Page
Flow variable values can be displayed in a Visualforce page. Once youve embedded your flow in a Visualforce page, you can use
Visualforce markup to get values for variables or sObject variables. To display values for a collection variable or an sObject collection
variable, you can use Visualforce markup to get the individual values contained in the collection.
Control Whether Users Can Pause a Flow from a Visualforce Page
After you embed a flow in a Visualforce page with the <flow:interview> component, consider whether you want to let users
pause flows from that page. Set the allowShowPause attribute to false to prevent users from pausing.
Customize How Users Resume Paused Flow Interviews
By default, users can resume their paused interviews from the Paused Interviews component on their home page. If you want to
customize how and where users can resume their interviews, use the pausedInterviewId attribute on the
<flow:interview> component.
Configure the finishLocation Attribute in a Flow
If finishLocation isnt specified, users who click Finish start a new interview and see the first screen of the flow. You can
shape what happens when a user clicks Finish on the final screen by using the URLFOR function, the $Page variable, or a
controller.

253

Render Flows with Visualforce

Embed Flows in Visualforce Pages

Customize a Flows User Interface


After youve embedded a flow in a Visualforce page, you can customize what the flow looks like at run time by applying custom
styles using CSS. Using a combination of flow attributes and CSS classes, you can customize the individual parts of a flow, such as
the button location, button style, background, and the look and feel of the screen labels.

Embed Flows in Visualforce Pages


To customize a flows look and feel or enhance its functionality, embed it in a Visualforce page. If your org has flows enabled for sites
and portals, use the Visualforce page to deliver the flow to your [Link] site, portal, or community.
Note: Users can run only flows that have an active version. If the flow you embed doesn't have an active version, users see an
error message. If the flow you embed includes a subflow element, the flow that is referenced and called by the subflow element
must have an active version.
To add a flow to a Visualforce page, embed it using the <flow:interview> component:
1. Find the flow's unique name:
a. From Setup, enter Flows in the Quick Find box, then select Flows.
b. Click the name of the flow that you want to embed.
2. Define a new Visualforce page or open one that you want to edit.
3. Add the <flow:interview> component, somewhere between the <apex:page> tags.
4. Set the name attribute to the unique name of the flow. For example:
<apex:page>
<flow:interview name="MyUniqueFlowName"/>
</apex:page>

Note: If the flow is from a managed package, the name attribute must be in this format: [Link].
5. Restrict which users can run the flow by setting the page security for the Visualforce page that contains it.
To run the flow, external users (such as on a community) need access to the Visualforce page. To run the flow, internal users need
access to the Visualforce page and either:
The "Run Flows" permission
The [Link] Flow User field enabled on their user detail page

Setting Variable Values in a Flow


In this example, we'll build a simple flow to allow customer support agents to troubleshoot modem issues by creating a case. You can
set the value of variables when starting a flow through the <apex:param> component. For our example, to set the case number
variable called vaCaseNumber with the initial value 01212212 when the flow loads, use the following markup:
<apex:page>
<flow:interview name="ModemTroubleShooting">
<apex:param name="vaCaseNumber" value="01212212"/>
</flow:interview>
</apex:page>

254

Render Flows with Visualforce

An Advanced Example of Using <flow:interview>

You can also leverage standard Visualforce controllers to set variables. For example, if the Visualforce page is using the standardCase
controller, you can enhance the page to pass in the data from the standard controller:
<apex:page standardController="Case" tabStyle="Case" >
<flow:interview name="ModemTroubleShooting">
<apex:param name="vaCaseNumber" value="{![Link]}"/>
</flow:interview>
</apex:page>

For more examples of setting variable values, see Set Flow Variable Values from a Visualforce Page on page 257. For information about
getting variable values from a flow to display in a Visualforce page, see Get Flow Variable Values to a Visualforce Page on page 261.

Setting the finishLocation Attribute


Building on our modem troubleshooting example, we'll also set the finishLocation attribute to redirect the user to the Salesforce
home page when they click on the Finish button at the end of the flow:
<apex:page standardController="Case" tabStyle="Case" >
<flow:interview name="ModemTroubleShooting" finishLocation="{!URLFOR('/home/[Link]')}">
<apex:param name="vaCaseNumber" value="{![Link]}"/>
</flow:interview>
</apex:page>

For more examples of setting finishLocation, see Configure the finishLocation Attribute in a Flow on page 265.

An Advanced Example of Using <flow:interview>


The <flow:interview> component is designed to make it easy to develop complex Visualforce interactions. You can access
additional features in your flow by creating a custom controller. With custom controllers, you can build a page with multiple components
that can interact with each other. Any flow within your organization can be individually referenced by its own Apex type, and the variables
in the flow can be accessed as member variables.
Note: You can set only variables that allow input access, and you can get only variables that allow output access. For each flow
variable, input and output access is controlled by:
The Input/Output Type variable field in the Cloud Flow Designer
The isInput and isOutput fields on FlowVariable in the Metadata API
For a variable that doesnt allow input or output access, attempts to get the variable are ignored, and compilation may fail for the
Visualforce page, its <apex:page> component, or the Apex class.
For our next example, the flow with unique name ModemTroubleShooting is referenced as
[Link]. The markup illustrates how to display a value of a flow variable in a different
part of the page:
<apex:page Controller="ModemTroubleShootingCustomSimple" tabStyle="Case">
<flow:interview name="ModemTroubleShooting" interview="{!myflow}"/>
<apex:outputText value="Default Case Prioriy: {!casePriority}"/>
</apex:page>

Note: If the flow is from a managed package, the name attribute must be in this format: [Link].

255

Render Flows with Visualforce

An Advanced Example of Using <flow:interview>

The controller for the above markup looks like this:


public class ModemTroubleShootingCustomSimple {
// You don't need to explicitly instantiate the Flow object;
// the class constructor is invoked automatically
public [Link] myflow { get; set; }
public String casePriority;
public String getCasePriority() {
// Access flow variables as simple member variables with get/set methods
if(myflow == null) return 'High';
else return [Link];
}
}

If youre using a custom controller, you can also set the initial values of the variables at the beginning of the flow in the constructor of
the flow. Passing in variables using the constructor is optional and isnt necessary if youre using <apex:param> tags to set the value.
Heres an example of a custom controller that sets the values of flow variables in a constructor:
public class ModemTroubleShootingCustomSetVariables {
public [Link] myflow { get; set; }
public ModemTroubleShootingCustomSetVariables() {
Map<String, Object> myMap = new Map<String, Object>();
[Link]('vaCaseNumber','123456');
myflow = new [Link](myMap);
}
public String caseNumber { set; }
public String getCaseNumber() {
return [Link];
}
}

You can use the getVariableValue method in the [Link] class to enable a Visualforce controller to access the
value of a flow variable. The variable may be in the flow embedded in the Visualforce page or in a separate flow that is called by a subflow
element. The returned variable value comes from whichever flow the interview is currently running. If the specified variable cant be
found in that flow, the method returns null. This method checks for the existence of the variable at run time only, not at compile time.
The following sample uses the getVariableValue method to obtain breadcrumb (navigation) information from the flow embedded
in the Visualforce page. If that flow contains subflow elements, and each of the referenced flows also contains a vaBreadCrumb
variable, the Visualforce page can provide users with breadcrumbs regardless of which flow the interview is running.
public class SampleController {
//Instance of the flow
public [Link].Flow_Template_Gallery myFlow {get; set;}
public String getBreadCrumb() {
String aBreadCrumb;
if (myFlow==null) { return 'Home';}
else aBreadCrumb = (String) [Link]('vaBreadCrumb');
return(aBreadCrumb==null ? 'Home': aBreadCrumb);

256

Render Flows with Visualforce

Set Flow Variable Values from a Visualforce Page

}
}

The following table shows the differences in the naming of supported data types between the flow and Apex.
Flow

Apex

Text

String

Number

Decimal

Currency

Decimal

Date

Date, DateTime

Boolean

Boolean

As its a good practice to write tests against your Apex code, the following is a trivial example of writing a test class for
ModemTroubleShootingCustomSetVariables:
@isTest
private class ModemTroubleShootingCustomSetVariablesTest {
static testmethod void ModemTroubleShootingCustomSetVariablestests() {
PageReference pageRef = [Link];
[Link](pageRef);
ModemTroubleShootingCustomSetVariables mytestController =
new ModemTroubleShootingCustomSetVariables();
[Link]([Link](), '01212212');
}
}

Setting the reRender Attribute


By using the reRender attribute, the <flow:interview /> component re-renders the flow without refreshing the whole
page:
<apex:page Controller="ModemTroubleShootingCustomSimple" tabStyle="Case">
<flow:interview name="ModemTroubleShooting" interview="{!myflow}"
reRender="casePrioritySection"/>
<apex:outputText id="casePrioritySection"
value="Default Case Prioriy: {!casePriority}"/>
</apex:page>

Warning: If you dont set the reRender attribute, when you click a button to navigate to a different screen in a flow, the entire
Visualforce page refreshes, not just the <flow:interview> component.

Set Flow Variable Values from a Visualforce Page


After you embed your flow in a Visualforce page, set the initial values of variables, sObject variables, collection variables, and sObject
collection variables through the <apex:param> component.

257

Render Flows with Visualforce

Set Flow Variable Values from a Visualforce Page

Note: You can set variables only at the beginning of an interview. The <apex:param> tags are evaluated only once, when
the flow is launched.
You can set only variables that allow input access. For each flow variable, input access is controlled by:
The Input/Output Type variable field in the Cloud Flow Designer
The isInput field on FlowVariable in the Metadata API
If you reference a variable that doesnt allow input access, attempts to set the variable are ignored. Compilation can fail for the
Visualforce page, its <apex:page> component, or the Apex class.
The following table lists the ways you can set a flows variable, sObject variable, and sObject collection variable values using Visualforce.
Method

Variables

sObject Variables

Collection Variables

sObject Collection
Variables

Without a controller
With a standard controller
With a standard List
controller
With a custom Apex
controller
With an Interview Map

Setting Variable Values without a Controller


This example sets myVariable to the value 01010101 when the interview starts.
<apex:page>
<flow:interview name="flowname">
<apex:param name="myVariable" value="01010101"/>
</flow:interview>
</apex:page>

Setting Variable Values with a Standard Controller


You can use standard Visualforce controllers to set variables or sObject variables by passing in data from a record. This example sets the
initial value of myVariable to the Visualforce expression {!account} when the interview starts.
<apex:page standardController="Account" tabStyle="Account">
<flow:interview name="flowname">
<apex:param name="myVariable" value="{!account}"/>
</flow:interview>
</apex:page>

258

Render Flows with Visualforce

Set Flow Variable Values from a Visualforce Page

Setting an sObject Collection Variable Value with a Standard List Controller


Because sObject collection variables represent an array of values, you must use a standard list controller or a custom Apex controller.
This example sets myCollection to the value of {!accounts} when the interview starts.
<apex:page standardController="Account" tabStyle="Account" recordSetVar="accounts">
<flow:interview name="flowname">
<apex:param name="myCollection" value="{!accounts}"/>
</flow:interview>
</apex:page>

Setting Variable Values with a Custom Apex Controller


For finer control over your Visualforce page than a standard controller allows, write a custom Apex controller that sets the variable value,
and then reference that controller in your Visualforce page. This example uses Apex to set myVariable to a specific accounts Id
when the interview starts.
public class MyCustomController {
public Account apexVar {get; set;}
public MyCustomController() {
apexVar = [
SELECT Id, Name FROM Account
WHERE Name = Acme LIMIT 1];
}
}
<apex:page controller="MyCustomController">
<flow:interview name="flowname">
<apex:param name="myVariable" value="{!apexVar}"/>
</flow:interview>
</apex:page>

This example uses Apex to set an sObject collection variable myAccount to the Id and Name field values for every record with a
Name of Acme.
public class MyCustomController {
public Account[] myAccount {
get {
return [
SELECT Id, Name FROM account
WHERE Name = 'Acme'
ORDER BY Id
] ;
}
set {
myAccount = value;
}
}
public MyCustomController () {

259

Render Flows with Visualforce

Set Flow Variable Values from a Visualforce Page

}
}
<apex:page id="p" controller="MyCustomController">
<flow:interview id="i" name="flowname">
<apex:param name="accountColl" value="{!myAccount}"/>
</flow:interview>
</apex:page>

Setting Variable Values with an Interview Map


This example uses an Interview map to set the value for accVar to a specific accounts Id when the interview starts.
public class MyCustomController {
public [Link] myflow { get; set; }
public MyCustomController() {
Map<String, Object> myMap = new Map<String, Object>();
[Link]('accVar', [SELECT Id FROM Account
WHERE Name = 'Acme' LIMIT 1]);
myflow = new [Link](myMap);
}
}
<apex:page controller="MyCustomController">
<flow:interview name="flowname" interview="{!myflow}"/>
</apex:page>

Heres a similar example that sets the value for accVar to a new account when the interview starts.
public class MyCustomController {
public [Link] myflow { get; set; }
public MyCustomController() {
Map<String, List<Object>> myMap = new Map<String, List<Object>>();
[Link]('accVar', new Account(name = 'Acme'));
myflow = new [Link](myMap);
}
}
<apex:page controller="MyCustomController">
<flow:interview name="flowname" interview="{!myflow}"/>
</apex:page>

This example uses a map to add two values to a string collection variable (stringCollVar) and two values to a number collection
variable (numberCollVar).
public class MyCustomController {
public [Link] MyInterview { get; set; }
public MyCustomController() {
String[] value1 = new String[]{'First', 'Second'};
Double[] value2 = new Double[]{999.123456789, 666.123456789};
Map<String, Object> myMap = new Map<String, Object>();

260

Render Flows with Visualforce

Get Flow Variable Values to a Visualforce Page

[Link]('stringCollVar', value1);
[Link]('numberCollVar', value2);
MyInterview = new [Link](myMap);
}
}
<apex:page controller="MyCustomController">
<flow:interview name="flowname" interview="{!MyInterview}" />
</apex:page>

Get Flow Variable Values to a Visualforce Page


Flow variable values can be displayed in a Visualforce page. Once youve embedded your flow in a Visualforce page, you can use Visualforce
markup to get values for variables or sObject variables. To display values for a collection variable or an sObject collection variable, you
can use Visualforce markup to get the individual values contained in the collection.
Note: You can get only variables that allow output access. For each flow variable, output access is controlled by:
The Input/Output Type variable field in the Cloud Flow Designer
The isOutput field on FlowVariable in the Metadata API
If you reference a variable that doesnt allow output access, attempts to get the variable are ignored. Compilation can fail for the
Visualforce page, its <apex:page> component, or the Apex class.
The following example uses an Apex class to get an sObject variable value from a flow and then displays it in a Visualforce page.
public class FlowController {
public [Link] myflow { get; set; }
public Case apexCaseVar;
public Case getApexCaseVar() {
return [Link];
}
}
<apex:page controller="FlowController" tabStyle="Case">
<flow:interview name="flowname" interview="{!myflow}"/>
<apex:outputText value="Default Case Priority: {![Link]}"/>
</apex:page>

This example uses an Apex class to get the values that are stored in a string collection variable (emailsCollVar) in the flow. Then
it uses a Visualforce page to run the flow interview. The Visualforce page iterates over the flows collection variable and displays the
values for each item in the collection.
public class FlowController {
public [Link] myflow { get; set; }
public List<String> getVarValue() {
if (myflow == null) {
return null;
}
else {
return (List<String>)[Link];
}

261

Render Flows with Visualforce

Get Flow Variable Values to a Visualforce Page

}
}
<apex:page controller="FlowController">
<flow:interview name="flowname" interview="{!myflow}" />
<apex:repeat value="{!varValue}" var="item">
<apex:outputText value="{!item}"/><br/>
</apex:repeat>
</apex:page>

The following example uses an Apex class to set the flow to {!myflow} and then uses a Visualforce page to run the flow interview.
The Visualforce page uses a data table to iterate over the flows sObject collection variable and display the values for each item in the
collection.
public class MyCustomController {
public [Link] myflow { get; set; }
}
<apex:page controller="MyCustomController" tabStyle="Account">
<flow:interview name="flowname" interview="{!myflow}" reRender="nameSection" />
<!-- The data table iterates over the variable set in the "value" attribute and
sets that variable to the value for the "var" attribute, so that instead of
referencing {![Link]} in each column, you can simply refer
to "account".-->
<apex:dataTable value="{![Link]}" var="account"
rowClasses="odd,even" border="1" cellpadding="4">
<!-- Add a column for each value that you want to display.-->
<apex:column >
<apex:facet name="header">Name</apex:facet>
<apex:outputlink value="/{!account['Id']}">
{!account['Name']}
</apex:outputlink>
</apex:column>
<apex:column >
<apex:facet name="header">Rating</apex:facet>
<apex:outputText value="{!account['Rating']}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Billing City</apex:facet>
<apex:outputText value="{!account['BillingCity']}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Employees</apex:facet>
<apex:outputText value="{!account['NumberOfEmployees']}"/>
</apex:column>
</apex:dataTable>
</apex:page>

Depending on the contents of the sObject collection variable in your flow, heres what that data table looks like.

262

Render Flows with Visualforce

Control Whether Users Can Pause a Flow from a Visualforce


Page

Control Whether Users Can Pause a Flow from a Visualforce Page


After you embed a flow in a Visualforce page with the <flow:interview> component, consider whether you want to let users
pause flows from that page. Set the allowShowPause attribute to false to prevent users from pausing.
Whether the Pause button appears depends on three settings.
Your organizations Process Automation settings must have Let Users Pause Flows enabled.
For this <flow:interview>, allowShowPause must not be false. The default value is true.
Each screen must be configured to show the Pause button.
Example: In a Visualforce page, youve embedded a flow that includes three screens. Screen 1 is configured to show the Pause
button. Screens 2 and 3 are configured to not show the Pause button.
Let Users Pause Flows

allowShowPause

Result Pause button

(Process Automation setting)

(Visualforce component)

Enabled

true or not set

Pause button appears only on the first


screen

Enabled

false

Pause button doesnt appear for any


screens in this Visualforce page

Not enabled

true or not set

Pause button doesnt appear for any


screens

This example embeds the MyUniqueFlow flow in a Visualforce page and doesnt allow the Pause button to appear.
<apex:page>
<flow:interview name="MyUniqueFlow" allowShowPause="false" />
</apex:page>

263

Render Flows with Visualforce

Customize How Users Resume Paused Flow Interviews

Customize How Users Resume Paused Flow Interviews


By default, users can resume their paused interviews from the Paused Interviews component on their home page. If you want to customize
how and where users can resume their interviews, use the pausedInterviewId attribute on the <flow:interview>
component.
The following example shows how you can resume an interviewor start a new onefrom a button on a page layout. When users
click Survey Customer from a contact record, the Visualforce page does one of two things, depending on whether the user has any
paused interviews for the Survey Customers flow.
If the user does, it resumes the first one.
If the user doesnt, it starts a new one.

Create the Visualforce and Apex Controller


Because the Visualforce page will be referenced in a contact-specific button, it must use that standard controller. Use a controller extension
to add more logic to the page with Apex, which is where the page gets the ID of the interview to resume.
<apex:page
standardController="Contact" extensions="MyControllerExtension_SurveyCustomers">
<flow:interview name="Survey_Customers" pausedInterviewId="{!pausedId}"/>
</apex:page>

This Apex controller extension performs a SOQL query to get a list of paused interviews. If nothing is returned from the query,
getPausedId() returns a null value, and the Visualforce page starts a new interview. If at least one interview is returned from the
query, the Visualforce page resumes the first interview in that list.
public class MyControllerExtension_SurveyCustomers {
// Empty constructor, to allow use as a controller extension
public MyControllerExtension_SurveyCustomers(
[Link] stdController) { }
// Flow support methods
public String getInterviews() { return null; }
public String showList { get; set; }
public String getPausedId() {
String currentUser = [Link]();
List<FlowInterview> interviews =
[SELECT Id FROM FlowInterview WHERE CreatedById = :currentUser AND InterviewLabel
LIKE '%Survey Customers%'];
if (interviews == null || [Link]()) {
return null; // early out
}
// Return the ID for the first interview in the list
return [Link](0).Id;
}
}

264

Render Flows with Visualforce

Configure the finishLocation Attribute in a Flow

Reference the Visualforce Page from a Page Layout


To actually expose this Visualforce page to your users, make it available from the Contact page layout.
Tip: If you embed the Visualforce page directly in a page layout, every time a user accesses a contact, they automatically resume
the first of their paused interviewspossibly unintentionally. Its better for the user to make the conscious choice to start or resume
an interview, so lets use a custom button.
First create a custom button for the Contact object that links to the Visualforce page. Use these field values to create the button.
Field

Value

Label

Survey Customer

Display Type

Detail Page Button

Content Source

Visualforce Page

Content

YourVisualforcePage

Finally, add the button to your Contact page layout.

Configure the finishLocation Attribute in a Flow


If finishLocation isnt specified, users who click Finish start a new interview and see the first screen of the flow. You can shape
what happens when a user clicks Finish on the final screen by using the URLFOR function, the $Page variable, or a controller.
The following sections show the ways you can configure the <flow:interview> components finishLocation attribute.
Set finishLocation with the URLFOR Function
Set finishLocation with the $Page Variable
Set finishLocation with a Controller

Set finishLocation with the URLFOR Function


Note: You can't redirect flow users to a URL thats external to your Salesforce organization.
To route users to a relative URL or a specific record or detail page, using its ID, use the URLFOR function.
This example routes users to the Salesforce home page.
<apex:page>
<flow:interview name="MyUniqueFlow" finishLocation="{!URLFOR('/home/[Link]')}"/>
</apex:page>

This example routes users to a detail page with an ID of 001D000000IpE9X.


<apex:page>
<flow:interview name="MyUniqueFlow" finishLocation="{!URLFOR('/001D000000IpE9X')}"/>
</apex:page>

For more information about URLFOR, see Functions on page 631.

265

Render Flows with Visualforce

Customize a Flows User Interface

Set finishLocation with the $Page Variable


To route users to another Visualforce page without using URLFOR, set finishLocation to the name of the destination page with
the format {!$[Link]}.
<apex:page>
<flow:interview name="MyUniqueFlow" finishLocation="{!$[Link]}"/>
</apex:page>

For more information about $Page, see Global Variables on page 602.

Set finishLocation with a Controller


You can set finishLocation in a few ways with a custom controller.
This sample controller configures a flows finish behavior in three different ways.
getPageA instantiates a new page reference by passing a string to define the location.
getPageB returns a string that is treated like a PageReference.
getPageC returns a string that gets translated into a PageReference.
public class myFlowController {
public PageReference getPageA() {
return new PageReference('/300');
}
public String getPageB() {
return '/300';
}
public String getPageC() {
return '/apex/my_finish_page';
}
}

Heres a sample Visualforce page references that controller and sets the flow finish behavior to the first option.
<apex:page controller="myFlowController">
<h1>Congratulations!</h1> This is your new page.
<flow:interview name="flowname" finishLocation="{!pageA}"/>
</apex:page>

If you use a standard controller to display a record on the same page as the flow, users who click Finish start a new flow interview and
see the first screen of the flow, without the record. This is because the id query string parameter isnt preserved in the page URL. If
needed, configure the finishLocation to route users back to the record.

Customize a Flows User Interface


After youve embedded a flow in a Visualforce page, you can customize what the flow looks like at run time by applying custom styles
using CSS. Using a combination of flow attributes and CSS classes, you can customize the individual parts of a flow, such as the button
location, button style, background, and the look and feel of the screen labels.

266

Render Flows with Visualforce

Customize a Flows User Interface

Flow Button Attributes


Use these attributes to change how the Next, Previous, Finish, Pause, and Dont Pause buttons appear in your flow.
Attribute

Description

buttonLocation

Defines the location of the navigation buttons in the flows user interface. Available values are:
top
bottom
both
For example:
<apex:page>
<flow:interview name="MyFlow" buttonLocation="bottom"/>
</apex:page>

Note: If unspecified, the buttonLocation value defaults to both.


buttonStyle

Assigns a style to the flow navigation buttons as a set. Can only be used for inline styling, not for
CSS classes.
For example:
<apex:page>
<flow:interview name="MyFlow" buttonStyle="color:#050;
background-color:#fed; border:1px solid;"/>
</apex:page>

Flow-Specific CSS Classes


You can override these predefined flow style classes with your own CSS styles.
Flow Style Class

Applies to...

FlowContainer

The <div> element containing the flow.

FlowPageBlockBtns

The <apex:pageBlockButtons> element containing the flow navigation buttons.


Note: To prevent your CSS styling for flow navigation buttons from being overwritten
by button styling applied elsewhere in the system, we recommend you specify this flow
style class each time you apply CSS styling to flow navigation buttons.
For example, instead of .FlowPreviousBtn {}, enter .FlowPageBlockBtns
.FlowPreviousBtn {}.

FlowCancelBtn

The Dont Pause button.

FlowPauseBtn

The Pause button.

FlowPreviousBtn

The Previous button.

FlowNextBtn

The Next button.

267

Render Flows with Visualforce

Customize a Flows User Interface

Flow Style Class

Applies to...

FlowFinishBtn

The Finish button.

FlowText

A text field label.

FlowTextArea

A text area field label.

FlowNumber

A number field label.

FlowDate

A date field label.

FlowCurrency

A currency field label.

FlowPassword

A password field label.

FlowRadio

A radio button field label.

FlowDropdown

A drop-down list label.

268

CHAPTER 18 Templating with Visualforce


Visualforce provides several strategies for reusing similar content across multiple Visualforce pages. The method you choose depends
on how flexible you need your reused template to be. The more flexible a templating method is, the more any implementation of a
template using that method can be modified. The following template methods are available, in order of most to least flexible:
Defining Custom Components
Similar to the way you can encapsulate a piece of code in a method and then reuse that method several times in a program, you
can encapsulate a common design pattern in a custom component and then reuse that component several times in one or more
Visualforce pages. Defining custom components is the most flexible templating method because they can contain any valid Visualforce
tags and can be imported without restrictions into any Visualforce page. However custom components should not be used to define
reusable Visualforce pages. If you want to reuse the content of an entire Visualforce page, choose one of the other two templating
methods.
Defining Templates with <apex:composition>
If you want to define a base template that allows portions of the template to change with each implementation, use the
<apex:composition> component. This templating method is best for situations when you want to maintain an overall
structure to a page, but need the content of individual pages to be different, such as a website for news articles where different
articles should appear with the same page layout.
Through this technique, you can also define a template from a PageReference returned by a controller.
Referencing an Existing Page with <apex:include>
If you want the entire content of a Visualforce page inserted into another page, use the <apex:include> component. This
templating method is best for situations when you want to replicate the same content in multiple areas, such as a feedback form
that appears on every page of a website.
Templates made with <apex:insert> and <apex:composition> should only be used when you want to reference an
already existing Visualforce page. If you require only a set of components to be duplicated, use custom components.

Defining Templates with <apex:composition>


All templates defined using <apex:composition> must have one or more child <apex:insert> tags. An <apex:insert>
tag indicates to pages that import the template that a section needs a definition. Any Visualforce page that imports a template using
<apex:composition> must use <apex:define> to specify the content of each <apex:insert> section of the template.
You can create a skeleton template that allows subsequent Visualforce pages to implement different content within the same standard
structure. To do so, create a template page with the <apex:composition> tag.
The following example shows how you can use <apex:composition>, <apex:insert>, and <apex:define> to implement
a skeleton template.
First, create an empty