0% found this document useful (0 votes)
297 views758 pages

Salesforce Pages Developers Guide

This is salesforce material for learning salesforce.

Uploaded by

Munjeti Krishna
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)
297 views758 pages

Salesforce Pages Developers Guide

This is salesforce material for learning salesforce.

Uploaded by

Munjeti Krishna
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
You are on page 1/ 758

Visualforce Developer Guide

Version 40.0, Summer 17

@salesforcedocs
Last updated: May 18, 2017
Copyright 20002017 salesforce.com, inc. All rights reserved. Salesforce is a registered trademark of salesforce.com, 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 40.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Documentation Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10

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


Using the Development Mode Footer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
About the Visualforce Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Accessing Metrics for Your Visualforce Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16

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


Compiling Visualforce Successfully . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Creating Your First Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Displaying Field Values with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Using the Visualforce Component Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Overriding an Existing Page with a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Redirecting to a Standard Object List Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Using Input Components in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Adding and Customizing Input Field Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Setting the Tab Order for Fields in a Form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Adding Dependent Fields to a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Creating Visualforce Dashboard Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Displaying Related Lists for Custom Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Enabling Inline Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Converting a Page to a PDF File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Building a Table of Data in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
Editing a Table of Data in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Using Query String Parameters in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Getting Query String Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Setting Query String Parameters in Links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Getting and Setting Query String Parameters on a Single Page . . . . . . . . . . . . . . . . . . . 42
Using Ajax in a Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Contents

Implementing Partial Page Updates with Command Links and Buttons . . . . . . . . . . . . . 43


Providing Status for Asynchronous Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
Applying Ajax Behavior to Events on Any Component . . . . . . . . . . . . . . . . . . . . . . . . . 45

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


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

Chapter 5: Standard Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78


Associating a Standard Controller with a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . 78
Accessing Data with a Standard Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
Using Standard Controller Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
Validation Rules and Standard Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Styling Pages that Use Standard Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Checking for Object Accessibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81

Chapter 6: Standard List Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83


Associating a Standard List Controller with a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . 83
Accessing Data with List Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Using Standard List Controller Actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Pagination with a List Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Using List Views with Standard List Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Contents

Editing Records with List Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88

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


What are Custom Controllers and Controller Extensions? . . . . . . . . . . . . . . . . . . . . . . . . . . 90
Building a Custom Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
Building a Controller Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
Building a Custom List Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Controller Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Controller Class Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Working with Large Sets of Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Setting Read-Only Mode for an Entire Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Setting Read-Only Mode for Controller Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
Considerations for Creating Custom Controllers and Controller Extensions . . . . . . . . . . . . . . 101
Order of Execution in a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
Order of Execution for Visualforce Page Get Requests . . . . . . . . . . . . . . . . . . . . . . . . 103
Order of Execution for Visualforce Page Postback Requests . . . . . . . . . . . . . . . . . . . . 105
Examples of Visualforce Page Execution Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Testing Custom Controllers and Controller Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Validation Rules and Custom Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
Using the transient Keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

Chapter 8: Advanced Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120


Creating Your First Custom Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Creating a Custom Controller Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Defining Getter Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Defining Action Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
Defining Navigation Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
Creating a Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127
Advanced Visualforce Dashboard Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
Integrating Visualforce and Google Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
Mass-Updating Records with a Custom List Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

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


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

Chapter 10: Using Static Resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149


Creating a Static Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Referencing a Static Resource in Visualforce Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150

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


What are Custom Components? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
Defining Custom Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153
Contents

Custom Component Markup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154


Using Custom Components in a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
Managing Version Settings for Custom Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Custom Component Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Custom Component Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

Chapter 12: Dynamic Visualforce Bindings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159


Using Dynamic References with Standard Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
Using Dynamic References with Custom Objects and Packages . . . . . . . . . . . . . . . . . . . . . 169
Referencing Apex Maps and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
Working with Field Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Dynamic References to Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178
Dynamic References to Static Resources Using $Resource . . . . . . . . . . . . . . . . . . . . . 178
Dynamic References to Action Methods Using $Action . . . . . . . . . . . . . . . . . . . . . . . . 180
Dynamic References to Schema Details Using $ObjectType . . . . . . . . . . . . . . . . . . . . 182

Chapter 13: Dynamic Visualforce Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186


Dynamic Components Restrictions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
Creating and Displaying Dynamic Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
Deferred Creation of Dynamic Components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Example Using a Related List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192

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


Sending an Email with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
Creating a Custom Controller with the Messaging Class . . . . . . . . . . . . . . . . . . . . . . 198
Creating an Email Attachment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201
Visualforce Email Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205
Creating a Visualforce Email Template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
Using a Custom Stylesheet in a Visualforce Email Template . . . . . . . . . . . . . . . . . . . . 208
Adding Attachments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
Using Custom Controllers within Visualforce Email Templates . . . . . . . . . . . . . . . . . . . 215

Chapter 15: Visualforce Charting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217


Visualforce Charting Limitations and Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217
How Visualforce Charting Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
A Simple Charting Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
Providing Chart Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Building a Complex Chart with Visualforce Charting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223
Updating Charts with Refreshed Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
Refreshing Chart Data Using <apex:actionSupport> . . . . . . . . . . . . . . . . . . . . . . . . . 228
Refreshing Chart Data Using JavaScript Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Controlling the Appearance of Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Chart Colors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Chart Layout and Annotation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
Bar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Contents

Other Linear Series Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239


Pie Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Gauge Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
Radar Charts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

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


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

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


Embed Flows in Visualforce Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 258
An Advanced Example of Using <flow:interview> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Set Flow Variable Values from a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Get Flow Variable Values to a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 265
Control Whether Users Can Pause a Flow from a Visualforce Page . . . . . . . . . . . . . . . . . . . 267
Customize How Users Resume Paused Flow Interviews . . . . . . . . . . . . . . . . . . . . . . . . . . 268
Configure the finishLocation Attribute in a Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
Customize a Flows User Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270

Chapter 18: Templating with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273


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

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


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

Chapter 20: Adding Visualforce to a Force.com AppExchange App . . . . . . . . . . . . . 301


Managing Package Version Settings for Visualforce Pages and Components . . . . . . . . . . . 302
Contents

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


Using $Component to Reference Components from JavaScript . . . . . . . . . . . . . . . . . . . . . 303
Using JavaScript Libraries with Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
JavaScript Remoting for Apex Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
What Is JavaScript Remoting? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
When to Use JavaScript Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
Adding JavaScript Remoting to a Visualforce Page . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Declaring a Remote Method in Apex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Handling the Remote Response . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Debugging JavaScript Remoting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
JavaScript Remoting Limits and Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
JavaScript Remoting Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314
Visualforce Remote Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
A Simple Example of Remote Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Using Remote Objects in JavaScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 318
An Example of Using Remote Objects with jQuery Mobile . . . . . . . . . . . . . . . . . . . . . 333
Best Practices for Using Remote Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
Remote Objects Limits . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340

Chapter 22: Best Practices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341


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

Chapter 23: Standard Component Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351


analytics:reportChart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
apex:actionFunction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
apex:actionPoller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
apex:actionRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
apex:actionStatus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
apex:actionSupport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
apex:areaSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
apex:attribute . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
apex:axis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
apex:barSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
apex:canvasApp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
apex:chart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
apex:chartLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
apex:chartTips . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
Contents

apex:column . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
apex:commandButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
apex:commandLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
apex:component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
apex:componentBody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
apex:composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
apex:dataList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
apex:dataTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
apex:define . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
apex:detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
apex:dynamicComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
apex:emailPublisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
apex:enhancedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
apex:facet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
apex:flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
apex:form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
apex:gaugeSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
apex:iframe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
apex:image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
apex:include . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
apex:includeLightning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
apex:includeScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
apex:inlineEditSupport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
apex:input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
apex:inputCheckbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
apex:inputField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
apex:inputFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
apex:inputHidden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
apex:inputSecret . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
apex:inputText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
apex:inputTextarea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
apex:insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
apex:legend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
apex:lineSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
apex:listViews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
apex:logCallPublisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
apex:map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
apex:mapInfoWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
apex:mapMarker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
apex:message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
apex:messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
apex:milestoneTracker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
apex:outputField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
apex:outputLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
Contents

apex:outputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
apex:outputPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
apex:outputText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
apex:page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 479
apex:pageBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
apex:pageBlockButtons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
apex:pageBlockSection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
apex:pageBlockSectionItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
apex:pageBlockTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
apex:pageMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
apex:pageMessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
apex:panelBar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
apex:panelBarItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
apex:panelGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
apex:panelGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
apex:param . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
apex:pieSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
apex:radarSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
apex:relatedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
apex:remoteObjectField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 518
apex:remoteObjectModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
apex:remoteObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
apex:repeat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
apex:scatterSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
apex:scontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
apex:sectionHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
apex:selectCheckboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
apex:selectList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 531
apex:selectOption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
apex:selectOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 537
apex:selectRadio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
apex:slds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
apex:stylesheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
apex:tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
apex:tabPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 547
apex:toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
apex:toolbarGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
apex:variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
apex:vote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
chatter:feed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
chatter:feedWithFollowers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
chatter:follow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
chatter:followers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
chatter:newsfeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
Contents

chatter:userPhotoUpload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
chatteranswers:aboutme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
chatteranswers:allfeeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
chatteranswers:changepassword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
chatteranswers:datacategoryfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
chatteranswers:feedfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
chatteranswers:feeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
chatteranswers:forgotpassword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
chatteranswers:forgotpasswordconfirm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
chatteranswers:guestsignin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
chatteranswers:help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
chatteranswers:login . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
chatteranswers:registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
chatteranswers:searchask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
chatteranswers:singleitemfeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
flow:interview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
ideas:detailOutputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
ideas:listOutputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
ideas:profileListOutputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
knowledge:articleCaseToolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
knowledge:articleList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
knowledge:articleRendererToolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
knowledge:articleTypeList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
knowledge:categoryList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
liveAgent:clientChat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
liveAgent:clientChatAlertMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
liveAgent:clientChatCancelButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
liveAgent:clientChatEndButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
liveAgent:clientChatFileTransfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
liveAgent:clientChatInput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
liveAgent:clientChatLog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 583
liveAgent:clientChatLogAlertMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
liveAgent:clientChatMessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
liveAgent:clientChatQueuePosition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
liveAgent:clientChatSaveButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
liveAgent:clientChatSendButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
liveAgent:clientChatStatusMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
messaging:attachment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
messaging:emailHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
messaging:emailTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
messaging:htmlEmailBody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
messaging:plainTextEmailBody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
site:googleAnalyticsTracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
site:previewAsAdmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
Contents

social:profileViewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
support:caseArticles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
support:caseFeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
support:caseUnifiedFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
support:clickToDial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
support:portalPublisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
topics:widget . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
wave:dashboard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604

APPENDICES . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607

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


Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 607
$Action . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
$Api . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
$Asset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
$Cache.Session . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
$Component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 619
$ComponentLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
$CurrentPage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
$FieldSet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
$Label . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
$Label.Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
$Network . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 623
$ObjectType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
$Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
$Page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
$Permission . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
$Profile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
$Resource . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 631
$SControl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
$Setup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
$Site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
$System.OriginDateTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
$User . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
$User.UITheme and $User.UIThemeDisplayed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
$UserRole . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
Expression Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649

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


Cross Site Scripting (XSS) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
Unescaped Output and Formulas in Visualforce Pages . . . . . . . . . . . . . . . . . . . . . . . . . . 654
Cross-Site Request Forgery (CSRF) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
Contents

SOQL Injection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656


Data Access Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658

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


ApexPages Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
ApexPages Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 660
Action Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
Action Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
Action Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 664
Cookie Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
Cookie Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
Cookie Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
IdeaStandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
IdeaStandardController Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
IdeaStandardSetController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672
IdeaStandardSetController Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
KnowledgeArticleVersionStandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675
KnowledgeArticleVersionStandardController Constructors . . . . . . . . . . . . . . . . . . . . . 677
KnowledgeArticleVersionStandardController Methods . . . . . . . . . . . . . . . . . . . . . . . 678
Message Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
Message Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
Message Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
PageReference Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
PageReference Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
PageReference Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
SelectOption Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
SelectOption Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
SelectOption Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
StandardController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
StandardController Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
StandardController Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700
StandardSetController Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704
StandardSetController Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705
StandardSetController Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 706

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

GLOSSARY . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 722

INDEX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
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 Force.com 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 Force.com
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 Force.com 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 40.0

1
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
Force.com 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 Force.com 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.

2
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.

3
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 Force.com 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

4
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 force.com servers instead of a salesforce.com 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.

5
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 Force.com 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 Force.com 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 Force.com 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 Force.com 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:

6
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 Write HTML and JavaScript for entire page
components using tags

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 Developers can't bind an input component
(such as a text box) with a particular field with a particular field. Instead, they must
(such as Account Name). If a user saves a write JavaScript code that uses the API to
value in that input component, it is also update the database with user-specified
saved in the database. field values.

Stylesheet inheritance Yes No, must bring in Salesforce stylesheets


manually

7
Introducing Visualforce How is Visualforce Versioned?

Visualforce Pages S-Controls


Respect for field metadata, such as Yes, by default Yes, if coded in JavaScript using a
uniqueness If a user attempts to save a record that describe API call
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.

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 Less responsive because every call to the
generated on the Force.com platform API requires a round trip to the serverthe
burden rests with the developer to tune
performance

Page container Native In an iFrame

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.

8
Introducing Visualforce Whats New in Visualforce Version 40.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 40.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.
Winter 17 Release Notes
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

9
Introducing Visualforce Documentation Typographical Conventions

Spring 08 Release Notes


Winter 08 Release Notes
Summer 07 Release Notes
Spring 07 Release Notes
Force.com Mobile 7.0 for BlackBerry Release Notes
Force.com Mobile 6.1 for Windows Mobile 5 Release Notes
Winter 07 Release Notes
Summer 06 Release Notes
Winter 06 Release Notes
Force.com 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="{!account.Contacts}" var="contact">

<apex:column value="{!contact.Name}"/>
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</apex:pageBlockTable>

10
Introducing Visualforce Documentation Typographical Conventions

Convention Description
{} In descriptions of syntax, braces ({ }) are typed exactly as shown.
<apex:page>
Hello {!$User.FirstName}!
</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 Force.com IDE, a plug-in for the Eclipse IDE, offers capabilities not found elsewhere. The Force.com IDE provides a unified interface
for building and deploying Force.com 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 na3.salesforce.com, enter
https://na3.salesforce.com/apex/HelloWorld 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 341.
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
Tools for Visualforce Development Accessing Metrics for Your Visualforce Pages

Accessing Metrics for Your Visualforce Pages


To query metrics on the Visualforce pages in your org, use the VisualforceAccessMetrics object in the Salesforce SOAP API.
Make a SOQL query in Workbench to get information from the VisualforceAccessMetrics object. This is a sample SOQL call.
SELECT ApexPageId,DailyPageViewCount,Id,MetricsDate FROM VisualforceAccessMetrics

Each VisualforceAccessMetrics object tracks the daily page view count in the DailyPageViewCount field. The date
the metrics were collected is specified in MetricsDate, and the ID of the tracked Visualforce page is specified in ApexPageId.
Page views are tallied the day after the page is viewed, and each VisualforceAccessMetrics object is removed after 90 days.
Using VisualforceAccessMetrics, you can track the number of views each Visualforce page in your org receives in a 24-hour
time period. To find out how many views a page got over the course of multiple days, you can query multiple VisualforceAccessMetrics
objects for the same ApexPageId.

16
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 Force.com 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:

https://Salesforce_instance/apex/myNewPageName

For example, if you want to create a page called HelloWorld and your Salesforce organization uses na3.salesforce.com, enter
http://na3.salesforce.com/apex/HelloWorld.

17
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.

18
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
{!$User.FirstName} expression to a page:

<apex:page>
Hello {!$User.FirstName}!
</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 607.
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 {!$User.FirstName}!
</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 {!account.name} in the page markup:
<apex:page standardController="Account">
Hello {!$User.FirstName}!
<p>You are viewing the {!account.name} account.</p>
</apex:page>

The {!account.name} 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, {!account.parent.name} 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:
https://na3.salesforce.com/001D000000IRt53

Then 001D000000IRt53 is the ID for the account.

19
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:
https://na3.salesforce.com/apex/HelloWorld2

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

https://Salesforce_instance/apex/HelloWorld2?id=001D000000IRt53

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 {!$User.FirstName}!">
You are viewing the {!account.name} account.
</apex:pageBlock>
</apex:page>

20
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 {!$User.FirstName}!">
You are viewing the {!account.name} 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 {!$User.FirstName}!">

21
Getting a Quick Start with Visualforce Overriding an Existing Page with a Visualforce Page

You are viewing the {!account.name} account.


</apex:pageBlock>
<apex:detail subject="{!account.ownerId}" 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 https://na1.salesforce.com, the new URL would be
https://na1.salesforce.com/apex/tabbedAccount. You will get the following error message:

22
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, https://Salesforce_instance/apex/tabbedAccount?id=001D000000IRt53.
After you add in an account ID, your page should display as follows:

23
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.

24
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($Action.Account.List, $ObjectType.Account)}"/>

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($Action.Contact.List, $ObjectType.Contact)}"/>

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:

https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb

25
Getting a Quick Start with Visualforce Adding and Customizing Input Field Labels

Displaying Field Values with Visualforce on page 19 has more information about retrieving the ID of a record.
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="Hello {!$User.FirstName}!">
You are viewing the {!account.name} account. <p/>
Change Account Name: <p/>
<apex:inputField value="{!account.name}"/> <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 {!account.name} 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

26
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: {!Contact.Name}">
<apex:pageBlockSection title="Contact Details" columns="1">
<apex:inputField value="{!Contact.Phone}"/>
<apex:outputField value="{!Contact.MobilePhone}"
label="Mobile #"/>
<apex:inputText value="{!Contact.Email}"
label="{!Contact.FirstName + '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,

https://Salesforce_instance/apex/myPage?id=003D000000Q513R

Displaying Field Values with Visualforce on page 19 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>

27
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: {!Account.Name}">
<apex:pageBlockSection title="Account Details" columns="1">
<apex:inputField value="{!Account.Name}" tabOrderHint="4"/>
<apex:inputField value="{!Account.Website}" tabOrderHint="3"/>
<apex:inputField value="{!Account.Industry}" tabOrderHint="2"/>
<apex:inputField value="{!Account.AnnualRevenue}" 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:

https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb

Displaying Field Values with Visualforce on page 19 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

28
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.

29
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="{!account.industry}"/>
<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.

30
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="{!Location.country}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{!Location.state}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{!Location.city}">
<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

31
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">
{!c.subject}
</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.

32
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 134.

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,
http://na3.salesforce.com/myCustomRelatedList?id=a00x00000003ij0.
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="{!account.Id}" relatedList="false" />
</apex:page>

33
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:

https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb

Displaying Field Values with Visualforce on page 19 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="{!account.Id}" 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="{!record.Name}" id="AccountNameDOM" />
<apex:facet name="header">Name</apex:facet>
</apex:column>
<apex:column >
<apex:outputField value="{!record.Type}" id="AccountTypeDOM" />
<apex:facet name="header">Type</apex:facet>
</apex:column>
<apex:column >
<apex:outputField value="{!record.Industry}"
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" />

34
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 Idea.Body, 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" />

35
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="{!Location.country}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{!Location.state}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{!Location.city}">
<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%">

36
Getting a Quick Start with Visualforce Converting a Page to a PDF File

<apex:outputText value="{!account.Name}" 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

37
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 {!$User.FirstName}!">
You are viewing the {!account.name} account.
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:pageBlockTable value="{!account.Contacts}" var="contact">
<apex:column value="{!contact.Name}"/>
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</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:

https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb

Displaying Field Values with Visualforce on page 19 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, {!account.Contacts} retrieves
the ID of the account that is currently in context and then traverses the relationship to retrieve the list of the associated contacts.

38
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="{!contact.Name}" 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="{!a.name}"/>

<apex:column headerValue="Industry">
<apex:inputField value="{!a.Industry}"/>
</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,
https://c.na1.visual.soma.force.com/apex/HelloWorld?id=001D000000IR35T 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.

39
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:

$CurrentPage.parameters.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 {!$User.FirstName}!">
You are displaying values from the {!account.name} account and a separate contact

that is specified by a query string parameter.


</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4" border="1">

<apex:column>
<apex:facet name="header">Name</apex:facet>
{!contact.Name}
</apex:column>
<apex:column>
<apex:facet name="header">Phone</apex:facet>
{!contact.Phone}
</apex:column>
</apex:dataTable>

40
Getting a Quick Start with Visualforce Getting Query String Parameters

</apex:pageBlock>
<apex:detail subject="{!$CurrentPage.parameters.cid}" 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:

https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53&cid=003D000000Q0bIE

Displaying Field Values with Visualforce on page 19 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

41
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="http://google.com/search?q={!account.name}">
Search Google
</apex:outputLink>

<apex:outputLink value="http://google.com/search">
Search Google
<apex:param name="q" value="{!account.name}"/>
</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 {!$User.FirstName}!">
You are displaying contacts from the {!account.name} account.
Click a contact's name to view his or her details.
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:form>
<apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4"
border="1">
<apex:column>
<apex:facet name="header">Name</apex:facet>
<apex:commandLink>
{!contact.Name}
<apex:param name="cid" value="{!contact.id}"/>
</apex:commandLink>
</apex:column>
<apex:column>
<apex:facet name="header">Phone</apex:facet>
{!contact.Phone}
</apex:column>
</apex:dataTable>

42
Getting a Quick Start with Visualforce Using Ajax in a Page

</apex:form>
</apex:pageBlock>
<apex:detail subject="{!$CurrentPage.parameters.cid}" 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,

https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53

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 42. 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 {!$User.FirstName}!">
You are displaying contacts from the {!account.name} account.

43
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="{!account.Contacts}" var="contact" cellPadding="4"
border="1">
<apex:column>
<apex:commandLink rerender="detail">
{!contact.Name}
<apex:param name="cid" value="{!contact.id}"/>
</apex:commandLink>
</apex:column>
</apex:dataTable>
</apex:form>
</apex:pageBlock>
<apex:outputPanel id="detail">
<apex:detail subject="{!$CurrentPage.parameters.cid}" 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 {!$User.FirstName}!">
You are displaying contacts from the {!account.name} account.
Click a contact's name to view his or her details.

44
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="{!account.Contacts}" var="contact" cellPadding="4"
border="1">
<apex:column>
<apex:commandLink rerender="detail">
{!contact.Name}
<apex:param name="cid" value="{!contact.id}"/>
</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="{!$CurrentPage.parameters.cid}"
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,

https://Salesforce_instance/apex/ajaxAsyncStatus?id=001x000xxx3Jsxb

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 reRender attribute isnt required. If you dont set it, the page does not refresh upon the specified event, but apex:param>
still sets the name and value of cid.
The resulting markup looks like this:
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$User.FirstName}!">

45
Getting a Quick Start with Visualforce Applying Ajax Behavior to Events on Any Component

You are displaying contacts from the {!account.name} account.


Mouse over a contact's name to view his or her details.
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:form>
<apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4"
border="1">
<apex:column>
<apex:outputPanel>
<apex:actionSupport event="onmouseover" rerender="detail">
<apex:param name="cid" value="{!contact.id}"/>
</apex:actionSupport>
{!contact.Name}
</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="{!$CurrentPage.parameters.cid}" 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

46
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 121.

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="{!$Resource.TestStyles}"/>

47
Customizing the Appearance and Output of Visualforce Pages Using the Lightning Design System

<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 the Lightning Design System


Use the <apex:slds> element to incorporate the Lightning Design System in your Visualforce pages and align them with the styling
of Lightning Experience. This component is a streamlined alternative to uploading the Lightning Design System as a static resource and
using it in your Visualforce pages.
Because you dont have to upload the Lightning Design System as a static resource, you can keep the syntax of your page simple and
stay under the 250-MB static resource limit. To use Lightning Design System stylesheets in your Visualforce page, add <apex:slds
/> anywhere in your page markup.
In general, the Lightning Design System is already scoped. However, if you set applyBodyTag or applyHtmlTag to false, you
must include the scoping class slds-scope. Within the scoping class, your markup can reference Lightning Design System styles
and assets.
To reference assets in the Lightning Design System, such as SVG icons and images, use the URLFOR() formula function and the
$Asset global variable. Use the following markup, for example, to reference the SVG account icon.

<svg aria-hidden="true" class="slds-icon">


<use xlink:href="{!URLFOR($Asset.SLDS,
'assets/icons/standard-sprite/svg/symbols.svg#account')}"></use>
</svg>

To use SVG icons, add the required XML namespaces by using xmlns="http://www.w3.org/2000/svg" and
xmlns:xlink="http://www.w3.org/1999/xlink" in the html tag.

Note: Currently, if you are using the Salesforce sidebar, header, or built-in stylesheets, you cant add attributes to the html tag.
This means that SVG icons arent supported on your page if you dont have showHeader, standardStylesheets, and
sidebar set to false.

Example: The following markup shows a simple account detail page. This page uses the Lightning Design System card element
and the account standard controller. This page also includes the account PNG icon.
Note that this page doesnt have any data in it, unless you load it with a record ID. The Lightning Design System doesnt support
components that bring data into your Visualforce pages, such as <apex:pageBlock> and <apex:detail>. To access
Salesforce data from pages using the Lightning Design System, instead use Remote Objects, JavaScript remoting, or the REST API.
<apex:page showHeader="false" standardStylesheets="false" sidebar="false"
docType="html-5.0" standardController="Account" applyBodyTag="False"
applyHtmlTag="False">
<head>
<title>{! Account.Name }</title>
<apex:slds />
</head>

<body class="slds-scope">
<!-- MASTHEAD -->

48
Customizing the Appearance and Output of Visualforce Pages Using the Lightning Design System

<p class="slds-text-heading--label slds-m-bottom--small">


Using the Lightning Design System in Visualforce
</p>
<!-- / MASTHEAD -->

<!-- PAGE HEADER -->


<div class="slds-page-header" role="banner">
<div class="slds-grid">
<div class="slds-col slds-has-flexi-truncate">
<!-- HEADING AREA -->
<p class="slds-text-title--caps slds-line-height--reset">Accounts</p>
<h1 class="slds-page-header__title slds-truncate" title="My Accounts">{!
Account.Name }</h1>
<span class="slds-icon_container slds-icon--small slds-icon-standard-account"
title="Account Standard Icon">
<img src="{!URLFOR($Asset.SLDS, 'assets/icons/standard/account_60.png')}"
alt="Account Standard Icon" />
</span>
<!-- / HEADING AREA -->
</div>
<div class="slds-col slds-no-flex slds-grid slds-align-top">
<button class="slds-button slds-button--neutral">New Account</button>
</div>
</div>
</div>
<!-- / PAGE HEADER -->

<!-- ACCOUNT DETAIL CARD -->


<div class="slds-panel slds-grid slds-grid--vertical slds-nowrap">
<div class="slds-form--stacked slds-grow slds-scrollable--y">

<div class="slds-panel__section">
<h3 class="slds-text-heading--small slds-m-bottom--medium">Account Detail</h3>

<div class="slds-form-element slds-hint-parent slds-has-divider--bottom">


<span class="slds-form-element__label">Name</span>
<div class="slds-form-element__control">
<span class="slds-form-element__static">{! Account.Name }</span>
</div>
</div>
<div class="slds-form-element slds-hint-parent slds-has-divider--bottom">
<span class="slds-form-element__label">Phone</span>
<div class="slds-form-element__control">
<span class="slds-form-element__static">{! Account.Phone }</span>
</div>
</div>
</div>
<div class="slds-panel__section slds-has-divider--bottom">
<div class="slds-media">
<div class="slds-media__body">
<div class="slds-button-group slds-m-top--small" role="group">
<button class="slds-button slds-button--neutral slds-grow">Edit</button>

<button class="slds-button slds-button--neutral slds-grow">Save</button>

49
Customizing the Appearance and Output of Visualforce Pages Using Custom Styles

<button class="slds-button slds-button--neutral slds-grow">New


Account</button>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- / ACCOUNT DETAIL CARD -->
</body>
</apex:page>

For more examples of Lightning Design System styling, see the Salesforce Lightning Design System reference site, and learn more
about the Lightning Design System on Trailhead.

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="{!$Resource.customCSS}" />
<h1>Testing Custom Stylesheets</h1>
<p>This text could go on forever...<br/><br/>
But it won't!</p>

<apex:outputLink value="http://www.salesforce.com" styleClass="newLink">


Click here to switch to www.salesforce.com
</apex:outputLink>
</apex:page>

50
Customizing the Appearance and Output of Visualforce Pages Suppressing the Salesforce User Interface and Styles

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
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 52.
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/dots.gif") }

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($Resource.myStyles, 'styles.css')}"/>

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.

51
Customizing the Appearance and Output of Visualforce Pages Defining Styles for a Components DOM ID

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.

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.

52
Customizing the Appearance and Output of Visualforce Pages Identifying the Salesforce Style Your Users See

The following stylesheets contain style classes you can reference. They are located in the /dCSS/ directory of your Salesforce instance.
dStandard.css Contains the majority of style definitions for standard objects and tabs.
allCustom.css 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.

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: $User.UITheme and
$User.UIThemeDisplayed. The difference between the two variables is that $User.UITheme returns the look and feel the
user is supposed to see, while $User.UIThemeDisplayed 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, $User.UIThemeDisplayed 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="{!$User.UIThemeDisplayed = 'Theme3'}">
<apex:stylesheet value="{!URLFOR($Resource.myStyles, 'newStyles.css')}" />
</apex:variable>
<apex:variable var="oldUI" value="oldSkinOn"
rendered="{!$User.UIThemeDisplayed != 'Theme3'}">
<apex:stylesheet value="{!URLFOR($Resource.myStyles, 'oldStyles.css')}" />
</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.

53
Customizing the Appearance and Output of Visualforce Pages HTML Comments and IE Conditional Comments

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 $User.UITheme variable to present alternate information to the user:
<apex:page showHeader="true" tabstyle="Case">
<apex:pageMessage severity="error" rendered="{!$User.UITheme = 'Theme3' &&
$User.UIThemeDisplayed != '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>
<apex:ListViews type="Case" rendered="{!$User.UITheme = 'Theme3' &&
$User.UIThemeDisplayed = 'Theme3'}"/>
</apex:page>

Notice that although $User.UITheme equals Theme3, $User.UIThemeDisplayed 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($Resource.BrowserCompatibility, 'css/style.css')}"/>

<!--[if lt IE 7]>
<script type="text/javascript"
src="{!URLFOR($Resource.BrowserCompatibility, 'js/obsolete-ie-shim.js')}>
</script>
<link rel="stylesheet" type="text/css"
href="{!URLFOR($Resource.BrowserCompatibility, 'css/ie-old-styles.css')}"
/>
<![endif]-->

<!--[if IE 7]>
<link rel="stylesheet" type="text/css"
href="{!URLFOR($Resource.BrowserCompatibility, 'css/ie7-styles.css')}" />
<![endif]-->
</head>

<body>
<h1>Browser Compatibility</h1>
<p>It's not just a job. It's an adventure.</p>

54
Customizing the Appearance and Output of Visualforce Pages HTML Tags Added or Modified by Visualforce

</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.

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.

55
Customizing the Appearance and Output of Visualforce Pages Manually Override Automatic <html> and <body> Tag
Generation

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>
<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="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"/>
</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.

56
Customizing the Appearance and Output of Visualforce Pages Creating an Empty HTML5 Container Page

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 Force.com 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"
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.

57
Customizing the Appearance and Output of Visualforce Pages Using a Custom Doctype

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"
"http://www.w3.org/TR/html4/loose.dtd">

You can specify a different doctype for a Visualforce page by using the docType attribute on the <apex:page> tag.
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/icon-person.gif" 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.

58
Customizing the Appearance and Output of Visualforce Pages Using a Custom ContentType

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/vnd.ms-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 http://www.iana.org/assignments/media-types/.

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/vnd.ms-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 38.
<apex:page standardController="Account">

<!-- This page must be accessed with an Account Id in the URL. For example:
https://<salesforceInstance>/apex/myPage?id=001D000000JRBet -->

<apex:pageBlock title="Contacts">
<apex:pageBlockTable value="{!account.Contacts}" var="contact">
<apex:column value="{!contact.Name}"/>
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</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/vnd.ms-excel">


<apex:pageBlock title="Contacts">
<apex:pageBlockTable value="{!account.Contacts}" var="contact">
<apex:column value="{!contact.Name}"/>
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</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.

59
Customizing the Appearance and Output of Visualforce Pages Setting Custom HTML Attributes on Visualforce Components

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"/>
</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>

60
Customizing the Appearance and Output of Visualforce Pages Setting Custom HTML Attributes on Visualforce Components

<apex:inputHidden>
<apex:inputSecret>
<apex:inputText>
<apex:inputTextarea>
<apex:messages>
<apex:outputField>
<apex:outputLabel>
<apex:outputLink>
<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 351.
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="#">{! item.Name}</a></li>
</apex:repeat>
</ul>

Pass-through attributes arent supported in dynamic Visualforce.

61
Customizing the Appearance and Output of Visualforce Pages Offline Caching Using the HTML5 manifest Attribute

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>
<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
index.html
stylesheet.css
images/logo.png
scripts/main.js
</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($Resource.Styles,'pdf.css')}"/>

<h1>Welcome to Universal Samples!</h1>

62
Customizing the Appearance and Output of Visualforce Pages Render a Visualforce Page as a PDF File

<p>Thank you, <b><apex:outputText value=" {!Account.Name}"/></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="{!Account.Name}"/></td>
</tr>
<tr><th>Account Rep</th>
<td><apex:outputText value="{!Account.Owner.Name}"/></td>
</tr>
<tr><th>Customer Since</th>
<td><apex:outputText value="{0,date,long}">
<apex:param value="{!Account.CreatedDate}"/>
</apex:outputText></td>
</tr>
</table>

</apex:page>

63
Customizing the Appearance and Output of Visualforce Pages Add a Save as PDF Feature to a Visualforce 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 }">

<!--
This page must be called with an Account ID in the URL, e.g.:
https://<salesforceInstance>/apex/AccountContactsPdf?id=001D000000JRBet
-->

<apex:form rendered="{! renderingService != 'PDF' }"


style="text-align: right; margin: 10px;">
<apex:commandLink action="{! saveToPdf }" value="Save to PDF">

64
Customizing the Appearance and Output of Visualforce Pages Add a Save as PDF Feature to a Visualforce Page

<apex:param assignTo="{! renderedFileName }" value="Contact-List.pdf"/>


</apex:commandLink>
<hr/>
</apex:form>

<h1>Contacts for {! Account.Name}</h1>

<apex:dataTable value="{! Account.Contacts }" var="contact">


<apex:column headerValue="Name" value="{! contact.Name }"/>
<apex:column headerValue="Title" value="{! contact.Title }"/>
<apex:column headerValue="Phone" value="{! contact.Phone }"/>
<apex:column headerValue="Email" value="{! contact.Email }"/>
</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(ApexPages.StandardController 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 = this.sanitizeFileName(value); }
}

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


public String renderedContentType {
get {
String renderedContentType = 'text/html'; // the default

if( ! this.renderingAsHtml() ) {
// Provides a MIME type for a PDF document
renderedContentType = 'application/pdf';

65
Customizing the Appearance and Output of Visualforce Pages Add a Save as PDF Feature to a Visualforce Page

// Add a file name for the PDF file


if( this.renderedFileName != null) {
// This is supposed to set the file name, but it doesn't work
renderedContentType += '#' + this.renderedFileName;

// This is a work-around to set the file name


ApexPages.currentPage().getHeaders().put(
'content-disposition', 'attachment; filename=' +
this.renderedFileName);
}
}

return renderedContentType;
}
}

// Are we rendering to HTML or PDF?


public Boolean renderingAsHtml() {
return ( (renderingService == null) ||
( ! renderingService.startsWith('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 =
unsafeName.replaceAll('[^' + 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.
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.

66
Customizing the Appearance and Output of Visualforce Pages Render a Visualforce Page as PDF from Apex

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 71.

Render a Visualforce Page as PDF from Apex


You can use the PageReference.getContentAsPDF() 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 -->


<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" />

67
Customizing the Appearance and Output of Visualforce Pages Render a Visualforce Page as PDF from Apex

</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; } // Account selected on Visualforce page
public String selectedReport { get; set; } // Report selected
public String recipientEmail { get; set; } // 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(String.isBlank(this.selectedAccount) || String.isBlank(this.recipientEmail)) {

ApexPages.addMessage(new
ApexPages.Message(ApexPages.Severity.ERROR,
'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 = :this.selectedAccount
LIMIT 1];
if(null == account) {
// Got a bogus ID from the form submission
ApexPages.addMessage(new
ApexPages.Message(ApexPages.Severity.ERROR,
'Invalid account. Please correct and resubmit.'));
return null; // early out
}

// Create email
Messaging.SingleEmailMessage message = new Messaging.SingleEmailMessage();
message.setToAddresses(new String[]{ this.recipientEmail });
message.setSubject('Account summary for ' + account.Name);
message.setHtmlBody('Here\'s a summary for the ' + account.Name + ' account.');

// Create PDF
PageReference reportPage =
(PageReference)this.reportPagesIndex.get(this.selectedReport);
reportPage.getParameters().put('id', this.selectedAccount);
Blob reportPdf;

68
Customizing the Appearance and Output of Visualforce Pages Render a Visualforce Page as PDF from Apex

try {
reportPdf = reportPage.getContentAsPDF();
}
catch (Exception e) {
reportPdf = Blob.valueOf(e.getMessage());
}

// Attach PDF to email and send


Messaging.EmailFileAttachment attachment = new Messaging.EmailFileAttachment();
attachment.setContentType('application/pdf');
attachment.setFileName('AccountSummary-' + account.Name + '.pdf');
attachment.setInline(false);
attachment.setBody(reportPdf);
message.setFileAttachments(new Messaging.EmailFileAttachment[]{ attachment });
Messaging.sendEmail(new Messaging.SingleEmailMessage[]{ message });

ApexPages.addMessage(new
ApexPages.Message(ApexPages.Severity.INFO,
'Email sent with PDF attachment to ' + this.recipientEmail));

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]) {
recentAccounts.add(new SelectOption(acct.Id, acct.Name));
}
}
return recentAccounts;
}
set;
}

// List of available reports, for the Summary Format selection menu


public List<SelectOption> reportFormats {
get {
if(null == reportFormats) {
reportFormats = new List<SelectOption>();
for(Map <String,Object> report : reports) {
reportFormats.add(new SelectOption(
(String)report.get('name'), (String)report.get('label')));
}
}
return reportFormats;

69
Customizing the Appearance and Output of Visualforce Pages Render a Visualforce Page as PDF from Apex

}
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>();
simpleReport.put('name', 'simple');
simpleReport.put('label', 'Simple');
simpleReport.put('page', Page.ReportAccountSimple);
reports.add(simpleReport);

// Add your own, more complete list of PDF templates here

// Index the page names for the reports


this.reportPagesIndex = new Map<String,PageReference>();
for(Map<String,Object> report : reports) {
this.reportPagesIndex.put(
(String)report.get('name'), (PageReference)report.get('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.
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 Messaging.SingleEmailMessage class to assemble an email message, setting the To, Subject, and Body email
message values.

70
Customizing the Appearance and Output of Visualforce Pages Fonts Available When Using Visualforce PDF Rendering

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 PageReference.getContentAsPdf(), 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
Messaging.EmailFileAttachment 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.:
https://<salesforceInstance>/apex/ReportAccountSimple?id=001D000000JRBet
-->

<h1>Account Summary for {! Account.Name }</h1>

<table>
<tr><th>Phone</th> <td><apex:outputText value="{! Account.Phone }"/></td></tr>
<tr><th>Fax</th> <td><apex:outputText value="{! Account.Fax }"/></td></tr>
<tr><th>Website</th><td><apex:outputText value="{! Account.Website }"/></td></tr>

</table>

<p><apex:outputText value="{! Account.Description }"/></p>

</apex:page>

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

71
Customizing the Appearance and Output of Visualforce Pages Fonts Available When Using Visualforce PDF Rendering

Typeface font-family Values

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
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

72
Customizing the Appearance and Output of Visualforce Pages Fonts Available When Using Visualforce PDF Rendering

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


public PageReference print() {
renderAs = 'PDF';
return null;
}

73
Customizing the Appearance and Output of Visualforce Pages Visualforce PDF Rendering Considerations and Limitations

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.
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.

74
Customizing the Appearance and Output of Visualforce Pages Component Behavior 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>
<apex:repeat>
<apex:stylesheet> (as long as the URL isnt directly referencing Salesforce style sheets)
<apex:variable>

75
Customizing the Appearance and Output of Visualforce Pages Component Behavior When Rendered as PDF

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>
<apex:pageBlockSectionItem>
<apex:pageBlockTable>
<apex:pageMessage>
<apex:pageMessages>

76
Customizing the Appearance and Output of Visualforce Pages Component Behavior When Rendered as PDF

<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>

77
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 Force.com 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 Force.com 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 Force.com 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 {!account.name} to return the value of the name field on the account that is currently in context.

78
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 Force.com 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
{!contact.Account.Owner.FirstName} (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
{!account.Contacts} 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.

79
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="{!account.name}"/>
<apex:inputField value="{!account.site}"/>
<apex:inputField value="{!account.type}"/>
<apex:inputField value="{!account.accountNumber}"/>
</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:

https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb

Displaying Field Values with Visualforce on page 19 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>

80
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:
{!$ObjectType.objectname.accessible}

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:
{!$ObjectType.Lead.accessible}

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="{!$ObjectType.Lead.accessible}">
<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="{!$ObjectType.Lead.accessible}">
<p>This text will display if you can see the Lead object.</p>
</apex:pageBlock>
<apex:pageBlock rendered="{! NOT($ObjectType.Lead.accessible) }">
<p>Sorry, but you cannot see the data because you do not have access to the Lead
object.</p>

81
Standard Controllers Checking for Object Accessibility

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

82
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.

83
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="{!a.name}"/>
</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 86.
As with queries in the Force.com 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 100.

SEE ALSO:
Force.com SOQL and SOSL Reference: Relationship Queries

84
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>

85
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">
{!a.name}
</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 93.

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">
{!a.name}
</apex:dataList>
</apex:pageBlockSection>
</apex:form>

86
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="{!opp.name}"/>
<apex:column headerValue="Stage">
<apex:inputField value="{!opp.stageName}"/>
</apex:column>
<apex:column headerValue="Close Date">
<apex:inputField value="{!opp.closeDate}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>

87
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="{!opp.name}"/>
<apex:column headerValue="Stage">
<apex:inputField value="{!opp.stageName}"/>
</apex:column>
<apex:column headerValue="Close Date">
<apex:inputField value="{!opp.closeDate}"/>
</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:

88
Standard List Controllers Editing Records with List Controllers

For more information, see Mass-Updating Records with a Custom List Controller on page 140.

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.

89
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.

90
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 = :ApexPages.currentPage().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 {!$User.FirstName}">
You belong to Account Name: <apex:inputField value="{!account.name}"/>
<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.

91
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 = ApexPages.currentPage().getParameters().get('id');
account = (id == null) ? new Account() :
[SELECT Name, Phone, Industry FROM Account WHERE Id = :id];
}

public PageReference save() {


try {
upsert(account);
} catch(System.DMLException e) {
ApexPages.addMessages(e);
return null;
}
// After successful Save, navigate to the default view page
PageReference redirectSuccess = new ApexPages.StandardController(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="{!Account.name}"/>
<apex:inputField value="{!Account.phone}"/>
<apex:inputField value="{!Account.industry}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>

92
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
ApexPages.StandardController 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(ApexPages.StandardController stdController) {
this.acct = (Account)stdController.getRecord();
}

public String getGreeting() {


return 'Hello ' + acct.name + ' (' + acct.id + ')';
}
}

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="{!account.name}"/> <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(ApexPages.StandardController acon) { }

93
Custom Controllers and Controller Extensions Building a Custom List Controller

public String getFoo() {


return 'foo-One';
}
}

public class ExtTwo {


public ExtTwo(ApexPages.StandardController 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 {
// ApexPages.StandardSetController must be instantiated
// for standard list controllers
public ApexPages.StandardSetController setCon {
get {
if(setCon == null) {
setCon = new ApexPages.StandardSetController(Database.getQueryLocator(
[SELECT Name, CloseDate FROM Opportunity]));
}
return setCon;
}
set;
}

// Initialize setCon and return a list of records


public List<Opportunity> getOpportunities() {
return (List<Opportunity>) setCon.getRecords();
}
}

94
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="{!o.Name}"/>
<apex:column value="{!o.CloseDate}"/>
</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(ApexPages.StandardSetController controller) {
this.acct = (Account)controller.getRecord();
}

public ApexPages.StandardSetController accountRecords {


get {
if(accountRecords == null) {
accountRecords = new ApexPages.StandardSetController(
Database.getQueryLocator([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>) accountRecords.getRecords();
}
}

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">
{!acct.name}
</apex:dataList>
</apex:pageBlockSection>
<apex:panelGrid columns="2">
<apex:commandLink action="{!previous}">Previous</apex:commandlink>

95
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 91, 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 123.

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 91, 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.

96
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="{!l.name}"/>
<apex:column value="{!l.email}"/>
<apex:column value="{!l.phone}"/>
</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;
}

97
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 91.
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();

98
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(): {!contactMethod2.name}<br/>
getContactMethod1(): {!contactMethod1.name}
</apex:page>

<apex:page controller="conVsBad">
getContactMethod2(): {!contactMethod2.name}<br/>
getContactMethod1(): {!contactMethod1.name}
</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

99
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 714. 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 Opportunity.IsClosed = 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);

100
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="{!product.Name}" />
</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 Force.com Apex Code Developer's Guide

Considerations for Creating Custom Controllers and Controller


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

101
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 98.
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 Force.com 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

102
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:

103
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.

104
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 105.
For a specific example of a get request, see Examples of Visualforce Page Execution Order on page 107.

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:

105
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.

106
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 107.

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>

107
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 = :ApexPages.currentPage().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) {


this.acct = (Account)controller.getAccount();
}

public String getGreeting() {


return acct.name + ' Current Information';
}

public void resetEmp() {


acct.numberofemployees = 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="{!$ObjectType.account.fields.Name.label}: "
for="acctName"/>

108
Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order

<apex:outputField value="{!account.name}" id="acctName"/>


<br/>
<apex:outputLabel
value="{!$ObjectType.account.fields.NumberOfEmployees.label}: "
for="emps"/>
<apex:outputField value="{!account.NumberOfEmployees}" id="emps"/>
<br/>
</apex:pageBlock>
<apex:pageBlock title="Variable values">
<c:editMode value="{!$CurrentPage.parameters.key}"/>
</apex:pageBlock>
<apex:form rendered="{!$CurrentPage.parameters.key = 'true'}">
<apex:pageBlock title="Update the Account" id="thePageBlock">
<apex:pageBlockSection columns="1">
<apex:inputField id="aName" value="{!account.name}"/>
<apex:inputField value="{!account.NumberOfEmployees}"/>
<apex:pageBlockSectionItem>
<apex:outputLabel value="{!$ObjectType.account.fields.Industry.label}"

for="acctIndustry"/>
<apex:actionRegion>
<apex:inputField value="{!account.Industry}" 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
https://Salesforce_instance/apex/setEmps?id=recordId, 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:

109
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="{!$CurrentPage.parameters.key}"/>

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
{!$CurrentPage.parameters.key}. 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="{!$CurrentPage.parameters.key = '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);
}

110
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
https://Salesforce_instance/apex/setEmps?id=recordId&key=false, 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="{!$CurrentPage.parameters.key}"/>

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 {!$CurrentPage.parameters.key}. 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.

111
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="{!$CurrentPage.parameters.key = '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
https://Salesforce_instance/apex/setEmps?id=recordId&key=true, 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.

112
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="{!$CurrentPage.parameters.key}"/>

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 {!$CurrentPage.parameters.key}. 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="{!$CurrentPage.parameters.key = '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.

113
Custom Controllers and Controller Extensions Testing Custom Controllers and Controller Extensions

<apex:form rendered="{!$CurrentPage.parameters.key = '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 96, but

114
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 String firstName;


private String lastName;
private String company;
private String email;
private String qp;

public thecontroller() {
this.qp = ApexPages.currentPage().getParameters().get('qp');
}

public String getFirstName() {


return this.firstName;
}

public void setFirstName(String firstName) {


this.firstName = firstName;
}

public String getLastName() {


return this.lastName;
}

public void setLastName(String lastName) {


this.lastName = lastName;
}

public String getCompany() {


return this.company;
}

public void setCompany(String company) {


this.company = company;
}

public String getEmail() {


return this.email;
}

public void setEmail(String email) {


this.email = email;
}

public PageReference save() {


PageReference p = null;

if (this.qp == null || !'yyyy'.equals(this.qp)) {


p = Page.failure;
p.getParameters().put('error', 'noParam');
} else {
try {

115
Custom Controllers and Controller Extensions Testing Custom Controllers and Controller Extensions

Lead newlead = new Lead(LastName=this.lastName,


FirstName=this.firstName,
Company=this.company,
Email=this.email);
insert newlead;
} catch (Exception e) {
p = Page.failure;
p.getParameters().put('error', 'noInsert');
}
}

if (p == null) {
p = Page.success;
}

p.setRedirect(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 = Page.success;
Test.setCurrentPage(pageRef);

thecontroller controller = new thecontroller();


String nextPage = controller.save().getUrl();

// Verify that page fails without parameters


System.assertEquals('/apex/failure?error=noParam', nextPage);

// Add parameters to page URL


ApexPages.currentPage().getParameters().put('qp', 'yyyy');

116
Custom Controllers and Controller Extensions Validation Rules and Custom Controllers

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


controller = new thecontroller();
controller.setLastName('lastname');
controller.setFirstName('firstname');
controller.setCompany('acme');
controller.setEmail('[email protected]');
nextPage = controller.save().getUrl();

// Verify that the success page displays


System.assertEquals('/apex/success', nextPage);
Lead[] leads = [select id, email from lead where Company = 'acme'];
System.assertEquals('[email protected]', leads[0].email);
}
}

Tip: If you are testing your controller you may see the following error message:
Method does not exist or incorrect signature: Test.setCurrentPage(System.PageReference)

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 Force.com 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 {!$User.FirstName}!">
This is your new page for the {!name} controller. <br/>
You are viewing the {!account.name} account.<br/><br/>
Change Account Name: <p></p>
<apex:inputField value="{!account.name}"/> <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,
http://na3.salesforce.com/apex/myValidationPage?id=001x000xxx3Jsxb.

117
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){
ApexPages.addMessages(ex);
}
return null;
}

public String getName() {


return 'MyController';
}

public Account getAccount() {


if(account == null)
account = [select id, name, numberoflocations__c from Account
where id = :ApexPages.currentPage().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 Schema.getGlobalDescribe.

118
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 = System.now();
return '' + t1;
}

public String getT2() {


if (t2 == null) t2 = System.now();
return '' + t2;
}
}

119
CHAPTER 8 Advanced Examples
The examples in the quick start tutorial are considered beginning examples, and primarily use only Visualforce markup. Advanced
examples use Force.com Apex code in addition to Visualforce markup.

Creating Your Firs