41,99 €
Discover over 70 real-world examples to overcome the most complex concepts you will face developing with Visualforce
This book will be beneficial to developers who are already well-versed with the basics of Visualforce. An awareness of the standard component library and the purpose of controllers is expected.
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 that is used to write the Visualforce pages and a set of controllers that are used to write business logic to the Visualforce pages.
Visualforce Development Cookbook provides solutions to a variety of challenges faced by Salesforce developers and demonstrates how easy it is to build rich, interactive pages using Visualforce. Whether you are looking to make a minor addition to the standard page functionality or override it completely, this book will provide you with the help you require throughout.
You will start by learning about the simple utilities and will build up to more advanced techniques for data visualization and to reuse functionality. You will learn how to perform various tasks such as creating multiple records from a single page, visualizing data as charts, using JavaScript to enhance client-side functionality, building a public website, and making data available to a mobile device.
With an interesting chapter on tackling common issues faced while developing Visualforce pages, the book provides lots of practical examples to enhance and extend your Salesforce user interface.
Following a cookbook structure, the book provides recipes on some essential technical scenarios and a few that focus on real-world development problems. This book is packed with illustrations and contains lots of code samples to improve your understanding.
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 345
Veröffentlichungsjahr: 2016
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First edition: September 2013
Second edition: August 2016
Production reference: 1260816
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham B3 2PB, UK.
ISBN 978-1-78646-808-6
www.packtpub.com
Author
Keir Bowden
Copy Editor
Safis Editing
Reviewer
Rahul Sharma
Project Coordinator
Suzanne Coutinho
Commissioning Editor
Aaron Lazar
Proofreader
Safis Editing
Acquisition Editor
Chaitanya Nair
Indexer
Tejal Daruwale Soni
Content Development Editor
Nikhil Borkar
Production Coordinator
Aparna Bhagat
Technical Editor
Hussain Kanchwala
Cover Work
Aparna Bhagat
Keir Bowden is a 30-year veteran of the IT industry from the United Kingdom. After spending the early part of his career in the defence industry, he moved into investment banking systems, implementing systems for Banque Nationale de Paris, CitiGroup, and Deutsche Bank. In the late 1990s, Keir moved into Internet technologies, leading to a development of the order management and payment handling systems of one of the first European Internet shopping sites.
Keir started working with Force.com in late 2008 and has been recognized multiple times by Salesforce as an MVP for his contribution and leadership in the community. In 2012, he became the first certified technical architect outside of Salesforce in EMEA, and he has served as a judge on several EMEA Technical Architect Certification Review Boards. Keir is also a prominent blogger on Apex, Visualforce and Lightning Components solutions; and a regular speaker at events such as Dreamforce, Cloud World Forum, and Salesforce World Tour.
Keir is a chief technical officer of BrightGena—a Salesforce.com Platinum Cloud Alliance Partner in the United Kingdom, where he is responsible for the present and future technical strategies.
Keir acted as a technical reviewer for the CRM Admin Cookbook before accepting the challenge of authoring this book, which also happens to be his first.
I would like to thank my partner, Marie, for putting up with me spending even more time than usual on my laptop, something that neither of us had previously thought possible. I’d also like to thank my reviewers, whose tireless efforts and attention to detail ensure that the recipes are correct and perform as expected.
Rahul Sharma has been working on the Force.com platform since 2010 and is a certified advanced developer and administrator. Currently, he is working with Cognizant and has worked on most of the areas in Salesforce. He is an active contributor to the Salesforce developer community (he holds the Pro position) and Stack Exchange. He holds a bachelors degree in electronics engineering based out of Mumbai, India. His areas of interest are UI and mobile development, along with Salesforce. He can be reached at about.me/rahuls91221.
He was a technical reviewer for the following books:
I would like to thank my family & friends for support , and Packt Publishing for giving me another opportunity to review an excellent book by our Salesforce MVP Keir Bowden.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Get notified! Find out when new books are published by following @PacktEnterprise on Twitter or the Packt Enterprise Facebook page.
The Visualforce framework allows developers to build highly customized, personalized, and branded user interfaces for their Salesforce, Force.com, and Salesforce1 applications. Hosted natively on the Salesforce platform, Visualforce gives developers complete control over all areas of the user interface, allowing them to satisfy complex business requirements and support multiple devices.
Visualforce pages use a mixture of HTML and Visualforce components, which are processed server-side and delivered to the browser as HTML. This allows the use of standard web technologies, such as CSS and JavaScript, to provide an enriched and dynamic user experience.
The Visualforce Development Cookbook provides solutions for a variety of challenges faced by the Salesforce developers and demonstrates how easy it is to build rich interactive pages for both desktop and mobile devices using Visualforce. Each recipe contains clear, step-by-step instructions along with detailed explanations of the key areas of Visualforce, Apex or JavaScript code, that deliver the solution.
Whether you are looking to make a minor addition to the standard page functionality or override it completely, this book will provide you with practical examples that can be readily adapted to a number of scenarios.
Chapter 1 , General Utilities, covers enhancing or replacing standard functionality with Visualforce, systemizing business processes, guiding users through the creation and ongoing management of data, and writing effective tests.
Chapter 2, Custom Components, demonstrates how to create custom Visualforce components to encapsulate functionality for reuse across multiple pages and techniques to allow communication between component and page controllers.
Chapter 3, Capturing Data Using Forms, describes how to capture data entered in a Visualforce page and send this to the server for processing.
Chapter 4, Managing Records, offers techniques to streamline and enhance the management of Salesforce data using Visualforce pages, using styling to indicate required fields and changing pages in response to user actions.
Chapter 5, Managing Multiple Records, covers recipes to manage multiple records in a single page, ranging from editing parent and child records to managing a deep and wide hierarchy.
Chapter 6, Visualforce Charts, presents a series of recipes to create charts of increasing complexity, embed a chart into a standard Salesforce page, and add multiple charts to a single page in a similar style to a Salesforce dashboard.
Chapter 7, Enhancing the Client with JavaScript, shows how to use JavaScript to provide a variety of client-side enhancements, including confirmation of user actions, instant feedback on user inputs, and speeding up pages that access server-side data via remote methods.
Chapter 8, Force.com Sites, provides step-by-step instructions to configure a publicly accessible website styled with the Lightning Design System, allowing visitors to access the Salesforce records and extract boilerplate content to reusable templates.
Chapter 9, Visualforce in Salesforce1, demonstrates how Visualforce can be used to enhance the user experience on the Salesforce1 mobile device, including capturing the user’s location and attaching images when creating records.
Chapter 10, Troubleshooting, covers some common error scenarios and how to avoid them, along with tips to improve performance by reducing the size of the Visualforce viewstate and page load time in general.
In order to build the recipes from this book, you will need an Enterprise, Unlimited or Developer (recommended) Edition of Salesforce, and System Administrator access. You will also need a supported browser, such as the latest version of Google Chrome, Mozilla Firefox, Apple Safari 8+, Internet Explorer 9+, or Microsoft Edge. Use the Setup menu to cut and paste the code samples rather than the developer console, as it may report visibility errors when the organization has a custom namespace.
This book is intended for intermediate Visualforce developers who are familiar with the basics of Visualforce and Apex development on the Salesforce platform. An understanding of the basics of HTML, CSS and JavaScript is also useful for some more advanced recipes.
In this book, you will find several headings that appear frequently (Getting ready, How to do it, How it works, There's more, and See also).
To give clear instructions on how to complete a recipe, we use these sections as follows:
This section tells you what to expect in the recipe, and describes how to set up any software or any preliminary settings required for the recipe.
This section contains the steps required to follow the recipe.
This section usually consists of a detailed explanation of what happened in the previous section.
This section consists of additional information about the recipe in order to make the reader more knowledgeable about the recipe.
This section provides helpful links to other useful information for the recipe.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Once the payment reaches the state Complete the action poller will be disabled."
A block of code is set as follows:
<apex:column style="color: {!IF(AND(NOT(ISNULL(campaign.ActualCost)), campaign.ActualCost<=campaign.BudgetedCost), "lawngreen", "red")}" value="{!campaign.ActualCost}"/>New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "Click on the New button."
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Visualforce-Development-Cookbook-2e. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/VisualforceDevelopmentCookbook_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
In this chapter, we will cover the following recipes:
This chapter provides solutions for a variety of situations that Visualforce developers are likely to encounter on a regular basis. Enhancing or replacing standard functionality with Visualforce enriches the user experience, improving user productivity and adoption. Visualforce also allows business processes to be highly systematized, guiding users through the creation and the ongoing management of data. Writing effective tests for Visualforce controllers is a key skill that allows developers to deploy Visualforce pages to production, and be confident that they will work as intended.
Two common complaints from users are that the information they are interested in requires a number of clicks to access, or that there is too much information on a single page, resulting in a cluttered layout that requires significant scrolling. This is an area where a Visualforce override can make a significant difference by traversing relationships to display information from a number of records on a single page.
Salesforce allows the standard pages associated with sObject record actions, such as view and edit, to be overridden with Visualforce pages. This is typically used to display the record in a branded or customized format; for example, to display details and related lists in separate tabs.
In this recipe, we will override the standard page associated with viewing an account record with a Visualforce page that not only provides a tabbed user interface but also lifts up additional activity information from the related contact list and line item information from the related opportunity lists. Furthermore, the related opportunities displayed will be limited to those that are open.
Only Visualforce pages that use the standard controller for the sObject can override standard pages.
This recipe makes use of a standard controller, so we only need to create the Visualforce page.
As the record view override applies to all users, ensure that all profiles are given access to the Visualforce page. Any user with a profile that does not have access will receive an Insufficient Privileges error when attempting to view an account record.
When a user clicks on an account record link anywhere in Salesforce, the tabbed page with details from related records is displayed, as shown in the following screenshot:
The key areas of the code are the tabs for the related records. The Open Opportunities tab iterates the opportunities related list, and generates an <apex:pageblock /> for each opportunity that is currently open by encapsulating this inside a conditionally rendered <apex:outputPanel />:
<apex:repeat value="{!Account.Opportunities}" var="opp"> <apex:outputPanel rendered="{!NOT(opp.IsClosed)}"> <apex:pageBlock >Then, the standard <apex:relatedList /> component is used to generate the opportunity product list by specifying the current value of the opportunity iterator as the subject of the component:
<apex:relatedList subject="{!opp}" list="OpportunityLineItems" />A useful technique when creating a custom user interface with Visualforce is to conditionally style important pieces of information to draw the user's attention to them as soon as a page is rendered.
Most Visualforce developers are familiar with using merge fields to provide sObject field values to output tags, or to decide if a section of a page should be rendered. In the tag shown next, the merge field, {!account.Name}, will be replaced with the contents of the Name field from the account sObject:
<apex:outputField value="{!account.Name}"/>The merge fields can also contain formula operators and be used to dynamically style data when it is displayed.
In this recipe, we will display a table of campaign records and style the campaign cost in green if it was within-budget, or red if it was over-budget.
Opening the following URL in your browser displays the ConditionalColour page: https://<instance>/apex/ConditionalColour. Here, <instance> is the Salesforce instance specific to your organization, for example, na6.salesforce.com.
A list of campaigns is displayed, with the campaign cost rendered in red or green depending on whether it came in on- or over-budget:
The page makes use of a standard list controller by defining the recordSetVar attribute on the <apex:page /> standard component:
<apex:page StandardController="Campaign" recordSetVar="Campaigns">Standard list controllers allow a Visualforce page to manage a collection of records without the need for Apex code. The collection of records, by default, is from the last list view accessed by the user. Specifying the filterId property in the page allows the records from a particular list view to be used.
For more information on standard list controllers, see: https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_sosc_about.htm.
Conditional styling is applied to the Actual Cost column by comparing the actual cost with the budgeted cost.
<apex:column style="color: {!IF(AND(NOT(ISNULL(campaign.ActualCost)), campaign.ActualCost<=campaign.BudgetedCost), "lawngreen", "red")}" value="{!campaign.ActualCost}"/>The standard Visualforce <apex:actionPoller/> component sends AJAX requests to the server based on the specified time interval. An example use case is a countdown timer that sends the user to another page when the timer expires. But what if the action poller should stop when a condition in the controller becomes true, for example, when a batch apex job completes or an update is received from a third-party system?
In this recipe, we will simulate the progression of a payment through a number of states. An action poller will be used to retrieve the latest state from the server and display it to the user. Once the payment reaches the state Complete, the action poller will be disabled.
This recipe makes use of a custom controller, so this will need to be created before the Visualforce page.
Note that there is nowhere to specify a name for the class when creating it through the setup pages; the class name is derived from the Apex code.
Opening the following URL in your browser displays the ActionPoller page: https://<instance>/apex/ActionPoller.
Here, <instance> is the Salesforce instance specific to your organization, for example, na6.salesforce.com.
The page polls the server for the current state, displaying the message Polling ... when the action poller executes, as shown in the following screenshot:
Once the current state reaches Complete, the action poller terminates.
The key to this recipe is the enabled attribute on the actionPoller component:
<apex:actionPoller action="{!movePayment}" rerender="payment" interval="5" status="status" enabled="{!paymentState!='Complete'}"/>This merge field references the paymentState property from the custom controller, which is evaluated each time the action poller executes until it becomes false. At that point, the action poller is permanently disabled.
The Polling ... message is generated by the actionStatus component associated with the action poller. This component has a startText attribute but not a stopText attribute, which means that the text will only be displayed while the AJAX request is in progress:
<apex:actionStatus startText="Polling ..." id="status"/>Visualforce is commonly used to produce custom pages that override or supplement standard platform functionality. Visualforce pages can also be incorporated into any HTML markup through the use of an iframe.
An iframe, or inline frame, nests an HTML document inside another HTML document. For more information, visit http://reference.sitepoint.com/html/iframe.
In this recipe, we will add a Visualforce page to a Salesforce sidebar component. This page will display the number of currently open cases in the organization, and will be styled and sized to fit seamlessly into the sidebar.
This recipe makes use of a custom controller, so this will need to be created before the Visualforce page.
Ensure that all profiles whose sidebar will display the Visualforce page are given access. Any user with a profile that does not have access will see an Insufficient Privileges error in their sidebar.
To stop this information screen appearing each time you create a home page component, select the Don't show this page again box before clicking on the Next button.
This will add the component to the sidebar of the home page only. To add it to the sidebar of all pages, a change must be made to the user interface settings.
The component appears in the sidebar on all pages, showing the number of cases open for each non-closed status, as shown in the following screenshot:
The case counts displayed in the sidebar will be retrieved when the page is displayed, but will remain static from that point. An action poller can be used to automatically refresh the counts at regular intervals. However, this will introduce a security risk, as each time the poller retrieves the updated information it will refresh the user's session. This means that, if a user leaves their workstation unattended, the Salesforce session will never expire. If this mechanism is used, it is important to remind users of the importance of locking their workstation should they leave it unattended.
When developers move to Apex/Visualforce from traditional programming languages, such as Java or C#, a concept many struggle with is how to pass parameters from a Visualforce page to a controller action method.
Passing parameters to an action method is key when a Visualforce page allows a user to manage a list of records and carry out actions on specific records. Without this, the action method cannot determine which record to apply the action to.
In this recipe, we will output a list of opportunities and for each open opportunity, provide a button to update the opportunity status to Closed Won. This button will invoke an action method to remove the list element and will also send a parameter to the controller to identify which opportunity to update.
This recipe makes use of a custom controller, so this will need to be created before the Visualforce page.
Opening the following URL in your browser shows the list of currently open opportunities: https://<instance>/apex/ActionParameter.
Here, <instance> is the Salesforce instance specific to your organization, for example, na6.salesforce.com.
Clicking on the Win button for the Grand Hotels Kitchen Generator opportunity updates the status to Closed Won and redraws the list of opportunities:
The page markup to send the parameter to the controller is as follows:
<apex:commandButton value="Win" action="{!winOpp}" status="status" rerender="opps_pb" rendered="{!opp.StageName!='Closed Won'}"> <apex:param name="oppIdToWin" value="{!opp.Id}" assignTo="{!oppIdToWin}" /> </apex:commandButton>The <apex:param /> component defines the value of the parameter, in this case the ID of the opportunity, and the controller property that the parameter will be assigned to - oppIdToWin.
Note that there is a rerender attribute on the command button. If this attribute is omitted, making the button a simple postback request, the parameter will not be passed to the controller. This is a known issue with Visualforce, as documented in the following knowledge article: http://blog.jeffdouglas.com/21/3/4/passing-parameters-with-a-commandbutton/.
The property is declared in the controller in the normal way:
public Id oppIdToWin {get; set;}Finally, the action method is invoked when the button is pressed:
