Getting a Quick Start with Visualforce. salesforce Visualforce Developer Guide
Publicitate
Publicitate
CHAPTER 3
Getting a Quick Start with Visualforce
To showcase the essential elements of Visualforce, this chapter includes a set of examples that demonstrate features of the language.
While the examples do not go into every detail, rule, or exception for every tag or controller, new Visualforce developers can use this tutorial to understand how Visualforce works before proceeding to the more detailed descriptions in the remainder of this guide.
The examples are broken up into beginner and advanced sections. The beginner examples primarily use Visualforce markup. The advanced examples use Force.com Apex code in addition to Visualforce markup.
Advanced examples that require Apex are in their own chapter.
Compiling Visualforce Successfully
You can't save your Visualforce pages and components unless they correctly compile. Here's a list of things to watch out for when creating Visualforce pages:
•
Verify that your component tags start with the correct namespace identifier like apex:
—that is, apex
followed by a colon.
•
Make sure that every opening quote and bracket has a closing one.
•
Verify that the controller or controller extension is named correctly.
•
Visualforce pages and components created using Salesforce API version 19.0 or higher must be written as well-formed XML. In general, this means that elements must be correctly nested, non-empty elements must have an end tag, empty elements must be terminated with a closing slash (“
/
”), and so on. The World Wide Web Consortium (W3C) provides an article on the specifications of well-formed XML .
The following exceptions are allowed:
–
Code that violates well-formed XML is permitted inside JavaScript. For example, you don't need to use
<![CDATA[]]>
tags in Visualforce.
–
Code that violates well-formed XML is permitted inside expressions. For example, you don't need to escape quotation marks inside formulas.
–
XML directives that are normally required at the beginning of a page—such as
<?xml
version= "1.0" encoding= "UTF-8"?>
—can occur inside top-level container tags, like
<apex:page >
and
<apex:component >
.
Creating Your First Page
bar as follows: https://
Salesforce_instance
/apex/
myNewPageName
For example, if you want to create a page called “HelloWorld” and your Salesforce organization uses na3.salesforce.com
, enter http://na3.salesforce.com/apex/HelloWorld
.
16
Getting a Quick Start with Visualforce Creating Your First Page
Because the page does not yet exist, you are directed to an intermediary page from which you can create your new page. Click Create
Page
<myNewPageName>
to create it automatically.
Note: If you do not have Visualforce development mode enabled, you can also create a new page from Setup by entering
Visualforce Pages
in the
Quick Find
box, then selecting Visualforce Pages, and then clicking New.
Visualforce pages can always be edited from this part of setup, but to see the results of your edits you have to navigate to the URL of your page. For that reason, most developers prefer to work with development mode enabled so they can view and edit pages in a single window.
A New Visualforce Page
You now have a Visualforce page that includes default text. To edit your new page, click the Page Editor bar that appears at the bottom of the browser. It expands to show you the following Visualforce markup:
<apex:page >
<!-- Begin Default Content REMOVE THIS -->
<h1 >Congratulations </h1 >
This is your new Apex Page: HelloWorld
<!-- End Default Content REMOVE THIS -->
</apex:page >
This default markup includes the only required tag for any page— the
<apex:page >
tag that begins and ends any page markup.
Embedded within the start and close
<apex:page >
tags is plain text, some of which is formatted with a standard HTML tag,
<h1 >
.
As long as you keep the required
<apex:page >
tag you can add as much plain text or valid HTML to this page as you want. For example, after entering the following code and clicking Save in the Page Editor, the page displays the text “Hello World!” in bold:
<apex:page >
<b >Hello World!
</b >
</apex:page >
Tip: Pay attention to warnings—the Visualforce editor displays a warning if you save a page with HTML that does not include a matching end tag for every opened tag. Although the page saves, this malformed HTML might cause problems in your rendered page.
17
Getting a Quick Start with Visualforce Displaying Field Values with Visualforce
Displaying Field Values with Visualforce
Visualforce pages use the same expression language as formulas—that is, anything inside
{! }
is evaluated as an expression that can access values from records that are currently in context. For example, you can display the current user's first name by adding the
{!$User.FirstName}
expression to a page:
<apex:page >
Hello {!$User.FirstName}!
</apex:page >
$User
is a global variable that always represents the current user record. All global variables are referenced with a $ symbol. For a list
of global variables that you can use in Visualforce, see Global Variables
on page 602.
To access fields from a record that is not globally available, like a specific account, contact, or custom object record, you need to associate your page with a controller. Controllers provide pages with the data and business logic that make your application run, including the logic that specifies how to access a particular object's records. While you can define a custom controller for any page with Apex, Salesforce includes standard controllers for every standard and custom object.
For example, to use the standard controller for accounts, add the standardController
attribute to the
<apex:page >
tag, and assign it the name of the account object:
<apex:page standardController= "Account" >
Hello {!$User.FirstName}!
</apex:page >
After you save your page, the Accounts tab is highlighted for the page, and the look-and-feel for the components on the page match the Accounts tab. Additionally, you can now access fields on the account record currently in context by using
{!account.
<fieldName>}
expression syntax.
For example, to display an account's name on a page, use
{!account.name}
in the page markup:
<apex:page standardController= "Account" >
Hello {!$User.FirstName}!
<p >You are viewing the {!account.name} account.
</p >
</apex:page >
The
{!account.name}
expression makes a call to the getAccount()
method in the standard Account controller to return the record ID of the account currently in context. It then uses dot notation to access the name
field for that record.
Note: You cannot access parent objects using this expression language. In other words,
{!account.parent.name}
will return an error.
Note: When you save a page, the value
attribute of all input components—
<apex:inputField >
,
<apex:inputText >
, and so on—is validated to ensure it’s a single expression, with no literal text or white space, and is a valid reference to a single controller method or object property. An error will prevent saving the page.
To bring an account record into the current context, you must add a query parameter to the page URL that specifies the ID of the record.
To do this:
1. Find the ID of an account by any means you wish. One easy way is to view the detail page of an account record and copy the character code at the end of the URL. For example, if you navigate to an account detail page with the following URL: https://na3.salesforce.com/001D000000IRt53
Then
001D000000IRt53
is the ID for the account.
18
Getting a Quick Start with Visualforce Using the Visualforce Component Library
2. Back on your page, add the account ID as a query string parameter to the URL in your browser's address bar. For example, if your page is located at: https://na3.salesforce.com/apex/HelloWorld2
Add
?id=001D000000IRt53
to the end of the URL: https://
Salesforce_instance
/apex/HelloWorld2?id=001D000000IRt53
Note:
If you use the id
parameter in a URL, it must refer to the same entity referred to in the standard controller.
Once an account ID is specified in the URL, the page displays the appropriate account name, as shown in the following figure.
Displaying Account Data in a Visualforce Page
Using the Visualforce Component Library
Up to this point, the only Visualforce tag that has been used in the examples is the mandatory
<apex:page >
tag that must be placed at the start and end of all Visualforce markup. However, just as you can insert images or tables into an HTML document with the
<img > or
<table >
tags, respectively, you can add user interface components to your Visualforce pages using tags that are defined in the
Visualforce component library.
For example, to add a component that looks like a section on a detail page, use the
<apex:pageBlock >
component tag:
<apex:page standardController= "Account" >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
You are viewing the {!account.name} account.
</apex:pageBlock >
</apex:page >
19
Getting a Quick Start with Visualforce
The
<apex:pageBlock >
Component
Using the Visualforce Component Library
Tags also exist for other common Salesforce interface components, such as related lists, detail pages, and input fields. For example, to add the content of a detail page, use the
<apex:detail >
component tag:
<apex:page standardController= "Account" >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
You are viewing the {!account.name} account.
</apex:pageBlock >
<apex:detail/ >
</apex:page >
The
<apex:detail >
Component Without Attributes
Without any specified attributes on the tag,
<apex:detail >
displays the complete detail view for the context record. If you want to modify properties such as which record details are displayed, or whether related lists or the title appear, you can use attributes on the tag. For example, the following markup displays the details of the context account's owner, without related lists or a colored title bar:
<apex:page standardController= "Account" >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
20
Getting a Quick Start with Visualforce Overriding an Existing Page with a Visualforce Page
You are viewing the {!account.name} account.
</apex:pageBlock >
<apex:detail subject= "{!account.ownerId}" relatedList= "false" title= "false" />
</apex:page >
The
<apex:detail >
Component Without Related List or Title Elements
To browse the component library, click Component Reference in the Page Editor. From this page you can drill down into any component to see the attributes that are available for each, including any
that you define.
SEE ALSO:
Overriding an Existing Page with a Visualforce Page
Suppose you want to change the format of an existing page, such as the standard account detail page. All the information for an account displays on a single page. If there's a lot of information, you might end up doing a lot of scrolling. Using a Visualforce page you can make each section for an account display in a tab, such as contacts, opportunities, and so on.
First, create a new Visualforce page using the quick fix.
1. In your browser, add the text
/apex/tabbedAccount
to the URL for your Salesforce instance. For example, if your Salesforce instance is https://na1.salesforce.com
, the new URL would be https://na1.salesforce.com/apex/tabbedAccount
. You will get the following error message:
21
Getting a Quick Start with Visualforce Overriding an Existing Page with a Visualforce Page
2. Click Create Page tabbedAccount to create the new page.
3. Click the Page Editor link in the bottom left corner of the page. This displays the code for the new page, which should look like this:
<apex:page >
<!-- Begin Default Content REMOVE THIS -->
<h1 >Congratulations </h1 >
This is your new Page: tabbedAccount
<!-- End Default Content REMOVE THIS -->
</apex:page >
4. Replace the existing code with the following and click Save:
<apex:page standardController= "Account" showHeader= "true" tabStyle= "account" >
<style >
.activeTab {background-color: #236FBD; color:white; background-image:none}
.inactiveTab { background-color: lightgrey; color:black; background-image:none}
</style >
<apex:tabPanel switchType= "client" selectedTab= "tabdetails" id= "AccountTabPanel" tabClass= 'activeTab' inactiveTabClass= 'inactiveTab' >
<apex:tab label= "Details" name= "AccDetails" id= "tabdetails" >
<apex:detail relatedList= "false" title= "true" />
</apex:tab >
<apex:tab label= "Contacts" name= "Contacts" id= "tabContact" >
<apex:relatedList subject= "{!account}" list= "contacts" />
</apex:tab >
<apex:tab label= "Opportunities" name= "Opportunities" id= "tabOpp" >
<apex:relatedList subject= "{!account}" list= "opportunities" />
</apex:tab >
<apex:tab label= "Open Activities" name= "OpenActivities" id= "tabOpenAct" >
<apex:relatedList subject= "{!account}" list= "OpenActivities" />
</apex:tab >
<apex:tab label= "Notes and Attachments" name= "NotesAndAttachments" id= "tabNoteAtt" >
<apex:relatedList subject= "{!account}" list= "CombinedAttachments" />
</apex:tab >
</apex:tabPanel >
</apex:page >
5. Notice that there is no data in the Account page. You need to specify the ID of a particular account in the URL, as you've done with previous pages, for example, https://Salesforce_instance/apex/tabbedAccount?id=001D000000IRt53
.
After you add in an account ID, your page should display as follows:
22
Getting a Quick Start with Visualforce Overriding an Existing Page with a Visualforce Page
Things to note about the page markup:
•
<style >
is actually part of CSS markup, not Visualforce markup. It defines the styles for two types of tabs: activeTab and inactiveTab.
•
<apex:tabPanel >
is used to generate the tabs. Notice how it uses the following attributes:
–
tabClass
attribute: specifies the style class used to display a tab when it is active.
–
inactiveTabClass
attribute: specifies the style class used to display a tab when it is inactive.
•
Within the definition of the tab panel, is the definition of each child tab component,
<apex:tab >
. The first tab uses the
<apex:detail >
tag to return that portion of the detail view for the page:
<apex:tab label= "Details" name= "AccDetails" id= "tabdetails" >
<apex:detail relatedList= "false" title= "true" />
</apex:tab >
While the rest of the tabs use the
<apex:relatedList >
to specify the different parts of the account page. The following is the tab for contacts. It uses an existing list of contacts.
<apex:tab label= "Contacts" name= "Contacts" id= "tabContact" >
<apex:relatedList subject= "{!account}" list= "contacts" />
</apex:tab >
Now that you've created a page to display an account with tabs, you can use this page to override the detail view for all accounts.
1. From the object management settings for accounts, go to Buttons, Links, and Actions.
2. Click Edit next to View.
3. For
Override With
select Visualforce Page.
4. From the Visualforce Page drop-down list, select tabbedAccount.
5. Click Save.
23
Getting a Quick Start with Visualforce Redirecting to a Standard Object List Page
Click the Account tab, and select any account. The detail for the account is now displayed with tabs.
SEE ALSO:
Salesforce Help: Find Object Management Settings
Redirecting to a Standard Object List Page
For buttons or links that navigate a user to a standard tab, you can redirect the content to present a list of standard objects.
Create a Visualforce page with the following markup:
<apex:page action= "{!URLFOR($Action.Account.List, $ObjectType.Account)}" />
The user will see a page that resembles the following:
Overriding the Account Detail Page
The Visualforce page can also refer to other standard objects, such as contacts, by changing the reference to the standard object. For example:
<apex:page action= "{!URLFOR($Action.Contact.List, $ObjectType.Contact)}" />
Using Input Components in a Page
So far the examples in this quick start tutorial show ways that you can display data in a Visualforce page. To capture input from a user, use the
<apex:form >
tag with one or more input components and a
<apex:commandLink >
or
<apex:commandButton > tag to submit the form.
The input component tag that is most often used in a form is
<apex:inputField >
. This tag renders the appropriate input widget based on a standard or custom object field’s type. For example, if you use an
<apex:inputField >
tag to display a date field, a calendar widget displays on the form. If you use an
<apex:inputField >
tag to display a picklist field, a drop-down list displays instead. The
<apex:inputField >
tag can be used to capture user input for any standard or custom object field, and respects any metadata that is set on the field definition, such as whether the field is required or unique, or whether the current user has permission to view or edit it.
For example, the following page allows users to edit and save the name of an account:
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter in the URL for the page. For example: https://
Salesforce_instance
/apex/myPage?id=001x000xxx3Jsxb
24
Getting a Quick Start with Visualforce Adding and Customizing Input Field Labels
<apex:page standardController= "Account" >
<apex:form >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
You are viewing the {!account.name} account.
<p/ >
Change Account Name: <p/ >
<apex:inputField value= "{!account.name}" /> <p/ >
<apex:commandButton action= "{!save}" value= "Save New Account Name" />
</apex:pageBlock >
</apex:form >
</apex:page >
Notice in the example that:
•
The
<apex:inputField >
tag is bound to the account name
field by setting the tag’s value
attribute. The expression contains the familiar
{!account.name}
dot-notation used to display the field’s value elsewhere in the page.
•
The
<apex:commandButton >
tag has an action
attribute. The value for this attribute invokes the save
action of the standard Account controller, which performs identically to the Save button on the standard Account edit page.
Note:
When you save a page, the value
attribute of all input components—
<apex:inputField >
,
<apex:inputText >
, and so on—is validated to ensure it’s a single expression, with no literal text or white space, and is a valid reference to a single controller method or object property. An error will prevent saving the page.
The <apex:form> Component with a Single Input Field
The only fields that the
<apex:inputField >
tag cannot display are those defined as member variables of a custom controller class written in Apex. To gather data for these variables, use the
<apex:inputCheckbox >
,
<apex:inputHidden >
,
<apex:inputSecret >
,
<apex:inputText >
, or
<apex:inputTextarea >
tags instead.
Adding and Customizing Input Field Labels
When used inside of a
<apex:pageBlockSection >
component, Visualforce input components and some output components automatically display a form label for the field. For components that map to standard or custom object fields, the displayed label is the
25
Getting a Quick Start with Visualforce Adding and Customizing Input Field Labels object field label by default. To override the default value, and for components that aren’t mapped directly to object fields, you can set the label using the label
attribute of the component. For example:
<apex:page standardController= "Contact" >
<apex:form >
<apex:pageBlock title= "Quick Edit: {!Contact.Name}" >
<apex:pageBlockSection title= "Contact Details" columns= "1" >
<apex:inputField value= "{!Contact.Phone}" />
<apex:outputField value= "{!Contact.MobilePhone}" label= "Mobile #" />
<apex:inputText value= "{!Contact.Email}" label= "{!Contact.FirstName + '’s Email'}" />
</apex:pageBlockSection >
<apex:pageBlockButtons >
</apex:pageBlock >
</apex:form >
</apex:page >
<apex:commandButton action= "{!save}" value= "Save" />
</apex:pageBlockButtons >
Note:
For this page to display contact data, the ID of a valid contact record must be specified as a query parameter in the URL for the page. For example, https://
Salesforce_instance
/apex/myPage?id=003D000000Q513R
The label
attribute may be a string, or an expression that evaluates to a string. If you set label
to an empty string, the form label for that field will be suppressed.
The label
attribute can be set on the following Visualforce components:
•
<apex:inputCheckbox >
•
<apex:inputField >
•
<apex:inputSecret >
•
<apex:inputText >
•
<apex:inputTextarea >
•
<apex:outputField >
26
Getting a Quick Start with Visualforce Setting the Tab Order for Fields in a Form
•
<apex:outputText >
•
<apex:selectCheckboxes >
•
<apex:selectList >
•
<apex:selectRadio >
Custom Labels and Error Messages
When set, the label
attribute will be used for component-level error messages, for example, when a field is required or must be unique. Custom labels won't be used in custom error messages, and the default object field label will be used instead. If you set a label attribute to an empty string, the default object field label will be used in all error messages.
Setting the Tab Order for Fields in a Form
Visualforce forms have a “natural order” for tabbing through the input fields: left-to-right, top-to-bottom. For some forms, this might not be the most efficient or accessible arrangement. You can use the tabIndex
and tabOrderHint
attributes on input and other components in your page to change the tab order to anything you’d like.
Here is a simple example that uses the tabOrderHint
attribute to control the tab order.
<apex:page standardController= "Account" >
<apex:form >
<apex:pageBlock title= "Edit Account: {!Account.Name}" >
<apex:pageBlockSection title= "Account Details" columns= "1" >
<apex:inputField value= "{!Account.Name}" tabOrderHint= "4" />
<apex:inputField value= "{!Account.Website}" tabOrderHint= "3" />
<apex:inputField value= "{!Account.Industry}" tabOrderHint= "2" />
<apex:inputField value= "{!Account.AnnualRevenue}" tabOrderHint= "1" />
</apex:pageBlockSection >
</apex:pageBlock >
</apex:form >
</apex:page >
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter in the URL for the page. For example: https://
Salesforce_instance
/apex/myPage?id=001x000xxx3Jsxb
Notice that when you display this page and press TAB, the active field changes in the reverse order than you would normally expect.
Using
tabIndex
and
tabOrderHint
The tabOrderHint
attribute is used as a hint when calculating the value to set for the tabindex
value of the rendered HTML element or elements. It’s used to indicate the relative order in which the field is selected compared to other page components. This value must be an integer between 1 and 3276, or an expression which evaluates to an integer value in the same range. The tab order begins with component 1 being the first component selected when a user presses TAB.
The tabIndex
attribute is used to directly set the tabindex
value of the rendered HTML element. It’s an absolute index setting the order in which the field is selected, compared to other page components. This value must be an integer between 0 and 32767, or
27
Getting a Quick Start with Visualforce Adding Dependent Fields to a Page an expression which evaluates to an integer value in the same range. The tab order begins with component 0 being the first component selected when a user presses TAB.
The tabOrderHint
attribute is available on only the
<apex:inputField >
component. The tabIndex
attribute can be set on the following Visualforce components.
•
<apex:commandButton >
•
<apex:commandLink >
•
<apex:inputCheckbox >
•
<apex:inputFile >
•
<apex:inputSecret >
•
<apex:inputText >
•
<apex:inputTextarea >
•
<apex:outputLabel >
•
<apex:outputLink >
•
<apex:selectCheckboxes >
•
<apex:selectList >
•
<apex:selectRadio >
When mixing
<apex:inputField >
with components that use the tabIndex
attribute to set the tab order, you can multiply the tabOrderHint
by 10 to get the approximate equivalent value of the tabIndex
for that field. Use this to manually calculate equivalent values to set the appropriate attribute on each of the components in such a way as to set the desired tab order for all elements on the page.
Adding Dependent Fields to a Page
Dependent fields provide a way to filter the field values displayed on a Visualforce page. Dependent fields consist of two parts: a controlling field that determines the filtering, and a dependent field that has its values filtered. Dependent fields can dynamically filter values in fields such as picklists, multi-select picklists, radio buttons, and checkboxes. Dependent picklists can only be displayed on Visualforce pages with Salesforce API version 19.0 or higher. For more information, see Dependent Picklists in the Salesforce online help.
For this example, we’ll be adding a dependent picklist, Subcategories, to a Visualforce page. First, create this custom picklist:
1. From the object management settings for accounts, go to the fields area, and then click New.
2. Choose Picklist, and then click Next.
3. Enter
Subcategories
for the Field Label.
4. Enter the following terms for the list of values:
•
Apple Farms
•
Cable
•
Corn Fields
•
Internet
•
Radio
•
Television
•
Winery
5. Click Next twice, then click Save.
28
Getting a Quick Start with Visualforce Adding Dependent Fields to a Page
To define the field dependencies for Subcategories:
1. From the object management settings for accounts, go to the fields area.
2. Click Field Dependencies.
3. Click New.
4. Choose Industry as a controlling field, and Subcategories as a dependent field.
5. Click Continue.
6. Each value in the controlling field (from Industry) is listed in the top row and each value in the dependent field (from Subcategory) is displayed in the column below it. Set your field dependencies to match this image:
The Field Dependency Matrix for Subcategories
You can disregard any other Industry types that aren’t shown above.
7. Click Save.
Now, create a Visualforce page called dependentPicklists
that looks like this:
<apex:page standardController= "Account" >
<apex:form >
<apex:pageBlock mode= "edit" >
<apex:pageBlockButtons >
<apex:commandButton action= "{!save}" value= "Save" />
</apex:pageBlockButtons >
<apex:pageBlockSection title= "Dependent Picklists" columns= "2" >
<apex:inputField value= "{!account.industry}" />
<apex:inputField value= "{!account.subcategories__c}" />
</apex:pageBlockSection >
</apex:pageBlock >
</apex:form >
</apex:page >
When you select Agriculture from the Industry picklist, the Subcategories picklist contains Apple Farms, Corn Fields, and Winery. If you select Communication, your Subcategories picklist contains all the Communication types defined earlier.
Dependent Picklist Considerations
Consider the following when using dependent picklists in Visualforce pages:
•
You can mix controlling and dependent fields across various field types, such as picklists, multi-picklists, radio buttons, and checkboxes.
•
There’s a limit of 10 dependent picklist pairs per page. This is totalled across all objects. Thus, you could have five dependent picklists on Account, and five on Contact, but no more. However, you can repeat the same pair of dependent picklists, such as in an iterative tag like
<apex:repeat >
, without counting more than once against your limit.
29
Getting a Quick Start with Visualforce Adding Dependent Fields to a Page
•
If the user viewing the page has read-only access to the controlling field, a dependent picklist might not behave as expected. In this case, the dependent picklist shows all possible values for the picklist, instead of being filtered on the read-only value. This is a known limitation in Visualforce.
•
Pages must include the controlling field for a dependent picklist. Failing to include the controlling field on the page causes a runtime error when the page displays.
•
Don’t mix inline edit-enabled fields with regular input fields from the same dependency group. For example, don’t mix a standard input field for a controlling field with an inline edit-enabled dependent field:
<apex:page standardController= "Account" >
<apex:form >
<!-- Don't mix a standard input field... -->
<apex:inputField value= "{!account.Controlling__c}" />
<apex:outputField value= "{!account.Dependent__c}" >
<!-- ...with an inline-edit enabled dependent field -->
<apex:inlineEditSupport event= "ondblClick" />
</apex:outputField >
</apex:form >
</apex:page >
•
If you combine inline edit-enabled dependent picklists with Ajax-style partial page refreshes, refresh all fields with dependent or controlling relationships to each other as one group. Refreshing fields individually isn’t recommended and might result in inconsistent undo/redo behavior. Here’s an example of the recommended way to partially refresh a form with inline edit-enabled dependent picklists:
<apex:form >
<!-- other form elements ... -->
<apex:outputPanel id= "locationPicker" >
<apex:outputField value= "{!Location.country}" >
<apex:inlineEditSupport event= "ondblClick" />
</apex:outputField >
<apex:outputField value= "{!Location.state}" >
<apex:inlineEditSupport event= "ondblClick" />
</apex:outputField >
<apex:outputField value= "{!Location.city}" >
<apex:inlineEditSupport event= "ondblClick" />
</apex:outputField >
</apex:outputPanel >
<!-- ... -->
<apex:commandButton value= "Refresh Picklists" reRender= "locationPicker" />
</apex:form >
All of the inline edit-enabled picklists are wrapped in the
<apex:outputPanel >
component. The
<apex:outputPanel > rerenders when the
<apex:commandButton >
action method fires.
SEE ALSO:
Salesforce Help: Find Object Management Settings
30
Getting a Quick Start with Visualforce Creating Visualforce Dashboard Components
Creating Visualforce Dashboard Components
Visualforce pages can be used as dashboard components. A dashboard shows data from source reports as visual components, which can be charts, gauges, tables, metrics, or Visualforce pages. The components provide a snapshot of key metrics and performance indicators for your organization. Each dashboard can have up to 20 components.
Visualforce pages that use the Standard Controller
can’t be used in dashboards. To be included in a dashboard, a Visualforce page must
have either no controller, use a custom controller , or reference a page bound to the
. If a Visualforce page does not meet these requirements, it does not appear as an option in the dashboard component
Visualforce Page
drop-down list.
Create a Visualforce page called
VFDashboard
. The following markup shows an example of a Visualforce page that uses a standard list controller and can be used within a dashboard. It displays a list of the cases associated with your organization:
<apex:page standardController= "Case" recordSetvar= "cases" >
<apex:pageBlock >
<apex:form id= "theForm" >
<apex:panelGrid columns= "2" >
<apex:outputLabel value= "View:" />
<apex:selectList value= "{!filterId}" size= "1" >
<apex:actionSupport event= "onchange" rerender= "list" />
<apex:selectOptions value= "{!listviewoptions}" />
</apex:selectList >
</apex:panelGrid >
<apex:pageBlockSection >
<apex:dataList var= "c" value= "{!cases}" id= "list" >
{!c.subject}
</apex:dataList >
</apex:pageBlockSection >
</apex:form >
</apex:pageBlock >
</apex:page >
To create a dashboard that uses this Visualforce page:
1. View the dashboard and click Edit.
2. Click Add Component from the top of any column.
3. Choose a Visualforce Page as the component type.
4. Optionally, enter a header to display at the top of the dashboard component.
5. Optionally, enter a footer to display at the bottom of the dashboard component.
6. From the
Visualforce Page
drop-down list, select
VFDash
.
7. Click Save.
31
Getting a Quick Start with Visualforce
Sample Visualforce Page Running in a Dashboard
Displaying Related Lists for Custom Objects
on page 130.
Displaying Related Lists for Custom Objects
Displaying custom objects and their related lists with Visualforce is very simple.
Suppose you have three custom objects: MyChildObject, MyMasterObject, and MyLookupObject. MyChildObject has a master-detail relationship with MyMasterObject (which is the master). MyLookupObject also has a Lookup relationship with MyChildObject.
If you want to create a Visualforce page that displays the related list for MyMasterObject, use the following markup:
<apex:page standardController= "MyMasterObject__c" >
<apex:relatedList list= "MyChildObjects__r" />
</apex:page >
For this page to display the related list data, the ID of a valid custom object record with a custom relationship must be specified as a query parameter in the URL for the page, for example, http://na3.salesforce.com/myCustomRelatedList?id=a00x00000003ij0
.
Although MyLookupObject uses a different type of relationship, the syntax is identical:
<apex:page standardController= "MyLookupObject__c" >
<apex:relatedList list= "MyChildObjects__r" />
</apex:page >
Enabling Inline Editing
Visualforce pages 21.0 and above support inline editing. Inline editing lets users quickly edit field values, right on a record’s detail page.
Editable cells display a pencil icon ( ) when you hover over the cell, while non-editable cells display a lock icon ( ).
The
<apex:detail >
component has an attribute that activates inline editing, while the
<apex:inlineEditSupport > component provides inline editing functionality to several container components.
To see the power of inline editing, create a page called inlineDetail
with the following code:
<apex:page standardController= "Account" >
<apex:detail subject= "{!account.Id}" relatedList= "false" />
</apex:page >
32
Getting a Quick Start with Visualforce Enabling Inline Editing
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter in the URL for the page. For example: https://
Salesforce_instance
/apex/myPage?id=001x000xxx3Jsxb
Try to double-click one of the fields, like
Account Number
. You’ll notice that nothing happens.
Now, replace the page with the following code:
<apex:page standardController= "Account" >
<apex:detail subject= "{!account.Id}" relatedList= "false" inlineEdit= "true" />
</apex:page >
Hover over any of the fields, and you’ll notice that you can now edit their contents directly. Clicking Save at the top of the section preserves all your changed information. Components that support inline editing must always be descendants of the
<apex:form > tag. However, the
<apex:detail >
component doesn’t have to be a descendant of an
<apex:form >
to support inline editing.
The
<apex:inlineEditSupport >
component must be a descendant of the following components:
•
<apex:dataList >
•
<apex:dataTable >
•
<apex:form >
•
<apex:outputField >
•
<apex:pageBlock >
•
<apex:pageBlockSection >
•
<apex:pageBlockTable >
•
<apex:repeat >
Here’s a sample that demonstrates how you can create a page using
<apex:pageBlockTable >
that makes use of inline editing:
<apex:page standardController= "Account" recordSetVar= "records" id= "thePage" >
<apex:form id= "theForm" >
<apex:pageBlock id= "thePageBlock" >
<apex:pageBlockTable value= "{!records}" var= "record" id= "thePageBlockTable" >
<apex:column >
<apex:outputField value= "{!record.Name}" id= "AccountNameDOM" />
<apex:facet name= "header" >Name </apex:facet >
</apex:column >
<apex:column >
<apex:outputField value= "{!record.Type}" id= "AccountTypeDOM" />
<apex:facet name= "header" >Type </apex:facet >
</apex:column >
<apex:column >
<apex:outputField value= "{!record.Industry}" id= "AccountIndustryDOM" />
<apex:facet name= "header" >Industry </apex:facet >
</apex:column >
<apex:inlineEditSupport event= "ondblClick" showOnEdit= "saveButton,cancelButton" hideOnEdit= "editButton" />
</apex:pageBlockTable >
<apex:pageBlockButtons >
<apex:commandButton value= "Edit" action= "{!save}" id= "editButton" />
33
Getting a Quick Start with Visualforce Enabling Inline Editing
<apex:commandButton value= "Save" action= "{!save}" id= "saveButton" />
<apex:commandButton value= "Cancel" action= "{!cancel}" id= "cancelButton"
/>
</apex:pageBlockButtons >
</apex:pageBlock >
</apex:form >
</apex:page >
The following are cases when inline editing isn’t supported.
•
Inline editing isn’t available in:
–
Accessibility mode
–
Setup pages
–
Dashboards
–
Customer Portal
–
Descriptions for HTML solutions
•
The following standard checkboxes on case and lead edit pages are not inline editable:
–
Case Assignment (
Assign using active assignment rules
)
–
Case Email Notification (
Send notification email to contact
)
–
Lead Assignment (
Assign using active assignment rule
)
•
The fields in the following standard objects are not inline editable.
–
All fields in Documents and Price Books
–
All fields in Tasks except for
Subject
and
Comment
–
All fields in Events except for
Subject
,
Description
, and
Location
–
Full name fields of Person Accounts, Contacts, and Leads. However, their component fields are, for example,
First Name and
Last Name
.
•
You can use inline editing to change the values of fields on records for which you have read-only access, either via field-level security or your organization's sharing model; however, Salesforce doesn't let you save your changes, and displays an insufficient privileges error message when you try to save the record.
•
Inline editing isn’t supported for standard rich text area (RTA) fields, such as
Idea.Body
, that are bound to
<apex:outputField >
when Visualforce pages are served from a separate domain, other than the Salesforce domain. By default, Visualforce pages are served from a separate domain unless your administrator has disabled this setting. Custom RTA fields aren’t affected by this limitation and support inline editing.
•
Inline editing is supported for dependent picklists that use
<apex:outputField >
.
•
Pages must include the controlling field for a dependent picklist. Failing to include the controlling field on the page causes a runtime error when the page displays.
•
Don’t mix inline edit-enabled fields with regular input fields from the same dependency group. For example, don’t mix a standard input field for a controlling field with an inline edit-enabled dependent field:
<apex:page standardController= "Account" >
<apex:form >
<!-- Don't mix a standard input field... -->
<apex:inputField value= "{!account.Controlling__c}" />
<apex:outputField value= "{!account.Dependent__c}" >
<!-- ...with an inline-edit enabled dependent field -->
<apex:inlineEditSupport event= "ondblClick" />
34
Getting a Quick Start with Visualforce Converting a Page to a PDF File
</apex:outputField >
</apex:form >
</apex:page >
•
If you combine inline edit-enabled dependent picklists with Ajax-style partial page refreshes, refresh all fields with dependent or controlling relationships to each other as one group. Refreshing fields individually isn’t recommended and might result in inconsistent undo/redo behavior. Here’s an example of the recommended way to partially refresh a form with inline edit-enabled dependent picklists:
<apex:form >
<!-- other form elements ... -->
<apex:outputPanel id= "locationPicker" >
<apex:outputField value= "{!Location.country}" >
<apex:inlineEditSupport event= "ondblClick" />
</apex:outputField >
<apex:outputField value= "{!Location.state}" >
<apex:inlineEditSupport event= "ondblClick" />
</apex:outputField >
<apex:outputField value= "{!Location.city}" >
<apex:inlineEditSupport event= "ondblClick" />
</apex:outputField >
</apex:outputPanel >
<!-- ... -->
<apex:commandButton value= "Refresh Picklists" reRender= "locationPicker" />
</apex:form >
All of the inline edit-enabled picklists are wrapped in the
<apex:outputPanel >
component. The
<apex:outputPanel > rerenders when the
<apex:commandButton >
action method fires.
Converting a Page to a PDF File
You can render any page as a PDF by adding the renderAs
attribute to the
<apex:page >
component, and specifying “pdf” as the rendering service. For example:
<apex:page renderAs= "pdf" >
Visualforce pages rendered as PDFs will either display in the browser or download as a PDF file, depending on your browser settings.
In the previous tutorial, you used a Visualforce page to change the name of a company. Suppose you wanted to generate an announcement of the new name as a PDF. The following example produces such a page, along with the current date and time.
<apex:page standardController= "Account" renderAs= "pdf" applyBodyTag= "false" >
<head >
<style > body { font-family: 'Arial Unicode MS' ; }
.companyName { font: bold 30px; color: red; }
</style >
</head >
<body >
<center >
<h1 >New Account Name!
</h1 >
<apex:panelGrid columns= "1" width= "100%" >
35
Getting a Quick Start with Visualforce Converting a Page to a PDF File
<apex:outputText value= "{!account.Name}" styleClass= "companyName" />
<apex:outputText value= "{!NOW()}" > </apex:outputText >
</apex:panelGrid >
</center >
</body >
</apex:page >
Things to note about the page:
•
<style >
is CSS markup, not Visualforce markup. It defines the font family used for the entire page, as well as a particular style for the company name.
•
Some of the output text is contained in an
<apex:panelGrid >
component. A panel grid renders as an HTML table. Each component found in the body of the
<apex:panelGrid >
component is placed into a corresponding cell in the first row until the number of columns is reached. As there is only a single cell, each output text is displayed in a separate row.
A Visualforce Page Rendered as PDF
Always verify the format of your rendered page before deploying it.
SEE ALSO:
Render a Visualforce Page as a PDF File
Visualforce PDF Rendering Considerations and Limitations
36
Getting a Quick Start with Visualforce Building a Table of Data in a Page
Building a Table of Data in a Page
Some Visualforce components, such as
<apex:pageBlockTable >
or
<apex:dataTable >
, allow you to display information from multiple records at a time by iterating over a collection of records. To illustrate this concept, the following page uses the
<apex:pageBlockTable >
component to list the contacts associated with an account that is currently in context:
<apex:page standardController= "Account" >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
You are viewing the {!account.name} account.
</apex:pageBlock >
<apex:pageBlock title= "Contacts" >
<apex:pageBlockTable value= "{!account.Contacts}" var= "contact" >
<apex:column value= "{!contact.Name}" />
<apex:column value= "{!contact.MailingCity}" />
<apex:column value= "{!contact.Phone}" />
</apex:pageBlockTable >
</apex:pageBlock >
</apex:page >
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter in the URL for the page. For example: https://
Salesforce_instance
/apex/myPage?id=001x000xxx3Jsxb
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.
37
Getting a Quick Start with Visualforce Editing a Table of Data in a Page
•
var
specifies the name of the iteration variable. This variable is used within the body of the
<apex:pageBlockTable >
tag to access the fields on each contact. In this example, value= "{!contact.Name}"
is used on the
<apex:column >
tag to display the name of the contact.
The
<apex:pageBlockTable >
component takes one or more child
<apex:column >
components. The number of rows in the table is controlled by the number of records returned with the value
attribute.
Note: The
<apex:pageBlockTable >
component automatically takes on the styling of a standard Salesforce list. To display a list with your own styling, use
<apex:dataTable >
instead.
Editing a Table of Data in a Page
In the last tutorial, you built a table of data. Using
<apex:inputField >
in the data table columns, you can create a table with editable fields. Using
<apex:commandButton >
you can save the data you change. Any message (such as
Saving
) is automatically displayed with the
<apex:pageMessages >
tag.
The following page creates a page that enables you to edit a series of Industry types at the same time:
<apex:page standardController= "Account" recordSetVar= "accounts" tabstyle= "account" sidebar= "false" >
<apex:form >
<apex:pageBlock >
<apex:pageMessages />
<apex:pageBlockButtons >
<apex:commandButton value= "Save" action= "{!save}" />
</apex:pageBlockButtons >
<apex:pageBlockTable value= "{!accounts}" var= "a" >
<apex:column value= "{!a.name}" />
<apex:column headerValue= "Industry" >
<apex:inputField value= "{!a.Industry}" />
</apex:column >
</apex:pageBlockTable >
</apex:pageBlock >
</apex:form >
</apex:page >
Note: If you have an ID attribute in the URL, this page does not display correctly. For example, https://c.na1.visual.soma.force.com/apex/HelloWorld?id=001D000000IR35T
produces an error.
You need to remove the ID from the URL.
Notice the following about the page markup:
•
This page takes advantage of
to generate the data for the table. Use the recordSetVar
attribute to specify the name of the set of data you want to use. Then, in the
<apex:pageBlockTable >
value, use the name of that set to populate the table with data.
•
The
<apex:inputField >
tag automatically generates the correct display for the field. In this case, as a drop-down list.
•
The page must be enclosed in an
<apex:form >
tag in order to use the
<apex:commandButton >
tag. A form specifies a portion of a Visualforce page that users can interact with.
38
Getting a Quick Start with Visualforce
Example of Editing a Table of Data
Using Query String Parameters in a Page
Using Query String Parameters in a Page
As shown in earlier examples, the default page context—that is, the record that provides the source of data displayed on the page—is controlled by a query string parameter named id
in the page URL. You can also get and set query string parameters in the Visualforce markup. The following topics provide examples:
•
Getting Query String Parameters
•
Setting Query String Parameters in Links
•
Getting and Setting Query String Parameters on a Single Page
Getting Query String Parameters
You can reference query string parameters in Visualforce markup by using the
$CurrentPage
global variable. Using
$CurrentPage
, you can access the query string parameters for the page by specifying the parameters
attribute, after which you can access each individual parameter:
$CurrentPage.parameters.
parameter_name
For example, suppose you want to add detail information about a specific contact to an Account page. The account record ID is specified by the default id
query string parameter, and the contact record ID is specified by the query string parameter named cid
:
<apex:page standardController= "Account" >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
You are displaying values from the {!account.name} account and a separate contact that is specified by a query string parameter.
</apex:pageBlock >
<apex:pageBlock title= "Contacts" >
<apex:dataTable value= "{!account.Contacts}" var= "contact" cellPadding= "4" border= "1" >
<apex:column >
<apex:facet name= "header" >Name </apex:facet >
{!contact.Name}
</apex:column >
<apex:column >
<apex:facet name= "header" >Phone </apex:facet >
{!contact.Phone}
</apex:column >
</apex:dataTable >
39
Getting a Quick Start with Visualforce Getting Query String Parameters
</apex:pageBlock >
<apex:detail subject= "{!$CurrentPage.parameters.cid}" relatedList= "false" title= "false" />
</apex:page >
For this example to render properly, you must associate the Visualforce page with valid account and contact IDs in the URL. For example, if
001D000000IRt53
is the account ID and
003D000000Q0bIE
is the contact ID, the resulting URL should be: https://
Salesforce_instance
/apex/MyFirstPage?id=001D000000IRt53&cid=003D000000Q0bIE
Displaying Field Values with Visualforce
on page 18 has more information about retrieving the ID of a record.
Note: If you use the id
parameter in a URL, it must refer to the same entity referred to in the standard controller.
Using Query String Parameters in a Page
40
Getting a Quick Start with Visualforce Setting Query String Parameters in Links
Setting Query String Parameters in Links
You can set query string parameters in links to pages by constructing the link URL manually, or by using
<apex:param >
tags within the
<apex:outputLink >
tag. For example, both of the following examples create identical links to an external page:
<apex:outputLink value= "http://google.com/search?q={!account.name}" >
Search Google
</apex:outputLink >
<apex:outputLink value= "http://google.com/search" >
Search Google
<apex:param name= "q" value= "{!account.name}" />
</apex:outputLink >
The latter method, which uses
<apex:param >
tags instead of manually creating the URL, is preferable for stylistic reasons.
Note:
In addition to
<apex:outputLink >
, use
<apex:param >
to set request parameters for
<apex:commandLink >
, and
<apex:actionFunction >
.
Getting and Setting Query String Parameters on a Single Page
Having seen examples of both getting and setting query string parameters, this example shows how the two actions can be combined on a single page to produce a more interesting result. Based on the example from Getting Query String Parameters, the following page makes the name of each contact in the list a hyperlink that controls the context of the detail component below it.
This is possible by:
•
Wrapping the data table in an
<apex:form >
tag
•
Turning each contact name into an
<apex:commandLink >
that sets the cid
parameter appropriately with an
<apex:param >
tag
When used with a standard controller, command links always entirely refresh the current page with the new information added to the page—in this case, an updated cid
that updates the contact detail component.
<apex:page standardController= "Account" >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
You are displaying contacts from the {!account.name} account.
Click a contact 's name to view his or her details.
</apex:pageBlock >
<apex:pageBlock title= "Contacts" >
<apex:form >
<apex:dataTable value= "{!account.Contacts}" var= "contact" cellPadding= "4" border= "1" >
<apex:column >
<apex:facet name= "header" >Name </apex:facet >
<apex:commandLink >
{!contact.Name}
<apex:param name= "cid" value= "{!contact.id}" />
</apex:commandLink >
</apex:column >
<apex:column >
<apex:facet name= "header" >Phone </apex:facet >
{!contact.Phone}
</apex:column >
</apex:dataTable >
41
Getting a Quick Start with Visualforce Using Ajax in a Page
</apex:form >
</apex:pageBlock >
<apex:detail subject= "{!$CurrentPage.parameters.cid}" relatedList= "false" title= "false" />
</apex:page >
After saving this markup, refresh your browser with the id
query string parameter but without the cid
parameter in the URL For example, https://
Salesforce_instance
/apex/MyFirstPage?id=001D000000IRt53
Initially the contact detail page is not rendered, but when you click a contact name the page renders the appropriate detail view.
Note: If you use the id
parameter in a URL, it must refer to the same entity referred to in the standard controller.
SEE ALSO:
Using Ajax in a Page
Some Visualforce components are Ajax aware and allow you to add Ajax behaviors to a page without having to write any JavaScript.
The following topics provide examples:
•
Implementing Partial Page Updates with Command Links and Buttons
•
Providing Status for Asynchronous Operations
•
Applying Ajax Behavior to Events on Any Component
Implementing Partial Page Updates with Command Links and Buttons
One of the most widely used Ajax behaviors is a partial page update, in which only a specific portion of a page is updated following some user action, rather than a reload of the entire page.
The simplest way to implement a partial page update is to use the reRender
attribute on an
<apex:commandLink >
or
<apex:commandButton >
tag to identify a component that should be refreshed. When a user clicks the button or link, only the identified component and all of its child components are refreshed.
For example, consider the contact list example shown in
Getting and Setting Query String Parameters on a Single Page
on page 41. In that example, when a user clicks the name of a contact in the list to view the details for that contact, the entire page is refreshed as a result of this action. With just two modifications to that markup, we can change the behavior of the page so that only the area below the list refreshes:
1. First, create or identify the portion of the page that should be rerendered. To do this, wrap the
<apex:detail >
tag in an
<apex:outputPanel >
tag, and give the output panel an id
parameter. The value of id
is the name that we can use elsewhere in the page to refer to this area. It must be unique in the page.
2. Next, indicate the point of invocation (the command link) that we want to use to perform a partial page update of the area that we just defined. To do this, add a reRender
attribute to the
<apex:commandLink >
tag, and give it the same value that was assigned to the output panel's id
.
The final markup looks like this:
<apex:page standardController= "Account" >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
You are displaying contacts from the {!account.name} account.
42
Getting a Quick Start with Visualforce Providing Status for Asynchronous Operations
Click a contact 's name to view his or her details.
</apex:pageBlock >
<apex:pageBlock title= "Contacts" >
<apex:form >
<apex:dataTable value= "{!account.Contacts}" var= "contact" cellPadding= "4" border= "1" >
<apex:column >
<apex:commandLink rerender= "detail" >
{!contact.Name}
<apex:param name= "cid" value= "{!contact.id}" />
</apex:commandLink >
</apex:column >
</apex:dataTable >
</apex:form >
</apex:pageBlock >
<apex:outputPanel id= "detail" >
<apex:detail subject= "{!$CurrentPage.parameters.cid}" relatedList= "false" title= "false" />
</apex:outputPanel >
</apex:page >
After saving the page, click any contact and notice how the detail component displays without a complete page refresh.
Note: You cannot use the reRender
attribute to update content in a table.
Providing Status for Asynchronous Operations
Ajax behaviors, such as partial page updates, are asynchronous events that occur in the background while a page user continues to work. For good usability, designers often add a status element to alert the user of any background activity currently in progress.
Visualforce supports status updates with the
<apex:actionStatus >
tag. This tag allows you to display text at the beginning or end of a background event with the startText
or stopText
attributes, or, for more advanced developers, allows you to display an image or other component.
For this example, we'll add status text to the contact list page that we have been developing. After a user clicks the name of a contact, the detail area displays the text, “Requesting...” while the detail area is rendered.
To implement the message, wrap
<apex:actionStatus >
around the
<apex:detail >
component, since that is the component being updated asynchronously. In between the two tags, add an
<apex:facet >
tag named “stop”.
A facet consists of content in an area of a Visualforce component that provides contextual information about the data that is presented in the component. For example,
<apex:dataTable >
supports facets for the header, footer, and caption of a table, while
<apex:column >
only supports facets for the header and footer of the column. The
<apex:facet >
component allows you to override the default facet on a Visualforce component with your own content. Facets only allow a single child within the start and close tags.
Note:
Not all components support facets. Those that do are listed in the
.
In the following example,
<apex:actionStatus >
supports a facet named “stop” that contains the component that should be displayed as soon as the action completes—in this case, the detail area:
<apex:page standardController= "Account" >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
You are displaying contacts from the {!account.name} account.
Click a contact 's name to view his or her details.
43
Getting a Quick Start with Visualforce Applying Ajax Behavior to Events on Any Component
</apex:pageBlock >
<apex:pageBlock title= "Contacts" >
<apex:form >
<apex:dataTable value= "{!account.Contacts}" var= "contact" cellPadding= "4"
<apex:column > border= "1" >
<apex:commandLink rerender= "detail" >
{!contact.Name}
<apex:param name= "cid" value= "{!contact.id}" />
</apex:commandLink >
</apex:column >
</apex:dataTable >
</apex:form >
</apex:pageBlock >
<apex:outputPanel id= "detail" >
<apex:actionStatus startText= "Requesting..." >
<apex:facet name= "stop" >
<apex:detail subject= "{!$CurrentPage.parameters.cid}" relatedList= "false" title= "false" />
</apex:facet >
</apex:actionStatus >
</apex:outputPanel >
</apex:page >
Remember when you visit this page, to include an ID as part of the URL. For example, https://
Salesforce_instance
/apex/ajaxAsyncStatus?id=001x000xxx3Jsxb
Applying Ajax Behavior to Events on Any Component
Using command links and buttons to implement a partial page update is relatively simple, but suppose you want to have the same page update occur just by hovering the mouse over a contact's name?
To do this with the contact list example, remove the
<apex:commandLink >
tag from the data table and wrap the contact name in an
<apex:outputPanel >
tag instead. Within this output panel, add an
<apex:actionSupport >
element as a sibling of the contact's name:
•
The
<apex:outputPanel >
tag defines the area over in which we want the specialized behavior.
•
The
<apex:actionSupport >
tag defines the partial page update behavior that was implemented previously by the command link.
–
The event
attribute specifies the DOM event that should trigger the update. Whereas
<apex:commandLink >
only executes during the “onclick” event,
<apex:actionSupport >
can execute on any valid event such as “onclick”, “ondblclick”, or, for this example, “onmouseover”.
–
The reRender
attribute specifies which part of the page should refresh.
–
The
<apex:param >
tag sets the value of the cid
query string parameter when the specified event occurs.
The resulting markup looks like this:
<apex:page standardController= "Account" >
<apex:pageBlock title= "Hello {!$User.FirstName}!" >
You are displaying contacts from the {!account.name} account.
Mouse over a contact 's name to view his or her details.
</apex:pageBlock >
44
Getting a Quick Start with Visualforce Applying Ajax Behavior to Events on Any Component
<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
45
Descarcă
Publicitate