December 7, 2016 | Author: karunkasi | Category: N/A
HAND BOOK WHICH IS USE FUL TO LEARN SALES FORCE...
Community Praise for the Salesforce Handbook “The developer.force.com community is the best resource for anyone wishing to learn more about the Force.com platform. Jeff Douglas and Wes Nolte, are two of the communities most active and respected members. The Salesforce Handbook is as close as you can get to bottling the combined experience of Jeff and Wes into a book designed to get new developers building apps in no time. They just made my job so much easier!” Quinton Wall Developer Evangelist, salesforce.com “This book is great! I've been a Salesforce Admin for over 4 years and I thought I knew a lot. But I started to expand my knowledge the minute I began reading this book. It's well written and really is the perfect fit between the Dummies series and Visualforce guides. In my opinion it's a must have for any admin!” Mike Gerholdt Popular Salesforce.com blogger /Certified Advanced Administrator “This is a pragmatic and clear guide to using Force.com and building applications in the cloud. Jeff and Wes spend their days building awesome applications on the platform, and this experience and skill is very apparent throughout the book. A must read!” Jon Mountjoy Community Manager & Editor-In-Chief, salesforce.com “The Handbook provides a broad, high-level view of the Force.com platform with all of the information you need to get started. It's a definite asset to any new administrator or developer.” Ron Hess Developer Evangelist, salesforce.com “Online searches for Salesforce related topics will inevitably lead you to Wes or Jeff's blog. To have their knowledge captured in a single, thorough reference is simply awesome.” Mike Leach Business Applications Development, Facebook “The Salesforce Handbook is an essential reference tool for any Force.com developer, whether you're a seasoned pro or a beginner. Jeff and Wes describe routines and strategies most needed in Enterprise Force.com development.” Kyle Roche President & CEO, Isidorey Cloud Solutions “The Salesforce Handbook is priceless. For new and experienced force.com developers alike, this book is a 'must have'.” Scott Hemmeter Owner, Arrowpointe Corp.
“Indispensable resource that skillfully explains the advantages of cloud computing, provides best practice for coding in the cloud, not to mention provides many great tips and recipes that will keep even seasoned Force.com developers continually coming back for more. A book you can't afford not to have!” Joel Dietz CEO, Titania, Inc. “The handbook is an excellent resource for the administrator seeking to improve skills and for the beginning developer, whether a trained programmer or an administrator. The handbook provides a bridge from administration to development for Salesforce CRM power users, and introduces the platform to novices. It should be a part of any discussion on Force.com 101.” David Schach President, X-Squared On Demand “An essential guide to Salesforce.com; from honing the skills you already have to stretching you to try things with Salesforce you thought ‘only developers’ could do. Jeff and Wes provide information and instruction that's not only easy to grasp but the kind of things that will make you a Salesforce.com hero in your organization. It's the ‘I've got Salesforce, so now what’ guide to applying the power of the cloud to real business situations and making the most of your Salesforce investment.” Jeff Grosse Founder, crmfyi.com & The Salesforce Channel
ii
Salesforce Handbook
Salesforce Handbook A newcomer’s guide to building applications on salesforce.com and the Force.com platform
Jeff Douglas & Wes Nolte
Salesforce Handbook Copyright © 2010 by Jeff Douglas and Wes Nolte All rights reserved. No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher. ISBN 978-1-4461-0853-6 Printed and bound in the United States of America Trademarked names may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, we use the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark. The information in this book is distributed on an “as is” basis, without warranty. Although every precaution has been taken in the preparation of this work, neither of the authors shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in this work. Please visit http://salesforcehandbook.wordpress.com for more information or to interact with Jeff and Wes.
For Cathy, the one person that I simply can’t live without. I love you. —JD For Mum, Dad and Woni - who will have neither interest nor understanding of the contents of this book, but who I know will read it anyway. —WN
Contents Contents.............................................................................................................................ix Foreword............................................................................................................................. 1 About the Authors .............................................................................................................. 5 Acknowledgements ............................................................................................................ 7 Introduction........................................................................................................................ 9 Target Audience ............................................................................................................. 9 Salesforce.com is the Final Word ................................................................................. 10 Next Steps..................................................................................................................... 10 Conventions Used in this Book .................................................................................... 10 Terminology Conventions............................................................................................................ 10 Typographic Conventions ............................................................................................................ 10 Iconic Conventions ....................................................................................................................... 11 Introduction to Salesforce.com ........................................................................................ 13 Salesforce.com Overview .............................................................................................. 13 Salesforce.com IS Cloud Computing ........................................................................... 13 Save Money and Time................................................................................................................... 15 Innovate Quicker ........................................................................................................................... 16 What is Salesforce.com? ............................................................................................... 16 Sales Cloud ..................................................................................................................................... 17 Service Cloud.................................................................................................................................. 19 Collaboration Cloud ...................................................................................................................... 20 Force.com Custom Cloud ............................................................................................................ 20 Custom Application Development ............................................................................................. 22 VMforce .......................................................................................................................................... 23 Security ......................................................................................................................... 23 User Security and Authentication................................................................................................ 23 Session Security .............................................................................................................................. 24 Network-based Security ................................................................................................................ 25 Security Tokens .............................................................................................................................. 25 Data Security .................................................................................................................................. 25 Infrastructure ................................................................................................................ 27 Scheduled releases ......................................................................................................................... 29 Metadata-driven Architecture ...................................................................................................... 30 Force.com Database ..................................................................................................... 30 Standard Field Types ..................................................................................................................... 31 Relationship Fields ........................................................................................................................ 32 System Fields .................................................................................................................................. 33
Apex Triggers ..................................................................................................................................34 Platform Limits ............................................................................................................ 35 Salesforce.com Editions ............................................................................................... 36 Sales and Service Cloud Editions .................................................................................................36 Custom Cloud Editions .................................................................................................................39 Salesforce.com License Types ..................................................................................... 41 Standard Salesforce.com Applications ......................................................................... 43 Salesforce CRM Content ...............................................................................................................44 Chatter ..............................................................................................................................................44 Salesforce Knowledge ....................................................................................................................44 Entitlements & Service Contracts ................................................................................................44 Salesforce Ideas ...............................................................................................................................45 Salesforce Answers .........................................................................................................................45 Salesforce Mobile............................................................................................................................45 Customer Portal ..............................................................................................................................45 Partner Portal ..................................................................................................................................46 Salesforce to Salesforce .................................................................................................................47 Force.com Sites ...............................................................................................................................47 Standard Objects .......................................................................................................... 47 Account ............................................................................................................................................47 Person Account ..............................................................................................................................48 Contact .............................................................................................................................................48 Lead ..................................................................................................................................................49 Campaign .........................................................................................................................................49 Opportunity.....................................................................................................................................49 Quote................................................................................................................................................50 Product and Price Book ................................................................................................................50 Case ..................................................................................................................................................50 Custom Objects ............................................................................................................ 51 Types of Orgs ............................................................................................................... 51 Production Org ...............................................................................................................................51 Sandbox Org ...................................................................................................................................51 Developer Org ................................................................................................................................52 Partner Developer Org ..................................................................................................................52 Pre-release Org ...............................................................................................................................52 Where Should You Develop? .......................................................................................................53 Getting Started with Salesforce.com ................................................................................ 55 Managing Users ........................................................................................................... 55 Profiles .............................................................................................................................................55 Roles .................................................................................................................................................56 Groups .............................................................................................................................................57 Securing and Sharing Data .......................................................................................... 57 Object-Level Security .....................................................................................................................57 x
Field-Level Security ....................................................................................................................... 57 Record-Level Security ................................................................................................................... 57 Field Accessibility .......................................................................................................................... 60 Record Types.................................................................................................................................. 62 Automate Business Processes with Workflow ............................................................. 63 Developing Approval Processes ................................................................................... 65 Formulas ....................................................................................................................... 68 Syntax .............................................................................................................................................. 68 Cross Object Formulas ................................................................................................................. 70 Where Do I Use Them? ............................................................................................................... 70 Workflows & Business Rules ....................................................................................................... 72 Visualforce ...................................................................................................................................... 73 Limitations ...................................................................................................................................... 73 Best Practices.................................................................................................................................. 74 Examples ......................................................................................................................................... 75 Validating User Input ................................................................................................... 76 Building Public Websites ............................................................................................. 77 Going Global................................................................................................................. 78 Divisions ......................................................................................................................................... 79 Locale .............................................................................................................................................. 79 Currencies ....................................................................................................................................... 80 Advanced Currency Management ............................................................................................... 81 Translating the User Interface ..................................................................................................... 82 Using Analytics............................................................................................................. 83 Running Dynamic Reports ........................................................................................................... 84 Custom Report Types ................................................................................................................... 85 Dashboards ..................................................................................................................................... 85 Analytic Snapshots ........................................................................................................................ 87 Overriding Link, Tabs and Labels ............................................................................... 87 Sending Mass Email ..................................................................................................... 89 Importing Data ............................................................................................................. 89 Deploying Code to Production..................................................................................... 91 Force.com IDE .............................................................................................................................. 91 Force.com Migration Tool ........................................................................................................... 91 Unmanaged Packages .................................................................................................................... 92 Change Sets .................................................................................................................................... 92 Storing Application Metadata ...................................................................................... 93 List Custom Settings ..................................................................................................................... 93 Hierarchy Custom Settings ........................................................................................................... 94 Monitoring your Org .................................................................................................... 95 Debug Logs .................................................................................................................................... 95 Email Logs ...................................................................................................................................... 95 Login History ................................................................................................................................. 95 View Setup Audit Trail ................................................................................................................. 95 xi
Time-Based Workflow Queue ......................................................................................................96 Scheduled Jobs ................................................................................................................................96 Outbound Messages .......................................................................................................................96 Apex Job Queue .............................................................................................................................96 Import Queue .................................................................................................................................96 Mass Email Queue .........................................................................................................................96 Case Escalation Rule Queue .........................................................................................................96 Entitlement Process Queue ..........................................................................................................96 Bulk Data Load Jobs ......................................................................................................................97 Google Integration ....................................................................................................... 97 Add Google Docs to Salesforce.com ..........................................................................................97 Google Docs Tab ...........................................................................................................................97 Gmail to Salesforce.com................................................................................................................97 Gmail Buttons and Links ..............................................................................................................98 Google Talk Sidebar Component ................................................................................................98 Google AdWords ...........................................................................................................................98 Working Remotely........................................................................................................ 98 Force.com Connect for Microsoft Office ..................................................................................98 Salesforce for Outlook...................................................................................................................99 Force.com Connect for Lotus Notes ..........................................................................................99 Force.com Connect Offline ..........................................................................................................99 Programmatic Development Tools & Strategies ............................................................ 101 A New but Familiar Development Infrastructure ...................................................... 101 That’s Old School ........................................................................................................................ 101 Developing in the Clouds........................................................................................................... 102 The Importance of Metadata ..................................................................................................... 104 The Right Tool for the Right Job................................................................................104 Developing Applications on the Force.com Platform ........................................................... 104 Deploying Applications on the Force.com Platform ............................................................. 118 Developing Applications that Scale .......................................................................................... 122 Testing Applications on the Force.com Platform .................................................................. 124 Analysis and Maintenance on the Force.com Platform ......................................................... 128 Tools to Assist Productivity & More........................................................................................ 132 Application Support on the Force.com Platform ................................................................... 133 Programmatic Development Languages ........................................................................ 137 MVC in the Cloud .......................................................................................................137 The Model ...................................................................................................................138 Data Creation, Manipulation, Update and Deletion .............................................................. 139 Data Retrieval using SOQL and SOSL .................................................................................... 140 The Controller .............................................................................................................150 The Apex Programming Language ........................................................................................... 150 CRUD Operations ...................................................................................................................... 155 Apex Triggers ............................................................................................................................... 165 xii
Scheduling Apex .......................................................................................................................... 193 Batch Apex ................................................................................................................................... 196 Governor Limits .......................................................................................................................... 199 Debugging Apex .......................................................................................................................... 201 The View ..................................................................................................................... 202 The System Architecture ............................................................................................................ 203 MVC: Bringing it all Together ................................................................................................... 205 When would you use Visualforce? ............................................................................................ 206 Advantages of Using Visualforce .............................................................................................. 207 Visualforce Controllers ............................................................................................................... 208 Visualforce Page Syntax .............................................................................................................. 221 Output Components ................................................................................................................... 222 Static Resource in Visualforce Pages ........................................................................................ 229 Visualforce & the Web................................................................................................ 230 Visualforce Email Templates ..................................................................................................... 232 Mobile Visualforce Pages ........................................................................................................... 232 Security .......................................................................................................................................... 233 Order of Execution ..................................................................................................................... 234 Visualforce View State ................................................................................................................ 234 Development Best Practices....................................................................................... 235 Apex............................................................................................................................................... 235 Triggers ......................................................................................................................................... 235 Visualforce .................................................................................................................................... 236 Unit Testing .................................................................................................................................. 236 Miscellanea ................................................................................................................. 237 Global Variables........................................................................................................................... 237 Functions & Operators ............................................................................................................... 237 Integration with the Cloud ............................................................................................. 239 Path 1: AppExchange ................................................................................................. 240 Publishing to the AppExchange ................................................................................................ 240 The AppExchange from a Consumers Perspective ............................................................... 241 Path 2: Build Your Own ............................................................................................. 244 SOAP Based Web Services ........................................................................................................ 244 RESTful Web Services ................................................................................................................ 252 Deployment and Modifying the Model with the Metadata API ........................................... 256 File-Based Metadata API Calls .................................................................................................. 257 Force.com Web Service Connector (WSC) ............................................................................. 258 Tolerado ........................................................................................................................................ 258 OAuth ........................................................................................................................................... 258 Path 3: Native ERP & Desktop Connectors .............................................................. 259 Path 4: Middleware Connectors ................................................................................. 259 Path 5: Toolkits........................................................................................................... 259 PHP Toolkit ................................................................................................................................. 259 xiii
Self-Service Portal Toolkit for PHP 5 ...................................................................................... 260 Standalone PHP Bulk API Client ............................................................................................. 260 AJAX Toolkit ............................................................................................................................... 260 Adobe Flash Builder for Force.com ......................................................................................... 260 Salesforce Python Toolkit .......................................................................................................... 261 Force.com Toolkit for Google Data APIs .............................................................................. 261 Force.com Office Toolkit .......................................................................................................... 261 Force.com for Google App Engine.......................................................................................... 261 iOS Toolkit for Force.com ........................................................................................................ 261 Force.com for Amazon web services ....................................................................................... 261 Force.com for Facebook ............................................................................................................ 261 ActiveSalesforce ........................................................................................................................... 262 Perl Toolkit................................................................................................................................... 262 Force.com for PayPal X Payments Platform .......................................................................... 262 SalesforceCFC - A ColdFusion Toolkit for Force.com ......................................................... 262 Advanced Development Examples ................................................................................ 263 Using External ID Fields ........................................................................................... 263 Visualforce Component Ids & JavaScript .................................................................. 266 Passing JavaScript Values to Apex ............................................................................. 267 ActionSupport with Facets and JavaScript ................................................................ 268 Passing Parameters with a CommandLink ................................................................271 Passing Parameters with a CommandButton ............................................................ 272 Using Anonymous Code Blocks ................................................................................ 274 Use an Inline Visualforce Page with Standard Page Layouts ................................... 275 Apex Search with Checkbox Results using a Wrapper Class .................................... 279 Dependent Multi-level Pick Lists .............................................................................. 285 Uploading a Document using Visualforce ................................................................ 289 Uploading an Attachment using Visualforce ............................................................. 292 Visualforce and CSS ................................................................................................... 295 Redirecting Users to Different Visualforce Pages ..................................................... 297 RESTful Web Service Callouts using POST .............................................................. 300 Force.com & Case-Sensitivity .....................................................................................301 Calling a REST Web Service (XML) ......................................................................... 303 Calling a REST Web Service (JSON) ........................................................................ 307 Locking sObject Records ............................................................................................314 Automating Approval Processes with Triggers ..........................................................315 Enhancing the Lead Conversion Process ...................................................................316 Using Email Templates with Apex .............................................................................319 Writing an Inbound Email Service ............................................................................ 320 Unit Tests & Code Coverage ..................................................................................... 323 Programmatically Creating Sharing Rules ................................................................ 328 Rolling Back Transactions with Database Savepoints .............................................. 332 Enforcing Security With Sharing Keywords .............................................................. 334 xiv
Working with Person Accounts .................................................................................. 335 Summary ......................................................................................................................... 343
xv
Foreword
Y
ou’ve just picked up a book on Salesforce and the Force.com platform—welcome to the ground floor in our industry’s shift to cloud computing. Few would disagree that the development of consumer and enterprise applications has been completely transformed by the emergence of cloud computing over the past several years. First came a revolution in application delivery—the idea that applications could be delivered as a service over the internet, without any software to install or maintain. Then came a revolution in application infrastructure—the idea that developers could consume raw computing and storage capabilities as a service, without any physical infrastructure to deploy or maintain. Now we’re seeing a revolution in application platforms—giving developers the ability to build applications using higher-level building blocks, without any concept of the underlying physical machine or database. Force.com is the leading platform as a service, and represents a major contribution in our industry's shift to the cloud. Here’s why Force.com is so important to everyone in the technology ecosystem: To the enterprise On-premise platforms are lousy for custom application development. You spend lots of time planning and then building your development and deployment stack-- all before you write a single line of code that your end users actually care about. And once you’ve actually deployed, you can't take advantage of future platform capabilities without expensive customizations and rewrites. This kind of wasted effort has fueled the growth an entire industry of service providers, with busloads of consultants to build and maintain custom applications. Building on Force.com is different. Across Appirio's 200+ enterprise customers, we see savings of over 50% on operating costs and up to 5x improvements in time-to-market when building custom apps on cloud platforms. For one publishing client, we built a custom application that automated their entire publishing process in less than 6 months. Their estimate for doing this using on-premise platforms was over 3 years. In terms of ongoing cost/productivity improvements, they have estimated a 50-75% reduction in the time and effort it takes to add new products. And since the application is built on the Force.com platform, upgrades are seamless and the platform gets better over time, all for no additional cost. To application vendors Force.com is as disruptive to standalone SaaS vendors as Salesforce.com was to onpremise CRM vendors. Force.com changes the economics of building packaged applications-we experienced this firsthand at Appirio building a packaged industry-specific application 100% on Force.com. Within 6 months, we were winning deals from established competitors... even those who were committed to the SaaS model. The fact is that its hard work to be a stand-alone SaaS vendor-- you spend up to 80% of your R&D dollars on infrastructure and operations...
just “keeping the lights on.” We were able to focus 100% of our engineering on the business functionality our customers cared about. And when Salesforce released its “Chatter” social networking functionality, our application instantly became the only “social” application in the market.... a feature-set that will take our competitors dozens of developer years to replicate on their own platforms. One frequently heard sentiment is that nobody can build a “big” business using someone else’s platform. This is nonsense. Lots of big businesses have been built using the platform capabilities of others (e.g., on the Oracle database platform). There's no reason for this to change. Plenty of great businesses will be built throughout the cloud value chain, including platform providers, tools providers, and platform consumers that deliver business value directly to the customer. To the rest of the ecosystem SaaS is just starting to penetrate the full business application market, a $50-100B market that includes ERP solutions. More great businesses will built in the market for SaaS applications, and some of these companies will build their offering using the capabilities of a platform delivered as a service. But cloud platforms like Force.com also impacts the much larger business “solutions” market, composed of the software and services that companies consume to develop customized solutions. This market is 3-4 times larger than the market for business applications — generally estimated by analysts at $200-300B. And that's just the beginning-- the market for hardware and infrastructure is also impacted by cloud platforms. These markets are seeing a dramatic concentration in their buying base, and some competition or substitution from companies they never would have expected, such as salesforce.com running its global customer base using only a few thousand servers. All told, platform as a service stands has the potential to disrupt $1 trillion of IT spending. The implications? These are fundamental changes in application development that are just starting to be recognized by the broader development community. The fact that you're holding this book means that you have the opportunity to participate in this once-in-a-generation shift to a new IT architecture. Most developers out there don’t know that they don’t need to buy hardware and software anymore in order to develop and deploy world-class web applications. But you will. Enjoy this fantastic introduction to the world of developing on salesforce.com's Force.com platform—I look forward to seeing the applications that you develop! Ryan Nichols VP Product Management & Marketing, Appirio Appirio (www.appirio.com) is a cloud solution provider offering products and professional services that help enterprises accelerate their adoption of cloud applications and platforms. Appirio's innovation and expertise has been recognized by Businessweek as one of America's Most Promising Startups and by AlwaysOn as On-Demand Company of the Year. Appirio has helped more than 180 leading enterprises implement, build and manage mission 2
Salesforce Handbook
critical cloud solutions using salesforce.com, Google, Workday and Amazon. We are proud to serve a wide range of customers such as Avago, the City of Los Angeles, Diversey, Dunkin Brands, Flextronics, Japan Post Network, Ltd., IMS Health, Motorola, Qualcomm, RehabCare, Safety Kleen, Starbucks and VMware, as well as the 5,000 companies that use Appirio's products to connect and extend cloud platforms. Founded in 2006, Appirio has offices in the U.S. and Japan, and is backed by Sequoia Capital and GGV Capital. Ryan Nichols runs product management and marketing for Appirio, and has driven the growth of Appirio's products that connect and extend cloud platforms, now used by over 5,000 companies. Ryan has nearly 15 years of experience bringing together business strategy and technology in the enterprise. He joined Appirio from SAP's corporate strategy group, in the office of the CEO, where he led projects to define and execute SAP's product, platform, and M&A strategy. Previously, Ryan's background spans consulting and business software. He was a management consultant for McKinsey & Company, serving over a dozen leading financial services and technology clients. He led professional services for an analytics software startup, delivering inventory and pricing analytics software and services to retail and CPG clients.
Jeff Douglas & Wes Nolte
3
About A the Authors Jeeff Douglas is a highlyy sought-after and awardd-winning teechnologist wiith more than n 15 years off leadership eexperience crrafting techno ology solution ns for compaanies of all ssizes. His teechnology skillls were honed during the fasst and furious “dot com erra,” when he provided SAP P developmen nt services forr Fortune 5000 companiess including C Coca-Cola, An nheuser-Busch h, Disney Im magineering, Moen, M and Erricsson. After years of beingg a lowly Jaava developer,, in 2006 he ascended into o cloud compuuting. He peeriodically wriites for develo oper.force.com m and activelyy tries to work w the word “automagical”” into functional documenttation. He speaks at indusstry conferencces, developer meetups andd enthusiasticaally blogs abo out cloud computing (espeecially Force.co om) at http://bblog.jeffdouglas.com m. Jeff workss for Appirio o, a cloud so olution providder that offerrs both prodducts and pro ofessional servvices to help en nterprises acceelerate their addoption of the cloud. With o over 2,500 customers, Appiirio has a provven track reco ord of implem menting missio on-critical soluutions and devveloping inno ovative produccts on cloud platforms succh as salesforrce.com, Googgle Apps, Workday and Am mazon Web Seervices. From offices in the U U.S. and Japan n, Appirio servves a wide ran nge of comp panies including Thompso on Reuters, Japan Post Network, Lttd, Brady Co orporation, BM MC, RehabCaree, Starbucks an nd Qualcomm m. Appirio was founded in 20006, is the fasstest growing partner of salesforce.com and a Google, an nd is backed by b Sequoia Caapital and GG GV Capital. Jeff residess in Sarasota, FL, F with his wife w Cathy andd four children n Scott, Tyler,, Brittany, and Kira (adopteed). He and hiis wife have beeen medical fo oster parents for f over 12 yeaars, caring forr more than 755 children. Wes W Nolte has a long histo ory of love forr all things tecchnologybased, b with experience spanning thee entire Infformation Technology T speectrum across two continentts. A relative n newcomer to o the cloud-ccomputing sceene he has no onetheless wo on several in nternational accolades a inccluding the auspicious F Force.com Developer D Herro award; he aalso holds thee much coveteed title of Force.com F Devveloper Challen nge Winner. A prevalent memberr in a num mber of devvelopment communities, c his highly acclaimed inputt on cloud computing matters m is often n sought across the US, Euro ope, Asia and A Africa. Wes is seen n as a champio on of salesforcee.com and the Force.com Pllatform, and hiis blog on thee subject is reegarded as on ne of the mosst influential in n the world. From this soapbox he insspires the com mmunity by im mplementing and a combiningg groundbreakking technologgies in all
manner of ingenious ways. His trail-blazing employment of the Force.com platform has been hugely advantageous to many of his peers in the Salesforce arena. As the head of Cloud Computing at Telegraph Media Group, one of the most renowned media companies in the world, Wes has access to cutting edge tools long before they’re accessible in the mainstream allowing him to dabble to his heart’s delight. Wes spent 27 years living in South Africa but now resides in North London where he feeds the ducks to relax and cycles in appropriately skinny jeans.
6
Salesforce Handbook
Acknowledgements
W
riting this book was a great experience for both Wes and myself. As this was my second and Wes’ first printed publication, we had a lot to learn about the process. Even though we live on different continents and have never met in person, the magic of the Internet allowed us to work together smoothly and (semi) efficiently. What a great time we live in. We wanted to write a book that provides a high-level overview of salesforce.com and the Force.com platform that is both easy to understand and highly informative. Hopefully the information we present will provide you with a good starting point and allow you to drill down into portions of the platform that interests you. As with most endeavors, we couldn’t do it alone and would like to thank some of the key people that made this book possible. First and foremost, we’d like to thank our friends and family that spent countless weekend and evening hours helping us put this book together. Thanks to my wife, Cathy, for putting up with my crazy working hours and not killing me in the process. Even though she resists any type of new technology, she went so far as to proofread every chapter before we sent the book to print. She’s a keeper. And thanks to Wes’ fiancée Gerosha who (even as a developer in the hectic finance sector) played the role of muse, photographer and editor without even sighing a complaint. Next, we’d like to thank everyone in the salesforce.com community for reviewing our book, providing feedback and supporting us through our blogs, Twitter and various message boards. It’s a great community of passionate and supportive people and one of the things that makes salesforce.com so special. Also, thanks to Appirio and Telegraph Media Group for not only paying us a descent wage in return for our services, but for providing an environment where we have the opportunity to expand our boundaries and write this type of book. We’d especially like to thank Ryan Nichols, VP Product Management & Marketing for Appirio, who wrote the fantastic Foreword for our book. Ryan is a thought leader in the cloud computing space and we’re honored to have him take an interest in our book. And lastly, a big thanks goes to salesforce.com for making such a great product. Without their efforts we’d probably be doing something less sexy right now, like working for Oracle. We know many of the salesforce.com evangelists, engineers, product managers, professional service consultants, marketing and support reps personally and they are all a great bunch that are really passionate about their product and their customers’ success. Without their brilliance, dedication and countless hours of hard work, our jobs wouldn’t be possible. A very, special thanks goes out to all of the evangelists and especially Dave Carroll, Jon Mountjoy, Quinton Wall and Ron Hess for all their assistance and friendship over the years. Jeff Douglas Wes Nolte
Introduction
T
his book is not intended to be a deep-dive on security, programming, reporting, configuration, etc. but more of a high-level overview on salesforce.com, Force.com development, tools, methodology and other resources. We will not cover all aspects of salesforce.com. This is not the “salesforce.com Bible”. We wrote this book to (hopefully) become an invaluable resource for anyone new or inexperienced with the Force.com platform. This book contains the information that we wish we had when we started developing applications on Force.com. For new administrators and developers coming on to the platform, we see a gaping hole in existing reference books. If you are an end user you can pick up a copy of Salesforce.com for Dummies. For advanced developers that need a deep-dive into the platform, there is Development with the Force.com Platform: Building Business Applications in the Cloud by Jason Ouellette of Appirio. Our book is for people somewhere in the middle; let’s say a business analyst or a new Java or .NET developer. We would like this to be the first book you pick up after your boss walks in and says, “Let’s take a look at salesforce.com and see if we can build some applications in the cloud”. Hopefully this book will get you up and running faster and make your transition into the cloud smoother.
Target Audience This book aims to strike a balance with information for both administrators (point-n-click development) and developers (Apex and Visualforce development). We tried to construct the later “programming” sections of the book in such a way that would be beneficial not only to developers but also provide administrators with an overview of the development process without making their eyes glaze over. Our goal was to make writing code “not so scary” for administrators. The programming sections of the book were relatively easy to write since this is our bailiwick. However, it was a struggle writing the declarative portions of the book. Declarative development on the Force.com platform is where the real power lies. However, it’s very hard to provide an overview of most declarative functionality without simply rewriting the salesforce.com Help sections. We trust that we provide some value without skipping around from topic to topic too often. The announcement of VMforce was also a major driver for this book. With the possibility of 6M+ Java developers moving to the Force.com platform we wanted to provide a way to transition them easily. We wrote the more advanced developer sections with these developers in mind.
Salessforce.com iis the Final Word Throughout T th he book we’ll provide featuures explanatio ons, code sam mples, tips from m the trench hes and links to resourcess for more in nformation. O One of the great g things about salesfo orce.com is thaat they release new features and a updates th hree times per year. The bad thing about salesforce.com m is that they release new features f and up pdates three times t per year.. This makes it hard to be right 100% of o the time reggarding how th he platform “ccurrently” worrks. If you fin nd a contradicction in this bo ook it’s probably due to a recent release or o update. Thee best sourcee of informatio on is http://developer.force.com and a salesforce.com Help and d documentatio on, so alwayss check there fo for the final wo ord.
Nextt Steps After A you are ffinished readin ng this book cover c to coverr, what are youur next steps? Since we on nly provide a ccursory overview of most to opics we invite you to drill into aspects o of the platforrm that intterest you. The first website thatt you shouuld bookmarrk is http:// /developer.force.coom. This site contains the latest inform mation regardiing the Forcee.com platforrm. There are many hidden gems at develo oper.force.com m so make surre you really exxplore the sitee. For advanced developers that need a deep-dive into the t platform, A Apex, Vissualforce and strategies for working with h governors an nd limits, pickk up a cop py of Developm ment with the Forrce.com Platform:: Building Businness Applicationss in the Clooud by Jason Ouellette. O Thee book coverss a surprisinglly large numb ber of devvelopment topics and is a great refeerence for bo oth salesforcee.com adm ministrators an nd developerss. It’s a logiccal extension to this book as it exp pands on topiccs that we coveer at a high levvel.
Convventions Used in this Book B Termiinology Convventions Org An A instance in which the saleesforce.com an nd Force.com applications arre developed, ttested and ussed. Salesfforce.com Not N only the aactual compan ny, salesforce.ccom, but also collectively th he software an nd its user in nterface. Typog graphic Convventions Italic URLs, U email adddress
10
Salesforce Handbbook
Co onstant Wid dth
Used for program listings, as well as within w paragrap phs to refer to program elem metns such as variable or meethod names, data d types, keyywords and stattements. Co onstant Wid dth Bold
Shows com mmands or oth her directives suuch as clickingg a button. Ico onic Conventtions An icon n to indicate a “Tip from tthe trenches” or some otheer type of importaant note or sideebar. An icon n to indicate a “Common Pitfall” or issue that we haave come across in n the past. An icon n to indicate an n important lin nk to a websitte with a demo o or more informaation. There iss so much greaat salesforce.co om content on n the web that we didn’t want to leave it out. Therefore T we’vve set up a dellicious.com acccount for quick acccess to all of the t links that w we’ve either reeferenced or haave found useful with w more in nformation. W We’ve categorrized these liinks with deliciouus tags that youu can find in th he footnotes off each section. You can acccess the delicious bookmarkks at: http://ww ww.delicious.com/ /salesforcehandboook
Jeff Do ouglas & Wes No olte
11
In ntroductiion to Sallesforce.ccom Saalesforce.co om Overview w Salesfo orce.com is so oftware as a sservice (SaaS), meaning thatt there is simply no software to install or serrvers to maintaain. You simplly sign up for an account and saalesforce.com spins up an in nstance of theirr software that yo ou can use to run r your busin ness right awayy. Salesforce.co om offers a 30-daay trial and sin nce there is no o contract, youu can cancel att any time and waalk away if it’s not a fit fo or your busin ness. Again th here is no software to insttall; everythingg is accessiblee from your b browser so it’ss easy for useers to get staarted. Even th hough salesforcce.com is a prre-configured system you arre not locked into their pro ocesses. You can tweak saleesforce.com per p your comp pany’s specificaations, develop custom fun nctionality andd even install frree and low co ost applicationss from the App pExchange. Founded in n 1999 by Maarc Benioff (O Oracle), Parkerr Harris (Left Coast Softwaare), Dave Mo oellenhoff, an nd Frank Dom minguez (both h from Clariffy), salesforce.com started out as a Cuustomer Relatio onship Managgement (CRM) product but o over the years has evolved in nto much, muuch more. Fro om a high levvel, salesforce.ccom consists o of several pro oducts: Sales, SService & Suupport, Partnerr Relationship Management, Marketing, C Content, Ideas, Analytics, andd Chatter. Deevelopers can extend the syystem by writiing application ns on the Forrce.com platfo orm using sallesforce.com’s proprietary lan nguages Apex and Visualforrce. Salesforce.ccom provides these services “in the clouud”. By now, you’ve probably heard about cloud com mputing. It’s go one from a forrward-lookingg concept, initiaally adopted b by smaller, nim mble companiies to a seriouss requirement for a growingg number of laarger businessees. Before wee dive into saleesforce.com leet’s take a step p back and talkk about Cloud d Computing, a concept thaat salesforce.co om is champio oning.
Saalesforce.co om IS Cloud d Computin ng A number of vendors are a making claaims to offer “cloud” soluttions. Howeveer, simply mo oving your serrver to anotheer company’s data center do oes not make it a cloud solution. In mo ost developmeent communities and the entterprise compuuting space in general, g salesfo force.com, Go oogle and Am mazon.com are a leading th he march tow wards enterpriise adoption of cloud computing servicces1. The threee commonly acccepted levels of cloud comp puting offeringgs include Infrastructure ass a Service (IaaaS), Platform as a a Service (PaaaS), and Softw ware as a Serviice (Saas). Eaach has its own n unique, but sometimes ovverlapping placce in the cloud d computing sp pace with theeir own uniquue features an nd benefits. However H they do share som me common attributes inh herent to the space itself.
1
clloud-computing
The key characteristic of a cloud computing offering is that, above all, it should be multitenant. The opposite of multitenancy, single tenancy, is how most systems are currently designed today. Each customer gets their own server, database, application layer and user interface to do with what they please. With a multitenant application architecture there is a single instance of the server, database, application layer and user interface that is shared by all users but partitioned for each client’s data programmatically. All IaaS, PaaS and SaaS share this same core multitenant trait. At the lowest level, IaaS offers a physical or virtualized infrastructure to tenants on a subscription basis allowing them to pay for what they need in terms of computing power. Instead of purchasing servers, software, and physical location, a tenant of an IaaS offering can pay for these components as needed. Consider B2C companies whose do most of their business during Christmas. Gone are the days when they would have to purchase the servers and software to handle their peak Christmas demand and then let them stand idle when not needed. With leading IaaS vendors like Amazon.com offering “pay per CPU hour” pricing for Linux and Windows platforms these companies can simply spin up new server instances to handle anticipated demand. At the other end of the ladder, SaaS, much like IaaS, offers solutions to the customer on a per-usage model. The major difference is that SaaS offerings completely abstract the physical and application layers from the end user and/or developer. Salesforce.com, widely considered the leading SaaS application, provides its own customizable user interface and proprietary Apex programming language but doesn’t expose hardware or software layers to the end user. One of the major benefits of SaaS offerings is that when salesforce.com releases a new feature, fixes a bug or applies a patch, it’s immediately available to all customers. Customers may log into salesforce.com one morning and find out they have bright, shiny new features that dramatically impact their business with no effort or extra money spent to develop them. PaaS lies between IaaS and SaaS and abstracts a bit more of the low level architecture but still without providing an actual end user product. PaaS typically provides solutions stacks or building blocks that you can use to build your own solutions. Google App Engine is a prime example of a PaaS offering, currently supporting both a Java and a Python runtime allow you to build scalable web applications without the need for complex underlying hardware and software layers. Google abstracts those layers and lets you concentrate fully on business functionality. The Force.com platform is also considered a PaaS offering however it’s positioned a bit higher in the cloud quadrant than App Engine for a number of reasons. Like some other platform vendors, Force.com encapsulates the runtime environment using its own proprietary language. Apex, the language for Force.com development, looks and feels like Java in many ways but doesn’t support the full implementation of any JRE. Building solutions on a PaaS platform is quick and somewhat easy but does come with its own set of challenges. With PaaS offerings like Force.com and App Engine, a governor process, applications limits or application quotas restrict you. PaaS governors and limits protect the shared layers of the multitenant platform from being monopolized by one heavy application or runaway code. Application quotas define the daily-allotted amount of computing power, space, or bandwidth that any one application is allowed to utilize. This becomes a challenge as developers must develop solutions to operate both efficiently and with in application and/or platform restrictions. 14
Salesforce Handbook
Figure 1 - 1. Cloud C vendor laandscape (Source: Appirio CIO blog)
Take a lookk at where the major playerss sit in relation n to the types of o cloud offerin ngs we’ve disscussed so farr as well as in comparison to t each other. You can quicckly see that tthe major offferings seem to o build on eacch other. Amazzon Web Serviices, in the botttom-left sectio on, offers thee least custom mization. It sim mply removes your need to o build out a physical infraastructure, leaaving all the m management and support to your y IT staff. SShifting to the right, you see that App En ngine offers just slightly morre abstraction, now covering the platform and a infrastructture while sallesforce.com aabstracts the ap pplication, plattform and infraastructure layers. It’s importtant to note that t the placeement of the offerings on this diagram does not ind dicate preferen nce or correlaate with value in any way. E Each of thesee offerings has its own un nique value andd place in the market and we’ve w used a co ombination off them to buildd the best sollution for our customers. Eaach offering do oes provide companies with the following b benefits. Saave Money an nd Time Consider a basic Java ap pplication runn ning on WebSSphere and assume that it m meets the reqquirements fo or an applicattion that coulld be run in the cloud. With W Amazon n’s Elastic Co omputing Clouud (EC2) you can quickly build b the Linuxx stack with a preconfiguredd Apache serrver and yourr choice of Jaava application n server and database. Youu have to sup pport the op perating system m, the datab base, the app plication serveer, the securiity, and all tthe same components youu’d be supportting in an on-p premise enviro onment, excep pt the physical machine. Th his, no doubt, ssaves time and d money. But, IaaS offerings still need provvisioning and llong-term sup pport at morre layers than n the applicattion. Now, on n the flip sid de, consider tthis same application runn ning on Force.ccom. You don n’t need hardw ware provisioneed or softwaree installed, need an appliccation server or o a database. All these are wrapped into o the core and you don’t n plaatform offeringg from salesforce.com.
Jeff Do ouglas & Wes No olte
15
Innovvate Quicker Take T a look att Figure 1-2, which w shows tw wo diagrams ccomparing thee scope of acttivities and th he budget and effort of a traaditional IT deepartment with h those of ano other IT departtment that is leveraging a P PaaS offering for fo its business applications. T Take special notice of the am mount of maaintenance on the hardwaree, middleware,, and applicattion layers forr the tradition nal IT departtment. It’s app parent that all that t lost time is intruding on n the time, budget, and effo ort left over fo or innovation. Now, in comp parison, consid der the IT dep partment leveraaging PaaS offe ferings for theeir hardware aand middlewarre layers. Rem moving the maiintenance requuired to keep those layers in house, the department is free to spend that extra tim me innovating on o its core business applicaations. You miight notice thaat vendor management is a n new time-allotm ment category when you’re using PaaS so olutions. How wever, that’s a small effort in n comparison n to managing these solutio ons internally. If I you’re currrently entrenched in a trad ditional softw ware-development structure or a traditio onal IT departtment, one of these previous illustrations probably lookks very familiarr. The inefficciency of tradiitional IT is one o of the main reasons so o many comp panies are ado opting Force.com for their development platform. p
Figure 1 - 2. Tradional IT T versus IT leverraging PaaS (So ource: Appirio CIO C blog)
Whatt is Salesforrce.com? From F its humb ble start as a sales s force auttomation (SFA A) tool, salesfo orce.com has ggrown into a platform forr developing and running mission criticcal, enterprise applications. Most compaanies get starteed on salesforcce.com as a waay to track theeir customers and a prospects more efficien ntly. Salesforce CRM is a seet of business processes andd integrated ap pplications thatt help compaanies manage customer infformation, acttivities, and cconversations in one centrralized locatio on. By combin ning business processes, p peo ople, and techn nology, compaanies can drivee sales and keeep customers satisfied after the sale. For F sales manaagers, CRM allows a them to o forecast salees more accurately with reall-time visibiliity into their team’s activitiies. For sales reps, CRM sstreamlines customer interacctions 16
Salesforce Handbbook
allowing them to spend less time handling data and more time providing value to customers. Tracking sales from generated leads is the life-blood of any marketer. CRM provides marketing staff with the tools to track leads and sources, route leads to qualified sales personnel and provide analytics on what’s driving sales and what is not. After the sale, CRM helps you provide support and deliver answers fast. Whether questions come from Facebook, Twitter, email or phone, your reps can solve problems quicker and at lower costs using CRM. Salesforce.com separates its offerings into the four following “clouds”. The features and services that make up these clouds typically overlap but provide specific functionality. Sales Cloud Sales force automation is the most popular of the sales tools, allowing companies to speed up the sales process and streamline lead to cash1. According to salesforce.com, more than 82,400 customers running more than 135,000 applications empowers over 2 million subscribers worldwide to manage resources and processes more effectively, pursue more business in less time, collaborate more closely and close more deals using SFA. The Sales Cloud consists of the following: Accounts and Contacts Accounts and contacts are the lifeline of the sales process. Reps have one centralized location to get a complete customer picture at a glance—including account history, contacts, interactions, documents, and more. You can manage and track all of your information, communication, activities, and opportunities by contact, so you can close more business faster. Marketing and Leads There’s no doubt that better quality leads means more sales. You can capture leads from websites, trade shows or direct mail that can be worked from the Sales Cloud. You can score leads more efficiently and automate their assignment to the right sales rep in record time and also track your marketing campaigns for leads and contacts across a wide spectrum for a consolidated view of campaign spending and performance. Opportunities and Quotes Drive more revenue by working deals that are hot. With opportunities and quotes in one centralized location, your sales teams always have the latest opportunity related data including deal size, current stage, products involved, decision makers, milestones and customer communications. Approvals and Workflow Design, streamline and automate virtually any process including shifting territorial boundaries, product configuration, telesales scripting and sales approvals. You can automate routine activities, eliminate redundant tasks and respond to changes in salesforce.com automatically. 1
sales-cloud Jeff Douglas & Wes Nolte
17
Email and Productivity Sales reps spend a large part of their day in their email clients. Whether your company uses Google Apps, Microsoft Outlook or Lotus Notes, your sales team won’t lose a step. Reps can synchronize their address book, calendars and email with salesforce.com to dramatically improve sales productivity. Content Library With Salesforce CRM Content you can provide your sales team with a centralized content library allowing them to subscribe to and find the latest version of relevant sales collateral needed to close deals. Analytics and Forecasting Get the insight you need into your sales pipeline and revenue growth, analyze your customer data across multiple modules, and visualize results with customized reports and dashboards. With customizable forecasting, your company can effectively use its sales forecast to assist with resource planning and other supply chain management decisions. Chatter Allow sales people to collaborate in real-time to close deals faster. Chatter automatically dispatches updates on people, data and documents that help shorten the sales cycle. Partners Increase your visibility into what your direct and indirect sales channels are doing in one centralized location. Using the Partner Portal your company empowers your indirect sales channels to sell more thus maximizing channel ROI. Mobile Mobile access is becoming a necessity in today’s environment. Your sales reps need access to the latest data when they are on the road. With Salesforce Mobile reps can stay plugged in and on top of their accounts with their Blackberry, iPhone or Windows handsets. Jigsaw Data Services Get instant access to millions of leads and contacts to eliminate dead, duplicate, incorrect, and incomplete records while automating data management and hygiene processes. AppExchange Enhance your sales processes with hundreds of add-on apps and services from the AppExchange. The AppExchange is an on-demand application-sharing service that allows you to browse, test drive and seamlessly install applications that help you drive sales and increase revenue.
18
Salesforce Handbook
Service Cloud Service and support, the Service Cloud, is the premium customer service platform for providing faster, more personalized service delivered via virtually every conceivable channel whether its phone, email, instant messaging, Twitter, Facebook or other social platforms1. The Service Cloud consists of the following: Case Management Support cases enable your company to track customer’s feedback, problem, or questions with a view of all relevant account data. Cases can be created manually or automatically via web, email or from social networks. Call Center Salesforce CRM Call Center seamlessly integrates with third-party computer-telephony integration (CTI) systems to create industry leading call centers. You can provide agents with a complete customer view for every interaction enabling faster service and higher customer satisfaction. Contracts and Entitlements With customer entitlements and service level agreements at their fingertips, service reps can ensure that customers receive the level of service that they are contracted for. Customer Portal Give your customers on-demand answers and community involvement with a personalized self-service portal. The Customer Portal allows your company to deliver a personalized experience to your most important customers. Knowledge Deliver answers to your customer’s questions when they want them. Salesforce Knowledge is a powerful, fully integrated knowledge base allowing your company to deliver relevant answers to customer inquiries and provide a better customer service experience. Analytics Real-time analytics allows you to monitor customer service statistics via customizable reports and dashboards. You can dramatically improve your customer service efforts by identifying trends and identifying knowledge gaps. Analytics provide you with the metrics to keep your service and support operations running efficiently. Chatter In support it’s all about what you know. With Chatter you enable collaboration for your support reps with automatic real-time updates on people, data and documents that help solve problems faster. 1
service-cloud Jeff Douglas & Wes Nolte
19
Email Provide your users with quick, convenient email tools for standardized messaging and branding as well as delivering content and solutions quickly and directly to customers. Community Salesforce.com communities allow you to harness your customer community enabling them to help one another plus uncover new ideas to improve your company, products and processes. Partners Empower your channel partners with the tools to provide better and more-effective service with the Partner Portal. Your company gains increased visibility into what your partners are doing thus maximizing channel ROI. Approvals and Workflow Design, streamline and automate virtually any support process including quotes, returns, and case resolution. You can set up simple or sophisticated approval automation for virtually any process from discount requests to refunds. AppExchange Extend your service and support capabilities with hundreds of add-on apps and services from the AppExchange. The AppExchange is an on-demand application-sharing service that allows you to browse, test drive and seamlessly install applications that help you deliver better support. Collaboration Cloud Salesforce.com’s latest release is the Collaboration Cloud with Chatter1. With Chatter, users can collaborate more effectively by following people, documents and data that is important to them with real-time update feeds. Users can set up groups and profiles to promote collaboration across multiple business applications while making sure people see only information that they have access to based on the Org-wide security and sharing model. Force.com Custom Cloud The Force.com Custom Cloud is a radical shift for salesforce.com2. No longer can salesforce.com be marginalized as “just a CRM”. You can build virtually any application with this PaaS service. Why would you want to build your next application on the Force.com platform? Enterprise application development with traditional software has become too complex, too slow, and too expensive. Building applications on the Force.com platform is faster, less 1 2
collaboration-cloud custom-cloud
20
Salesforce Handbook
expensive, and produces higher quality applications than building on traditional on-premises platforms. Industry analysts state that building applications on the Force.com platform is 5X faster at ½ the cost because cloud computing: 1.
Delivers faster time to value
2.
Requires no up-front capital expenses
3.
Minimizes operational costs
4.
Requires fewer technical resources
5.
Simplifies integration
What makes application development on the Force.com fast and cost-effective? Programmable user interface Force.com automatically generates a rich UI that can be customized by user profile with a simple, intuitive drag-and-drop page layout editor. If you want more control over the presentation layer, you can build your own UI with HTML, Flash, Flex, JavaScript and CSS. Programmable cloud logic Using a point-n-click, declarative interface you can enforce rules, define processes and trigger events for your custom applications. For more granular control use the Force.com IDE to write Visualforce and Apex code that implements functionally to extend the platform. Real-time database customizations Design and implement your data model with a simple point-n-click UI to define custom objects, fields, relationships, formulas and more. The database is tightly integrated with other parts of the platform providing reporting and search capabilities for all objects with no extra effort. Granular security and sharing Easily control access to data at the object, field, or record level. Effortlessly create custom restriction and sharing rules across roles and profiles that are enforced by the UI, APIs, search results, reporting and analytics. Integrated content library Finding content related to a business should be as easy as finding a video on YouTube. With great search results, user ratings, comments, and tagging, you can find the right content at the right time. And the integrated content library makes it easy to share presentations, video clips, documents, spreadsheets, or just about anything else. Visual process manager A new visual process manager allows you to design wizards, multi-step processes and automate manual tasks including approvals, task assignments and notifications. Jeff Douglas & Wes Nolte
21
Custo omer-facing w websites Not N only can yyou develop internal applicattions for your ccompany but you y can also ddesign, build and host puublic-facing websites w on th he Force.com m platform ussing standard Web techno ologies such ass HTML, Flash h, Flex and JavvaScript. Custo om Applicatio on Developmeent The T majority o of salesforce.co om customizatiions are done with the declaarative, point-n n-click interfaace. However, in certain casees you may neeed to create en ntirely new pro ocesses or inteerfaces that arre beyond the scope of the current declarrative capabilitiies. In these cases, salesforcee.com offers proprietary lan nguages, Apex and Visualforcce, which allow w you to write custom code o on the 1 Force.com platform . Apex is a strongly-typed, s , object-orienteed programmiing language tthat is compilled and execcuted on the Force.com multitenant m in nfrastructure. If I you have some develo opment experieence, Apex sho ould be fairly easy to pick up.. The languagee looks and feeels like Java and a has similarr variable and d expression syyntax, block aand conditionaal statement syyntax, loopin ng constructs, o object and arrayy notation, passs by referencee and other feattures that you might expectt in high level language. Wheere Apex shinees is its built-in n support for database d operaations. Apex supports s DML L statements fo or inserting, up pdating, upsertting and deletiing of records along with a powerful inlin ne query (SOQL L) and search (SOSL) ( syntax for locating reecords. To T build appliccations or custo omize the salessforce.com UI,, developers usse Visualforce, a tagbased markup m languaage similar to HTML, H in conjuunctions with A Apex code. Visuualforce tags prrovide develo opers with the ability to buiild AJAX-y ap pplications witth surprisingly few lines of code. Visualfforce pages caan consist of standard s or custom componeents intersperssed with snippets of HTML L, CSS or JavaSScript. We’ll be diving into Ap pex and Visualfo force in-depth later on in the b book.
F Figure 1 - 3. Cusstom developmeent on the Forcee.com platform. 1
apex-intro
22
Salesforce Handbbook
VM Mforce Salesforce.ccom recently accounted a a paartnership with h VMware to develop a new w product callled VMforce that allows Jaava developerss to write natiive apps in the cloud that sseamlessly ho ook into the Force.com platfform1. Java deevelopers can use the Springg Eclipse-based IDE to wrrite standard P POJOs, JSPs and a Servlets that t deploy efffortlessly to VMforce V serveers in the sallesforce.com ddatacenters. Th he native hooks into the Fo orce.com platfform (e.g., JPA A, REST) allo ow developers to write app plications thatt may normallly exist outsid de the platform m due to go overnor limits or other consstraints. Comp panies can levverage existingg developmentt skills to mo ove legacy Javva apps to th he cloud, devvelop new Javva apps that run in a muulti-tenant en nvironment or reuse existing Java J libraries that t are not avaailable on the Force.com F plaatform.
Seecurity Security is baked into all a aspects of Force.com in ncluding user,, session, netw work and plaatform restricctions2. The platform p featuures a robustt and flexiblee security arcchitecture, pro oviding granullar control oveer users, netwo ork access, andd data not onlly from a proggrammatic asp pect but from system configguration as welll. These securiity protocols are a intended to o not only pro otect data andd logic from unauthorized exxternal access,, but also from m unauthorizedd internal acccess as well. W When you acccess the appliication using a salesforce.co om-supported browser, Secure Socket Layer (SSL) technology protects youur informatio on using botth server authentication an nd data encryp ption, ensuringg that your datta is safe, securre, and availab ble only to reggistered users iin your compaany. We highly encourage you to visit the http://trust.sale lesforce.com/securrity site for thee latest in seccurity educatio on. This is where w salesforrce.com customers can learrn about secuurity best praactices, learn h how to spot suuspicious emaills and attend seecurity webinaars. Usser Security aand Authenticcation When a new w salesforce.co om instance iss provisioned, a unique “Orgg ID” is generaated. You willl need this Orrg ID anytime that you conttact salesforce..com for suppo ort, billing or activation of features. Thiss Org ID is ussed for both seecurity and data access. To find f your Orgg ID, click Se etup -> A Administrat tive In nformation. .
Setup p
->
Com mpany
Prof file
->
C Company
Figuree 1 - 4. The “Org g ID” displayed in the Builder
1 2
vm mforce seecurity Jeff Do ouglas & Wes No olte
23
Your producttion Org ID will w always rem main the same but a new Orrg ID will be generaated each timee your refresh h a sandbox. This T may affecct any third-party too ols that are liceensed by Org IID. Salesforce.com S requires that users login in nto the platfo orm with a un nique username and passwo ord. This deterrmines the insttance and Org ID for the useer and ties thesse identifiers to o their session n. Each requestt to the platform m utilizes this session s and thee associated Orgg ID to segmen nt and compaartmentalize datta protecting yo our company’s data from userrs outside your Org. Salesforce.com m usernames must be un nique across all a production n and sandbox enviironments. Fo or instance, tw wo production Orgs cannott have the same useername
[email protected], but it can c exist in b both a production an nd a sandbox Org. O Companies C thaat utilize singlee sign-on to sim mplify and stan ndardize their user authenticcation can im mplement either delegated or federated auth hentication witth salesforce.co om1. Using U delegated authenticatio on, Force.com m does not vallidate passworrds but insteadd uses an exteernal Web servvice to validatee user credentiials. When a usser attempts to o login, the plaatform checkss the user’s pro ofile to see if th hey are enabled for SSO. If sso, it makes a Web W services ccall to the en ndpoint specified for the Orgg, asking it to validate the username and password. p Thee Web servicee checks the crredentials again nst an identityy store (e.g., LD DAP, OpenID D) and either reeturns “true” or “false”. If true, the user is granted acceess to the appllication and prroceeds normaally. If false, the t user is info ormed that theiir credentials are a invalid. Federated F auth hentication, th he preferred an nd default of the two meth hods, uses Seecurity Asserttion Markup L Language (SAM ML) to send authentication a n and authorizzation data bettween affiliatted and unrelaated Web servvices. Federateed authenticattion does not validate the user’s actual password on tthe Force.com m platform. Instead, the platfo form receives a SAML assertiion in an HT TTP POST reqquest. The SA AML assertion has a limited vvalidity period d, contains a uunique identiffier, and is digiitally signed. Iff the assertion is still within its validity period, has an iden ntifier that haas not been uused before, an nd has a valid signature from m a trusted id dentity provideer, the user iss granted accesss to the appliccation. If the assertion a fails vvalidation for any a reason, thee user is informed that theiir credentials are invalid. With W the Wintter ’11 release salesforce.com m now suppo orts OAuth2 for f authorizingg web applicaations. This no ot only allows you to extend d the reach off your external applications b but to do so in a more seccure manner ass you are no lo onger requiredd to store userr credentials in n your client applications. A number of authentication a n flows for OA Auth 2.0 are suupported, inclluding the weeb server flow, user-agent flo ow and SAML assertion flow w. Sessio on Security When W loggingg in, salesforce.com issuees a session n cookie to record encrrypted authen ntication inform mation for the duration of a the session.. Session security is used to o limit 1
sso
24
Salesforce Handbbook
exp posure to youur network wh hen a user leavves their comp puter unattended while still llogged in. Th he session timeeout is configgurable for all users within tthe Org. When n a user’s sesssion times ouut (by default iit’s two hourss), they are prrompted with a popup that asks them to continue wo orking or log o out. If they do not respond to o the dialog att all, they are auutomatically lo ogged out. Yo ou can edit theese setting by clicking Setup p -> Administtration Setup -> - Security Co ontrols -> Session Settings. Neetwork-based d Security To help p prevent hackeers and otherr unauthorizedd users from m accessing your data, sallesforce.com p provides the ab bility to define the hours thaat users can loggin plus the raange of IP addresses that lo ogins can origiinate from. If a user attemptts to login from an IP not ddefined in thee network list, they will send d a challenge email e asking th hem to confirm m their attemptt to login. Yo ou can also wh hitelist IP addrresses from which w users can n always login without a chaallenge by clicking Setup -> Adminis stration Se etup -> Se ecurity Con ntrols -> N Network Ac ccess.
Seecurity Token ns Force.com has an additio on layer of acccess for extern nal and client applications. IIf you are run nning a deveelopment tooll (e.g., Data Loader, Forcce.com IDE) or developin ng a web application that uses the Web services API, you will need to append a special s securityy token to thee end of your p password if th he IP address iss outside of thee trusted IP raange. To receivve or reset your security token click Setup -> > Personal l Setup -> My Pe ersonal In nformation -> Reset Security Token T . This w will create a new n token andd send an em mail to the emaail address conttained in the user’s u account. E Each time you reset your paassword a new w security tokeen will be auto omatically em mailed to you.. Be careful when w resetting an administraator password as it may afffect running applications and a lock userss out. For extternal applicattions you m may want to create c a new “API-only” uuser and set it’s i password to never exxpire. Daata Security t most chaallenging and complex pro ocesses in Securing aaccess to dataa is one of the sallesforce.com1. Locking down n access is don ne by a combin nation of profille and role andd involves configuring objeect level secuurity, field levvel security an nd record level security. Iff you are im mplementing seecurity and shaaring rules forr your Org yo ou will want to o research thiss topic in depth and test yyour design in a sandbox to insure i that useers don’t have access to unaauthorized fieelds and recordds. Security is configured byy both user profile p and rolle. Profiles aree typically defi fined by a useer’s job function and are a collection c of settings and peermissions thatt determine wh hat a user can n do in the ap pplication. Currrently, a user can only be aassigned to on ne profile. A uuser’s role 1
seecurity-data Jeff Do ouglas & Wes No olte
25
defines which actuall records they have h access to o. Object level security is used to control C CRUD access to objects by profile. For eaach profile youu can determin ne whether or not n a user can view, create,, edit, or deletee any instance of a particular type of objectt.
Figure 1 - 5. 5 Configuring CRUD C access fo or a profile.
Once O you havee locked down access to objeects by profile,, you can limit access to indivvidual fields with w field-leveel security. Fielld-level securitty determines whether a useer, based upon n their profilee, can see, editt, and delete th he value for a particular p fieldd on an object.. This allows yyou to protecct sensitive fieelds (e.g., payrroll informatio on, social secuurity numbers) without haviing to hide th he entire object from speciffic profiles. Th hese restriction ns are also en nforced througgh the variouus salesforce.co om APIs.
Fiigure 1 - 6. Conffiguring accountt field level secu urity for a profilee.
Record-level R seecurity grants users access to the individdual records in i your Org aand is configgured with a co ombination of Org-wide defaaults, the role h hierarchy and sharing s rules. Configuring C reecord-level seccurity begins by b setting up the Org-widee defaults forr each object. These settinggs specify the default d level off access to reco ords in the Orgg. For most ob bjects, Org-w wide sharing seettings can be set s to Private, Public Read O Only, or Publicc Read/Write. With these setting s in place you basicallyy lock down access a to the m most restrictivee level and theen use the rolle hierarchy an nd sharing rules to open up access a to users..
26
Salesforce Handbbook
Figure 1 - 7. Org-wide default setting fo or sharing modell.
You can sh hare access to records by a user’s position n in the role hierarchy. h Youu define a rolle by its positio on in the role hierarchy, h which is similar to o an org chart. A user has access to all reccords owned b by roles beneatth them in the role hierarchyy. This ensures, for example, that sales maanagers have aaccess to the saame data as th heir sales reps. You can also use u a territory hierarchy to share records based upon crriteria such as zip z code, induustry or a custo om field. You can allso manually and programm matically sharee records with h sharing ruless. Sharing rulles let you make automatic exceptions e to Org-wide defaaults for particcular sets of (ssomewhat staatic) users to giive them accesss to records th hey do not own n or cannot no ormally see. Prrofiles determine what a useer can “see an nd do” with different types o of objects w while roles determine which records r a user h has “access” to o.
In nfrastructuree Infrastructuure is one of th hose things thaat you sometim mes take for grranted in a SaaaS or PaaS envvironment1. D Development in n the cloud inh herently removees the necessityy to be concern ned about inffrastructure an nd allows us to focus more m resourcess on businesss processes. However, inffrastructure is one of the seecret ingredien nts of salesforrce.com. Over 77,000 comp panies and commercial venddors trust the platform p to deliiver robust, reliiable, Internet--scale applicatio ons. Salesforce.ccom has five main m data centeers and is curreently building out o two new ones in the USS. Equinix ow wns these faciliities and salesfforce.com co-llocates their seervers there. T To ensure avaailability and reedundancy, saleesforce.com usses multiple neetwork vendorss at these locatiions.
1
Location
Function
San Jose, CA A
Main n Production D Data Center
Reston, VA
Prod duction & Backk-up Data Cen nter
Singapore
Prod duction Data C Center
Japan
Prod duction Data C Center
San Francisco, CA
R&D D Lab and Tap pe Archive
in nfrastructure Jeff Do ouglas & Wes No olte
27
Saleesforce.com reecently announ nced plans to b build a new datta center in Lo ondon by 22012. Each E user thaat logs into salesforce.com s m is mapped to what is called c an “Orrg”, a compllete “instance”” of the salesfforce.com sofftware stack. SSalesforce.com m has roughly 3000 Dell servers (50% % are idle, staged for disaster d recovery) configuured in a ““pod” infrasttructure. Thesse pods are cluustered pools of RedHat Liinux boxes ruunning open source Resin app servers, O Oracle RAC database d instan nces, Java app p servers, Luceene full-text ssearch servers, load balanccing servers and a a SAN disk d array. Requests to theese app serverrs are stateleess providingg for a high h degree of scalability an nd allowing for long run nning transactions to utiliize multiple boxes. The salesforce.com n network archiitecture is designed for maassive failoverr. Virtually eveery transaction n from the prrimary data cen nters are repliicated in reall-time to the R Reston, VA baack-up data ceenter. To T ensure th hat users havve a secure browser con nnection to the salesforcee.com enviro onment, all con nnections are via SSL 3.0/T TLS 1.0, usingg global step-uup certificates from Verisiggn. In responsse to phishingg attacks, salesfforce.com hass significantly stepped up seecurity and usser education. For an extra layer of securitty, all data is trransmitted across encrypted links, they have h implemen nted an extra token-based t e external access protocol and d you can configure networrk access by IP P and time fram me. When W you sign n up for an acccount, your Org O is provisio oned on an in nstance based upon your lo ocation: Reegion
Pods
No orth America
na1, na22, na3, na4, na55, na6, na7
Jap pan
ap0
AP PAC
ap1
EM MEA
eu0
SSL L
na0
You Y can determ mine what insstance your Orrg is running on by lookingg at the URL iin the addresss bar.
Fig gure 1 - 8. The in nstance for the Org O based upon the browser UR RL.
Sandbox S Orgs run on their own o instances as well (cs0-cs5 and tapp0 for f older Orgss) and are on n different main ntenance and upgrade u scheduules. Knowing K which instance youur Org runs on n is very impo ortant as salesfforce.com scheedules mainteenance, updates and upgrades per instan nce. Addition nally, when th here are outagges or 28
Salesforce Handbbook
dissruption they typically do not n affect all instances. i Youu can visit httpp://trust.salesforrce.com for reaal-time and hisstorical inform mation on systeem performance, planned maintenance m and security thrreats and best practices.
Fiigure 1 - 9. Trust.salesforce.com m displaying servvice performancce history.
Sccheduled releaases Salesforce.ccom schedulees three majo or seasonal reeleases per yeear: Spring (F February), Suummer (June) aand Winter (O October). These releases typically contain changes c to a w wide range of salesforce.com products and a services including the user interfacce, desktop in ntegration pro oducts, develo opment IDE, tools and AP PIs. These relleases are rollled out to users at no additional chargge and are avaailable to everryone on the platform. Som me features th hat greatly im mpact the user experience aree required to be b enabled by tthe Org’s adm ministrator. Forr example, theere is a new feeature in Winteer ’11 that allo ows a user to cclick on a record in table or chart in a rep port and be taaken to the reecord detail paage instead of another summ mary level. Th his feature muust be enabled by the Org ad dministrator. Salesforce.ccom works very hard to ensure compatibiility of existingg code and fun nctionality and we’ve seen vvery few instances where up pgrades break existing functiionality. Salesfforce.com acttively strives to implement new n functionaality that users request. Userrs submit new ideas for fun nctionality at the IdeaExcchange allowin ng other users to vote th he idea up o or down. Sallesforce.com ttakes these po opular ideas in nto account wiith each releasse and decidess whether theey are rolled in nto the next release. Each rellease typically contains a num mber of ideas ssubmitted byy the salesforcee.com commun nity. A couple o of months befo ore the upcom ming release, saalesforce.com makes m availablle a list of useer submitted iddeas that are under u considerration by Prodduct Managers for the next reelease. As thee release date gets closer, saalesforce.com starts s commun nicating some of the new feeatures on varrious blogs aand webinarss. They also make pre-reelease trial Orgs O available so that administrators an nd developer can test out the t impact of the new functtionality. As th he release Jeff Do ouglas & Wes No olte
29
data approaches, salesforce.com allows customers to optionally upgrade their sandboxes so that they can test out new customizations or features before rolling them out to users. Finally, salesforce.com schedules the updates of individual instances and notifies customers of the upgrade window and scheduled downtime. Following the upgrade, users simply log into their Org and are greeted with new and enhanced features and functionality. Metadata-driven Architecture To meet the extreme demands of its large user population, Force.com’s foundation is a metadata-driven software architecture that enables multitenant applications. In Force.com, everything exposed to developers and application users is internally represented as metadata. Forms, reports, workflow, user access privileges, tenant-specific customizations and business logic, even the definitions of underlying data tables and indexes, are all abstract constructs that exist merely as metadata in Force.com’s Universal Data Dictionary (UDD). For example, when a developer is building a new custom application and defines a custom table, lays out a form or writes some procedural code, Force.com does not create an “actual” table in a database or compile any code. Instead, Force.com simply stores metadata that the platform’s engine can use to generate the “virtual” application components at runtime. When someone wants to modify or customize an aspect of the application, all that’s required is a simple non-blocking update to the corresponding metadata. Because metadata is a key ingredient of Force.com applications, the platform’s runtime engine must optimize access to metadata; otherwise, frequent metadata access would prevent the platform from scaling. With this potential bottleneck in mind, Force.com uses metadata caches to maintain the most recently used metadata in memory, avoid performance sapping disk I/O and code recompilations, and improve application response times. Force.com stores the application data for all virtual tables in a few large database tables that serve as heap storage. The platform’s engine then materializes virtual table data at runtime by considering corresponding metadata1. To optimize access to data in the system’s large tables, Force.com’s engine relies on a set of specialized pivot tables that maintain denormalized data for various purposes such as indexing, uniqueness, relationships, etc. Force.com’s data processing engine helps streamline the overhead of large data loads and online transaction processing by transparently performing data modification operations in bulk. The engine has built-in fault recovery mechanisms that automatically retry bulk save operations after factoring out records that cause errors. To further hone application response times, the platform employs an external search service that optimizes full-text indexing and searches. As applications update data, the search service’s background processes asynchronously update tenant- and user-specific indexes in near real time. This separation of duties between the application engine and the search service lets platform applications efficiently process transactions without the overhead of text index.
Force.com Database One of the key features of the Force.com platform is the Force.com database, a powerful and intuitive data persistence layer baked into all aspects of platform1. The Force.com database 1
database
30
Salesforce Handbook
not only acts as a persistence layer for your data but also magically generates the user interface for creating, updating and displaying records. Non-technical users can create, configure and deploy persistent objects using the point-n-click, form-based interface in the Setup environment. Salesforce.com takes a slightly different approach with their database layer. Instead of coming from a pure database perspective, the Force.com database takes a more abstract approach and represents everything as objects. Whereas a traditional database has tables and columns, the Force.com database is composed of objects and fields. You can think of the two in roughly the same way. Standard Field Types The Force.com database supports many of the field types that you would expect to find in a relational database plus some surprisingly useful additional ones:
1
•
Auto Number - A system-generated read-only sequence number with a format that you can define. The format is configurable (i.e., PR-00001) and automatically increments for each new record inserted.
•
Formula - A read-only field that derives its value from a formula expression you define.
•
Checkbox - Displays as a checkbox for Boolean data.
•
Currency - A currency formatted number with optional multi-currency support.
•
Date or Date/Time - For date or date and time combinations, allows the user to enter a date or pick a date from a popup calendar.
•
Email - For entering email addresses that are also validated to ensure proper formatting.
•
Number - For representing real numbers with optional decimal points.
•
Percent - Allows users to enter a percentage number (e.g., 25) and automatically displays the percent sign with the number.
•
Phone - Allows users to enter any phone number and automatically formats it as a phone number.
•
Picklist and Multi-Select Picklists - Allows users to select one or more values from a list you define. However, the values in the object’s field are not restricted to these values.
•
Text and Text Areas - For representing text up to 255 characters in either a single line or multi-line text box.
•
Text Area (Long) - For representing text up to 32,000 characters in a multi-line text box.
database Jeff Douglas & Wes Nolte
31
•
Text Areea (Rich) - Fo or representingg rich text (HT TML) up to 32,,000 characterss with formattedd text, images and a links with an embedded WYSIWYG editor. e
•
URL - A Allows the userr to enter a weebsite address that open thee URL in a sep parate browser w window when clicked on.
Relatiionship Fields The T Force.com m database sim mplifies that way w that developers work with w related reccords. Relatio onal databasess enforce dataa integrity witth primary and foreign keyy relationships. The Force.com data absstracts and sim mplifies these requirements by creating simply s relation nships betweeen objects. A relationship field stores th he ID of thee parent recorrd in a pre-deefined relationship, providiing a user interface represen ntations in both h the parent and a child recorrds as well ass structured waay to query thee chain of relatted objects. Forr each relationsship you can sp pecify up to 5 levels in your queries. This aallows youu to build som me powerful an nd useful queriies that let youu reach up or down the relationship ch hain to fetch data. d Looku up Relationsh hip This T relationsh hip creates a simple (foreiggn key) relationship that liinks one objeect to anotheer. These can n be used to create one-tto-one and one-to-many reelationships. W When displayying records in n the salesforcce.com UI, thee platform gen nerates a link to o the related rrecord allowin ng you to naviggate from reco ord to related record. r Masteer-Detail Relaationship A master-detaill relationship creates c a speciial type of relattionship betweeen two objectts, the parentt, or “master” object and its child, or “dettail” object. Deetail objects caannot live with hout a masterr object and o once created, th his relationship cannot be cchange. Detail objects also in nherit the seccurity from th he master objeect and deletess cascade from m the master to o the detail ob bjects. An exxample of a m master-detail reelationship wo ould be a Salees Order (masster object) an nd the individ dual Sales Ordder Line Items (detail objectss) associated w with it. The linee items cannott exist withouut the order heeader and are deleted d when th he order headeer is deleted. A few caveats exist with thiss type of relatiionship. An ob bject cannot be the master in n one relationship and a detail in anotheer. An object can c be the maaster in multiplle relationship ps, but these relationships r cannot be used to implementt multiple levells of detail. This may seem backwards, but you createe a master-detail relationsh hip by addding a field to the child objeect instead of tthe parent. Ho owever, you cannot creaate a master-deetail relationsh hip for an objeect that curren ntly contains daata. A worrkaround is to create a lookuup relationship p to the masteer, add a value to all chilld records for the relationshiip, and then cconvert the loo okup relationsh hip to am master-detail rellationship.
32
Salesforce Handbbook
The masteer object in a master-detail relationship ccan also contaain a special ffield type callled a rollup ssummary field. These fields store values aaggregated fro om the child rrecords in thee relationship.. For example,, in our Sales Order examplle you could create an “Ordder Total” rolllup summaryy field that auttomatically sum ms the amoun nt of all line items. i Rollup summary fieelds can either count records or sum, min n and max specific fields bassed upon all records or reccords meetingg certain critteria (e.g., maatching recordd type, createed date before today, Bo oolean value). Many-to-Manyy Relationship p There are development scenarios where you will n need to impleement a manyy-to-many rellationship wheere a record on n one side of a relationship can be associaated with man ny records on n the other sidee. In this case salesforce.com m uses an intermediate objectt, which they rrefer to as a junction j objecct (aka mappin ng table or pivvot table). To implement a junction objecct, simply creeate a custom object and ad dd two masterr-detail relation nships to the objects o on eacch side of thee relationship. An issue with junction n objects invo olves usabilityy. When you add the junction ob bject as a related list on a paage layout, the user may havee to make an extra series of clickss to create neew records orr navigate bacck to the original reccord. This can be somewhat confusing from m a UI perspective. Syystem Fields It’s no surp prise that the Force.com daatabase contaiins a number read-only systtem fields automatically asssociated with h each objectt. For each rrecord in thee database, F Force.com automatically asssigns an identitty field (called ID) and manaages the identitty data. The ID D is a case sen nsitive 15 chaaracter string that is used to uniquely identify the record r througghout the plaatform. To view a record in the salesforce.com m UI, simply ap ppend the reco ord ID to your saleesforce.com domain. Fo or instance, when yo ou enter https://na1.salesforce.com/00014000000Hgg6pL, Force.co om will fetch th he record from the database, d along with its associiated metadataa, and display tthe record using the automatically a g generated UI baased upon youur security settiings. Each recorrd is also requuired to have a special “nam me” field. This can either bee an autonuumber field or a human-read dable identifierr for the recordd to distinguissh one record from one another. When F Force.com gen nerates a user interface, you’lll see that the value v for the n name field is always a displayeed as a link to the detail pagee of the recordd itself. Other read-only, systtem fields incclude: •
CreattedDate – the date and timee when the reco ord was createed
•
CreattedById – thee ID of the Useer that createdd the record Jeff Do ouglas & Wes No olte
33
•
LastMod difiedById - th he ID of the User U that last m modified the reecord
•
LastMod difiedDate – the t date and tim me when the rrecord was last modified by a User
•
SystemM ModStamp – the date and tim me when the o object was last modified by a User or system m process (e.g., trigger, web seervice) SSystem fields are a read-only. However, thiss can pose a prroblem when trying tto import dataa. You may want w to importt created dates or created b by for tthese new reco ords. You can contact c salesfo orce.com support and ask them to eenable “Createe Audit Fields””. This will allo ow you to imp port some readd-only ffields for mostt standard and all custom objjects using the Data Loader.
In I addition to traditional dattabase function nality, the Forcce.com databaase has a numb ber of servicees baked-in. Apex Triggers Similar S to otheer database trigggers, Apex Triggers T can bee programmattically configurred to fire beefore or after a record is creeated, updated,, deleted or un ndeleted1. Trigggers have acceess to virtuallly all Apex fun nctionality with h a few exceptiions (e.g., no ccallouts). Validaation Rules These T rules help enforce data d integrity from both th he salesforce.ccom UI and API2. Validaation rules fire each time a record r is saved d and perform ms the validatio on against a ccertain field based b upon a fformula expression. If the expression e evaaluates to true the save is ab borted and an n error message is displayed (or ( sent back through t the AP PI). For instan nce, you can crreate a validattion rule statin ng that a field always contain ns a value or tthat a number entered into a field falls within w a certain range. Formu ulas These T dynamiccally generated d fields are the real workhorsses of Force.co om. A formulaa field behavees much like a spreadsheet formula in th hat it reflects some calculatiion based on other fields and operation ns based upon n those fields3. For instance, for an opp portunity you could d amo ounted field: { {!Amount} – ({!Amount t} * create a formula thaat contains a discounted {!Pct t_Discount} }). This amo ount would diisplay on any page layout, could be useed for reportiing and wouldd look like a reggular field to queries. q Field History You Y can confiigure each objject to track changes c to field values (up to 20 fields). Field historyy can be displaayed on the page layout sho owing the befo ore and after value, v who chaanged the field and the datee and time it was w changed. intro-ttriggers validattion-rule-examplees 3 intro-tto-formulas 1 2
34
Salesforce Handbbook
You can contact salesfforce.com Sup pport and haave them increase the number off fields that can be trackedd for your Orgg. We have seen them increased this number 400 for most requuests.
Pllatform Lim mits Every programming en nvironment im mposes its ow wn sets of co onstructs, feattures and constraints. Thee Force.com platform p is no different. Alll programs, seervices and ap pplications run nning on the p platform run in n a multi-tenan nt environment where their resources r (e.g.,, memory, network, database connection ns) are being shared s with evvery other pro ogram on the platform. Th herefore it’s exxtremely imporrtant that the platform p preveents rouge, run naway applicatiions from satturating system m resources an nd degrading the t performan nce of other ap pplications also o running on n the platform m. Force.com im mplements a number of go overnors and limits l to ensurre that all applications “plaay nicely” with h each other. One O of the main n tasks for new w developers iis learning ho ow to write app plications that run within theese boundaries. T often forrce us to take a step back an nd analyze Governorss are not evil. They our code to t ensure that we are usingg best practices and system resources efficiently. Salesforce.com m engineering is actively wo orking to stream mline and make goveernors and lim mits easier to work with. The T Winter ‘111 release simplifies some s of the lim mits surroundin ng test method ds. Limits com me in many flavvors and may or o not be in reelation to the edition you are running1. Fo or instance, theere is a limit to t the numberr of application ns you can creeate, the numb ber of tab forr an Org and the number of o custom fiellds an object may have. Wh hen developin ng custom applications, youu have to activvely take into consideration c A Apex governorrs and limits. T The Apex run ntime engine sstrictly enforces limits and issues i a runtim me exception if, i for instancee, a script exceeds a limit. Limits differ based upon th he entry pointt of your codee. For instancee, when a Trrigger is called from a Visuallforce Controlller the Apex rruntime enginee uses the limiits for the Visualforce Conttroller, not thee limits for the Trigger. Governor exceptions e cann not be caught aand handled likke most other exxceptions. However, you y can test forr limits program mmatically usin ng the Limits claass, which returns the amount of reso ources availablee in the currentt context. t by salesforce.com m using theirr internal Some limiits can be tweaked provisionin ng feature or “black “ tab”. F For instance, the t API limits are 5000 calls per usser per 24 houurs. However, salesforce.com m Support can n increase this limit on a case by casse basis.
1
go overnor-limits-inttro Jeff Do ouglas & Wes No olte
35
Salessforce.com E Editions Salesforce.com S m offers a number of bundless of its produccts and servicees, called “editiions”, that prrovide the sam me look and feel but differ by price, features and functio onality1. Within n each edition n companies can purchase different liceenses, which allows them to access diff fferent featurees on the platfform. These ed ditions and licenses become very importan nt when develloping applicaations as youu have to taake your pottential users’ edition and license types into consid deration beforee offering funcctionality. You may develop a great manageed package thaat fails when a customer insstalls it due to restriction r (ediition and/or liicenses) in theiir Org. W We can’t stresss how importaant it is to kno ow the featuress and restrictio ons of eeach Edition. Applications that you devvelop on onee Edition mayy not ffunction on another a Editio on due to a ffeature not en nabled or a sset of ggovernor limitss. Sales and Service C Cloud Edition ns Contaact Manager E Edition Contact C Managger (CME) is a starting pointt for many smaall business and d provides acccess to key CRM features such as accouunts, contactss, activities, caalendars, notes, attachments and reports. CME is cusstomizable to a point and is i designed to whet a user’ss appetite for more functio onality. Contacct managemen nt supports up to 5 users andd is priced at $55/user/month h. •
Store and m manage unlimited contacts
•
Track custo omer interactio ons via reportiing
•
Stay on top p of your day with w tasks and reminders
•
Works with h any email app plication
•
Integrated w with Google Apps A
•
Share docuuments using th he content librrary
•
Mobile access
Restrictions R incclude no accesss to Apex, Vissualforce, APII, sharing ruless, scheduled reports, workfllow, approval processes, asssignments, cusstom labels, an nalytic snapsh hots, marketingg user licensee (thus no cam mpaigns), prod ducts or priceb books, opportuunities, leads, forecasting, f account or salees teams, multiiple currencies,, custom profilles and develo opment sandbo oxes. Group p Edition Group G Edition n (GE) is tarrgeted toward ds small busin nesses and teaams of up to o five provid ding sales and support functiionality and is priced at $25//user/month. In addition to o what
1
edition ns
36
Salesforce Handbbook
is offered by CME, GE offers access to accounts, contacts, opportunities, cases, and reports with a number of restrictions. •
Store and manage unlimited contacts
•
Track customer interactions via reporting
•
Stay on top of your day with tasks and reminders
•
Works with any email application
•
Integrated with Google Apps
•
Share documents using the content library
•
Capture leads from your web site
•
Track sales opportunities
•
Pre-built dashboards and reports
•
Track Google AdWords performance
•
Mobile access
•
Phone support
•
Storage limits, 1GB of data and 1GB of file storage shared by all users
Restrictions include no access to Apex, Visualforce, API, sharing rules, scheduled reports, workflow automation, approval processes, assignments, custom labels, analytic snapshots, marketing user license (no access to campaigns), products or pricebooks, leads, forecasting, account or sales teams, multiple currencies, custom profiles and development sandboxes. Professional Edition Professional Edition (PE) is priced at $65/user/month and is designed for small- to midsized businesses that need more CRM functionality, security and personalization. PE is the first edition on the edition ladder where you can really start doings some development work. However some features are still missing and this will drive you crazy. •
Store and manage unlimited contacts
•
Sales forecasting
•
Marketing campaigns
•
Track sales opportunities
•
Service and support with cases, solutions & answers
•
User personalization and security
•
Mass email and templates
•
Share documents using the content library
•
Reports, dashboards and analytics Jeff Douglas & Wes Nolte
37
•
Customizable dashboards
•
Works with any email application
•
Capture leads from your web site
•
Integrated with Google Apps and AdWords
•
Phone support
•
Mobile access
•
Storage limits, 20MB of data and 600MB of file storage/user
Restrictions include no access to Apex, Visualforce, API (can be enabled for an additional charge), workflow automation, approval processes, products or pricebooks, account or sales teams, custom profiles, development sandboxes and can’t grant login access. Enterprise Edition Enterprise Edition (EE) is designed for large, complex businesses and provides access to virtually all platform functionality for $125/user/month. EE is the edition that provides the most benefit for customers and the one that saleforce.com tries to sell the most. Most developers and administrators will want to work with EE as it allows them to provide the most functionality for end-users. EE includes all PE features plus: •
Apex and Visualforce
•
API access
•
Access to development sandboxes
•
Products and pricebooks
•
Workflow and approvals
•
Sales territory management, account and sales teams
•
Storage limits, 20MB of data and 600MB of file storage/user
•
Offline access
Unlimited Edition Unlimited Edition (UE) is the flagship solution for salesforce.com and includes all EE functionality plus Premier Support, full mobile access, unlimited custom apps and increased storage limits for $250/user/month. It includes all Enterprise Edition features plus:
38
•
2000 database objects
•
24x7 Premier Support
•
Fully customizable mobile capabilities
•
Unlimited customizations and applications
•
Access to multiple development sandboxes Salesforce Handbook
•
Increased storage limits, 120MB of data and 600MB of file storage/user
Custom Cloud Editions You can build virtually any application on salesforce.com’s infrastructure even if it’s not a CRM application. Most traditional on-premise database applications are great candidates for conversion to the Custom Cloud. Like the Sales and Service Clouds, the Custom Cloud includes a highly scalable database, security, workflow, customizable UI, analytics, granular security and sharing, development sandboxes and development tools that empower you to build powerful business applications, Web sites and mobile applications. The major difference between the Sales and Service Clouds and the Custom Cloud is that the latter does not provide access to CRM objects such as cases, solutions, campaigns, leads, opportunities, products, contracts, and forecasts. Access to accounts and contacts is available to specific licenses in certain editions so check the documentation before selecting an edition. Force.com Free The Force.com Free Edition (FFE) allows you to build a single application for free for up to 100 users. •
Complete cloud platform
•
Secure and reliable cloud infrastructure
•
Up to 100 users
•
Up to 10 custom objects per user
•
Storage limits, 1GB of data and 1GB of file storage
•
1 Force.com Site with up to 250,000 page views per month
•
1 Developer sandbox
•
API access for integration with third-party applications
Force.com Enterprise The Force.com Enterprise Edition (FEE) is salesforce.com’s most popular Cloud edition as it includes many of the key features that large enterprises require to run their mission critical applications in the cloud. All for only $50/user/month. •
Complete cloud platform
•
Secure and reliable cloud infrastructure
•
Unlimited number of users
•
Up to 200 custom objects
•
Access to accounts and contacts
•
Up to 10 apps Jeff Douglas & Wes Nolte
39
•
Storage lim mits, 20MB of data d and 600M MB of file storaage/user
•
Up to 25 F Force.com Sitess with up to 5000,000 page vieews per month h
•
1 Developeer sandbox
•
API access for integration n with third-paarty application ns
•
Fully customizable mobille capabilities for f an addition nal fee
Force.com Unlimitted The T Force.com m Unlimited Edition E (FUE) offers virtuallly unlimited clloud computin ng for your entire companyy for $75/user/ /month. •
24x7 Premiier Support
•
Complete ccloud platform m
•
Secure and reliable cloud infrastructuree
•
Unlimited n number of useers
•
Up to 20000 custom objeccts
•
Access to aaccounts and contacts c
•
Unlimited aapps per user
•
Storage lim mits, 120MB off data and 600M MB of file storrage/user
•
Up to 25 F Force.com Sitess with up to 1,000,000 page vviews per mon nth
•
Multiple saandboxes devellopment, testin ng and trainingg
•
API access for integration n with third-paarty application ns
•
Fully customizable mobille capabilities
Develloper Edition The T Developerr Edition (DE E) environmen nt is where yo ou develop yo our application ns for free . You Y can have aas many DE Orgs O as you need for any type of purpose. You Y can sign uup for a new DE Org on th he home pagee of http://develloper.force.com an nd be up and running in a m matter of min nutes. If you arre testing conffig change imp pact, developin ng new Apex co ode or develop ping a packagged application n for distributtion, most of your y time will probably be spent s in a DE E Org. Additiionally, all man naged packagess (applications)) must be deveeloped in a DE E Org. 1
Y You cannot deeploy code to production p or sandbox envirronments from ma D DE Org using Change Sets. You Y will need to use the Forrce.com IDE, ccreate an unmaanaged packagge or move the code manuallyy.
1
develo oper-edition
40
Salesforce Handbbook
DE Orgs provide full access to Force.com platform features, as well as licenses for other salesforce.com products that allow you to play around and discover new functionality. A number of salesforce.com licenses are provided including: •
2 Salesforce licenses
•
3 Salesforce Platform licenses
•
2 Salesforce CRM licenses
•
2 Salesforce Mobile licenses
•
5 Salesforce Partner licenses
•
10 Customer Portal Manager licenses
DE Orgs also have special limits based upon the nature of the edition: •
20 MB of Data Storage
•
20 MB of File Storage
•
5000 API requests per rolling 24 hours
•
A 500 MB bandwidth and 10 minute service request time limits (per rolling 24 hours) for Force.com Sites applications
Salesforce.com License Types Within each edition you also have a number of different licenses that provide access to specific features and functionality1. You can view the licenses available to your company and purchase additional licenses by clicking Setup -> Administration Setup -> Company Profile -> Company Information.
Salesforce This is the most commonly purchased license and entitles users to full access to all standard CRM functionality, standard applications, custom applications and AppExchange apps. Salesforce Platform This license is for users who need to access custom or AppExchange apps but not standard CRM functionality. These users have access to core platform functionality such as accounts, contacts, custom tabs, reports, dashboards and documents but are restricted in other ways. They do not have access to opportunities or forecasts and are not entitled to some user permissions and standard apps. Salesforce Platform Light This license is for users who need to access custom or AppExchange apps but not standard CRM functionality. It essentially provides the same access rights as the Salesforce 1
licenses Jeff Douglas & Wes Nolte
41
Platform license however the amount of times the user can log in is limited monthly. Salesforce Platform Light users cannot edit or create new dashboards and can only view them if the dashboard’s Running User also has a salesforce.com Platform Light license. Force.com – One App This license is for users who need access to a single custom application but not standard CRM functionality. These users have the same rights as Salesforce Platform users (plus unlimited number of custom tabs) but are limited to a single custom application consisting of up to 10 custom objects and have only read-only access to accounts and contacts. Force.com – Free This license is for users who need access to a single custom application but not standard CRM functionality. Essentially the same rights as Force.com – One App users but they do not have access to accounts and contacts. Knowledge Only User This license is for users who only need access to Salesforce Knowledge and allows them to access the following tabs: Articles, Article Management, Home, Reports, and custom tabs. The license also includes a profile that grants access to the Articles tab via the “View Articles” user permission. A user’s profile must also include the “Manage Articles” permission to view and use the Article Management tab. Content Only User This license is for users who only need access to Salesforce CRM Content and allows them to access the following tabs: Workspaces, Content, Subscriptions, Ideas and Home. Ideas and Answers Internal User This license is for internal salesforce.com users who only require access to the Answers and Ideas features. The license allows users to access the Home tab, Answers tab, Ideas tab and up to three other custom tabs. Guest User This is essentially a license for a Force.com Site which allows you to create one active Force.com Site for each Guest User license in your Org. Site visitors have access to any information made available in an active public site but can be restricted by object and read/write privileges. Your edition determines the number of Guest User licenses and you cannot purchase additional licenses. Customer Portal Manager Standard This license is for Contacts that access your customer support information by logging into your Customer Portal. These users can view and edit data owned by them or users below them in the Customer Portal role hierarchy. They also have the ability to view and edit cases in which 42
Salesforce Handbook
theey are involvedd, access custo om objects bassed upon their profile and reeceive the “Porrtal Super Usser” permission n. Cu ustomer Portaal Manager Custom C An extensio on of the Custom Portal Maanager Standarrd license, thiss license also aallows the useer to run rep ports based their t profile settings s plus rreceive the “Delegated Po ortal User Ad dministrator” p permission. Partner po ortal users can n also have th he following two user liceenses entitling them to additional features: •
Silverr Partner - This T license en ntitles the userr to access Saalesforce CRM M Content (basedd up feature license and profile), p 2 MB B of data storrage and acceess to the docum ments tab, app provals and Myy Account Proffile.
•
Gold Partner - Th his license enttitles the userr to access Salesforce CRM M Content (basedd up feature liicense and pro ofile), 5 MB off data storage and access to accounts, leads, opportunities, cases, custtom objects, documents taab, approvals and My Accouunt Profile.
Hiigh Volume C Customer Porrtal User This licensee is designed for f contacts wh ho need access to customer support information in your Org. Thesee users don’t have h roles, don n’t appear in th he role hierarcchy and can on nly access specific records based upon specific criteriia. These userrs can access accounts, asseets, cases, contacts, custom m objects, docuuments, ideas, and a questions depending on their profile settings. Ch hatter Only Salesforce.ccom recently announced a a Chatter C license for users who o typically do n not access Sallesforce CRM M but need to t collaboratee with other users via Chatter. C The llicense is $15/user/month h and allows th he user to acceess profiles, sttatus updates, people directo ories, realtim me feeds, file sharing/conttent, groups, ideas, contactts, accounts, dashboards, rreports, 1 custom app and up to 10 custo om objects. Be careful when purchassing salesforcee.com licenses on a budget. You may be tempted d to save mon ney by choosin ng a “cheaper” license but down the road you may discover that your users do not have h access to o required features.
Sttandard Saleesforce.com m Applicatio ons In addition n to core CRM M functionalityy, salesforce.co om has develo oped a large n number of staandard applicattions that you can utilize bassed upon your license.
Jeff Do ouglas & Wes No olte
43
Salesforce CRM Content Salesforce CRM Content allows you to organize, share, search, and manage content within your Org and make it accessible in various parts of salesforce.com1. Content can include virtually all file types including Microsoft Office, video, audio, web and Google docs. Content allows you to organize content by setting up searchable, virtual workspaces that are public or private. Documents can be previewed inline without needing to be downloaded to view. In addition to each user’s personal workspace, users can create multiple shared workspaces and define access to the workspaces and their content. Content authors can tag content documents for searching or additional classification. salesforce.com utilizes a powerful content search engine that scans the entire body of the document as well as content properties such as the title, description, tags, categorization data, and author name. Users can subscribe to a document ensuring that they receive notification when new versions are published or other changes are made. Salesforce CRM Content is also available in the Customer and Partner Portals as well as through Salesforce Mobile. Chatter With Chatter users can collaborate with people inside your Org in real time in a completely secure manner with a familiar “Facebook-like” user interface2. Users can follow people, documents and data to have access to real-time information that is important to them. Users can set up groups and profiles to promote collaboration across multiple business applications while making sure people only see information that they have access to based the Org-wide security and sharing model. You can even extend Chatter to external applications (e.g., Basecamp, Workday, SAP, Google Docs) to allow them to send updates about your employees, customers or projects. Salesforce Knowledge A powerful, fully integrated knowledge base allowing companies to deliver relevant answers to customer inquiries enabling better customer service3. This application delivers knowledge across your call center, website, portals, Google search results and social communities. You can categories and organize information and quickly search for relevant articles that are filtered based upon what you know about the customer, attach the docs to cases or other records and even email the article. Entitlements & Service Contracts This is a niche app that allows you to track and manage your service commitments to customers4. For support agents they can view the level of support that customers are entitled to and track the status with milestones and support cases to verify SLA commitment. You can use service contracts to up sell customers and generate support revenue. crm-content chatter 3 salesforce-knowledge 4 entitlements 1 2
44
Salesforce Handbook
Saalesforce Ideaas This comm munity applicattion allows useers to post ideaas and vote an nd comments o on them1. Ideeas can be orgganized into categories (e.g., New Producct Developmen nt, Peripheralss, Gloves) and sub-groups allowing userss to filter and d drill into whaat interests them. You can use Ideas intternally within your Org or make m it availablle externally viia the customeer portal. Salesforce.com uses Ideaas to develop new ideas forr future releasses. Users can vote id deas up or dow wn to let Produuct Managers know k which feeatures are important to them. Salesforce.com aactively uses these t new ideeas when determinin ng new featuress to include in future releasess. Saalesforce Answ wers Answers in n another com mmunity appllication that aallows membeers help one another2. Sim milar to a messsage board, users u ask questions, commuunity experts (o other commun nity users and customer seervice agents) provide answeers, the comm munity votes on n the best ansswers and thee best knowledge in the com mmunity bubb bles up to thee top. Compan nies can sharp ply reduce sup pport costs byy tapping into the power of their t commun nities resulting in faster answers, fewer inb bound calls and happier custtomers. Saalesforce Mob bile Salesforce M Mobile is a feature that enables users to aaccess their saalesforce.com ddata from theeir iPhone, Blaackberry, Palm m Treo and Win ndows mobile devices. The Salesforce S Mobile client application exchanges data witth salesforce.co om over wireleess carrier netw works, and storres a local copy of the userr’s data in its own o database on o the mobile device. Users can edit local copies of theeir salesforce.ccom records when w a wireleess connection n is unavailab ble, and transm mit those changes when th he connection n becomes avaailable. Admin nistrators can create multiplle mobile configurations ddetermining thee types of dataa that can be acccessed. A sep parate Salesforcce Mobile license is requireed for each useers running thee client. For P Professional, Enterprise, Unliimited, or Deeveloper Editiion users with hout mobile liicenses, salesfo force.com offeers Mobile Litte, a free, resstricted version n of Salesforcee Mobile. Cu ustomer Portaal The Custom mer Portal allo ows you to deliiver a personallized, service application a to yyour most 3 im mportant custom mers . The Cuustomer Portall consists of fu functionality siimilar to salesfforce.com and is one of th heir most useed and custom mizable offerin ngs. Many oth her application ns use the customer portal in the backgro ound for autheentication (e.gg., Force.com Sites, S Ideas) so o don’t be surrprised if you see it poppin ng up from tim me to time. F Functionality of o the Custom mer Portal inccludes but is not limited to th he following:
id deas an nswers 3 cu ustomer-portal 1 2
Jeff Do ouglas & Wes No olte
45
•
Self-service functionality with case management, Salesforce Knowledge, Solutions and Answers
•
Allow users to run customizable reports
•
Provide access to documents and Salesforce CRM Content
•
Access to a knowledge base for customers using Salesforce Knowledge
•
Ability for customers to participate in Salesforce Ideas communities
•
Expose access to custom objects to display and collect information for custom applications
•
Ability to create profiles with customizable page layouts, list views and field-level security
•
Manage users with profiles, roles, and sharing rules
•
Enable access via single sign-on
•
Tweak the look and feel by changing colors and logos and customizing tabs and their order
•
Customize communication templates
Partner Portal The Partner Portal allows companies to empower their indirect sales channels to sell more thus maximize channel ROI1. With a secure, partner-only website, companies can provide their sales partners with personalized access to salesforce.com data. With partner relationship management (PRM), companies can create multiple portals to manage, track, and forecast their channel business alongside their direct sales business thus fostering closer relationships with partners that translate into higher profits. Channel managers utilize Partner accounts to manage partner companies, user and activities. Partner Portal users have limited access to salesforce.com based upon the particular license they are assigned - Silver (Standard) or Gold (Strategic). Depending on the type of license, users may have access to:
1
•
Collaborate on sales opportunities with tasks and activities
•
Provide self-service functionality with case management, Salesforce Knowledge (view and rate), Solutions and Answers
•
Allow users to run customizable reports
•
Provide access to documents and Salesforce CRM Content (read-only)
•
Access to a knowledge base for customers using Salesforce Knowledge
•
Allow customers to participate in Salesforce Ideas communities
partner-portal
46
Salesforce Handbook
•
Expose access to custom objects to display and collect information for custom applications
•
Ability to create profiles with customizable page layouts, list views, sharing rules, user roles, role hierarchy and field-level security
•
Enable access via single sign-on
•
Brand the look and feel by changing colors, fonts, logos and customizing tabs and their order
•
Customize communication templates
•
Assign a salesforce.com user as the portal administrator
Salesforce to Salesforce Salesforce to Salesforce is a feature that allows you to share data with another salesforce.com Org1. So if a business partner is also using salesforce.com you can create connections that allow you to publish and subscribe to each other’s objects and fields for virtually any type of record (e.g., lead, accounts, opportunities, custom objects) in one another’s Org. Force.com Sites Using Force.com Sites you can build and serve public websites and applications directly from the Force.com platform2. Force.com Sites are built using Apex and Visualforce but can also include simple HTML markup, JavaScript, CSS and Flash to create a visually compelling user experience. You can even run your Force.com Site from your own domain name if you’d like. You can create a corporate website or intranet, ecommerce applications or simple microsites for an existing website that dynamically exposes data from your salesforce.com Org. Force.com Sites is enabled for most editions but there are bandwidth and usage restrictions. Sites applications run as their own special public user with public access settings which controls which database objects and fields your visitors can see. You can even allow your visitors to authenticate with their customer or partner portal credentials.
Standard Objects Salesforce.com comes with a number of standard objects that you can use as soon as your Org is setup. They comprise the core functionality of the platform and most are customizable to some extent. Account Since salesforce.com is by definition a CRM application, the account object is the heart and soul of virtually all processes in some way. Almost every object in salesforce.com is related to the account object in some way, by some relationship. Accounts represent your company’s 1 2
salesforce2salesforce sites Jeff Douglas & Wes Nolte
47
customers, competitors and other business partners that you interact with. Each account record stores information such as name, address and phone numbers along with related information for contacts, opportunities, cases, activities, partners, contracts and notes. You can create accounts specific to companies, people and/or partners depending on enabled features. Accounts can be related to one another to create an “Account Hierarchy” to represent companies with different corporate structures (e.g., subsidiaries, divisions) and/or sales territories. Territory management is an account sharing system that allows users access to accounts based on some characteristics of the accounts (e.g., zip code, industry, revenue, or a custom field). It enables your company to structure and forecast your salesforce.com data and users the same way you structure your sales territories. Your company can also enable multiple users (e.g., executive sponsor, account executive, support representative) to work together on an account. You can build an account team of users by role and specify the level of access each account team member will have to the account and any contacts, opportunities, or cases associated with that account. Person Account Out of the box (so to speak), salesforce.com is a B2B product. But what if your company provides home healthcare services or lawn care services or any other type of service for individual consumers? Salesforce.com can be tweaked for this scenario by using “Person Accounts”. By default, person accounts are not enabled. You’ll need to call support to have them enabled and they will repeatedly ask you if you really want to do this and if you understand the consequences. Once enabled, person accounts cannot be disabled. We recommend you setup a DE Org first and test out your solution there before enabling your production Org. So what actually happens when you enable person accounts and what are the consequences? In most situations, you can use person accounts as if they were contacts. You can include them in all contact list views (except the Recent Contacts list on the contacts home page), configure their own page layouts and field level security and use them in portals. When person accounts are enabled, a number of person-related info fields are created in the account object. So when you create a new person account record, salesforce.com creates not only an account record but also a contact record in the background. You cannot access the account record directly (it always relocates you back to the person account record) but it is needed for the functionality that requires a contact (emails, customer portal, etc.). Person accounts have some restrictions so you’ll want to see the documentation. Contact Contacts represent the individuals associated with an account that you need to track in salesforce.com. You can store various information for a contact including title, phone numbers, email addresses, physical addresses, titles and custom information that’s important to your company. When contacts are added to an account, case, contract or opportunity they can be assigned a role that they play in that record. These roles are customizable for your Org.
48
Salesforce Handbook
Contacts th hat are not lin nked to an account are alwayys private, regaardless of your Orgg’s sharing model. m Only the owner of the con ntact and administrattors can view it. i Sharing rulees and workflo ow rules do no ot apply to private con ntacts. Leead Leads are ssimply prospecctive customers that you are trying to sell to. Leads can b be entered maanually, imporrted or captureed from a Web b-to-Lead form m on your com mpany’s websiite. Leads aree very generic in nature and contain both company c and ccontact inform mation. When n new leads aree created you can automaticcally assign th hem to sales p people with leead assignmentt rules or plaace them in a queue to manage distributiion. Your salees team will work w these leads and at som me point in the sales proccess “convert”” them by crreating a new account, con ntact and, op ptionally, an op pportunity. Ad dministrators can configure ffield mappings which determ mines how thee data from th he lead is used to create the new n account, ccontact and op pportunity. All open and clo osed activities ffrom the lead are attached to o the account, contact, and opportunity. o Once leads are a converted they t can no lon nger be viewed d directly but ddo appear in lead reports. The lead objject contains IsConverted, C ConvertedDatee, ConvertedA AccountId, ConvertedCo ontactId and ConvertedOpp C portunityId fieelds. You can query for converted reecords and dettermine what accounts, con ntacts and opp portunities were created during the con nversion proceess. Caampaign Campaignss are outboun nd marketing projects p (e.g., direct mail program, p semin nar, print advvertisement, eemail) that youu want to plaan, manage, an nd track within salesforce.co om. Both leaads and contaccts can be addeed to campaign ns. You can orrganize campaiigns into hieraarchies for eassy analysis of rrelated marketting tactics. Alll campaigns arre executed ouutside of salesfforce.com buut you can trackk their responsse and analyze their influence on new busin ness. Opportuunities can be configured to o either manuually or autom matically associate multiple in nfluential cam mpaigns to determine what m marketing effo orts impacted sales. s Op pportunity Opportunitties are past or o pending salles for an account that youu want to worrk and/or traack. By using o opportunities you y are, in a sense, s buildingg your “pipelin ne” and enablin ng you to perform sales fforecasting. Opportunities O are one of the most wid dely used andd heavily customized objeects on the plaatform. Opporrtunities allow you to track the individual products (op pportunity linee items) that you y are selling on the deal, m multiple quotess, any partnerss involved and competitor aand their products that you are a competing against.
Jeff Do ouglas & Wes No olte
49
For F team sellin ng, opportunityy owners can set up sales teeams of users assigned to sp pecific roles (e.g., ( account eexecutive, pre--sales consultan nt) with speciffic access priviileges. You can n also split op pportunities to o give credit to o multiple mem mbers of the teeam. Forecasting F is a way to estim mate quarterly revenue from your opportuunities. The forecast amoun nt is based up pon your pipelline and is thee total amoun nt of all “Com mmit” opportuunities divided d by the total aamount of all “Best Case” opportunities. F For a more graanular view, yo ou can setup customizable forecasting to reflect ho ow your com mpany forecassts its sales. With custom mizable forecasting, you can forecast on a monthly or qquarterly basis,, use different dates when applying amouunts to forecassts, forecast baased on revenuue or quantity or both, and ddefine additio onal quotas based on producct families. Quotee A quote is a fo ormal proposall for products and services tthat you are offfering for a sp pecific opporttunity. Opporrtunities can contain multiiple quotes an nd quotes aree created from an opporttunity and its p products. Wheen a quote and d an opportun nity are synced, any change tto line items on the opporttunity will syn nc with produccts on the quo ote, and vice versa. v You can n also create templates thatt allow you to email completted quotes as P PDFs to prospects. Produ uct and Price Book Products P are th he actual itemss that you sell on your opporrtunities and quotes. q Produccts are associaated to one o or more price books to creeate price boo ok entries. Pro oducts can exxist in multip ple price bookks with manyy different prrices. For exaample, you may m have a “N North Ameriican” price boo ok with one seet of prices fo or your produccts and a “Souuth American” price book with a differeent set of priices. You can n also create default revenuue and/or quuantity scheduules for produucts or opporrtunity line iteems to determ mine how defaault unit pricees are handleed. You Y can use th he standard price p book thaat comes with salesforce.com m or create cuustom price books. b The staandard price book b is automatically generaated to contain n a master list of all produccts and standaard prices reggardless of thee custom pricce books that also contain them. When you add produucts to your op pportunities orr quotes, you ffirst have to seelect the price b book. W When importin ng products yo ou must also iimport price book b entries. IIf you aare using custtom price bo ooks, you must also add the t product to o the sstandard price book in additiion to the custtom price bookk. Case Cases C are the ffoundation of the Service Clloud and are uused to track customer c issuees and inquiriies. Cases are ttypically used to track and manage m custom mer feedback, issues or quesstions. Cases can be createed by support representativees, from web forms on youur website (weeb-tocase), by customers themselves from fr the Custo omer Portal o or directly from m emails (emaail-tocase). New cases caan be assigned directly to suupport agents, case teams orr case queues using assignm ment rules. Cases allow youu to interact with w customerr easily by sen nding and receeiving 50
Salesforce Handbbook
email in one centralized location, replying with knowledge articles or solutions and managing entitlements more efficiently.
Custom Objects Custom objects allow you to store information that is unique and important to your company. Custom objects are often used as building blocks for custom applications. For instance, you could create a Shipment custom object that tracks your product shipments or a Part custom object to track individual repair parts. Administrators define the custom object and its properties, such as custom fields, relationships to other types of data, page layouts, and access rights to fields and records. Custom object look and function for the most part just like standard objects and have similar functionality (e.g., store records, searchable, reportable). Custom objects allow you to extend the Force.com platform with a simple, point-n-click interface.
Types of Orgs Salesforce.com offers different types of Orgs for different purposes. Not all types of Orgs are available to all companies and may require an additional fee. Production Org Your production Org is where most users will perform their daily activities. Users can log into the production Org at https://login.salesforce.com. All usernames must be unique across all production Orgs. Sandbox Org You can create multiple copies of your production Org for development, configuration, testing and/or training without affecting your production configuration and data. The edition that your company purchased may be entitled to sandboxes or you can purchase additional sandboxes. Users can log into sandbox Orgs at https://test.salesforce.com. Professional, Group, or Personal Orgs do not have access to sandboxes. Full copy sandboxes can be refreshed from your production Org every 29 days while developer and configuration-only sandboxes can be refresh from production daily. Full Copy Sandbox Full sandboxes are essentially an exact replica of your production Org and all of its data, including standard and custom object records, documents, and attachments. Configuration-Only Sandbox Configuration-only sandboxes copy all of your production Org’s reports, dashboards, price books, products, apps, and customizations under Setup, but exclude all of your Org’s standard and custom object records, documents, and attachments. It’s essentially a copy of your production environment without your data. Config sandboxes can only include up to 500 MB of data. Jeff Douglas & Wes Nolte
51
Developer Sandbox Developer sandboxes are special configuration-only sandboxes intended for coding and testing by a single developer. They provide an environment in which changes under active development can be isolated until they are ready to be shared. Just like configuration-only sandboxes, developer sandboxes copy all application and configuration information to the sandbox but not the data. Developer Sandboxes are limited to 10 MB of data. Developer Org A developer Org is a free, non-expiring copy of an Enterprise Edition environment that you can use to instantly start developing, testing and deploying your applications. Developer Orgs are equipped with everything you need to get started including Apex, Visualforce, Web services API, Sites, pre-installed applications (Sales, Marketing, Ideas, Customer Portal, etc), licenses for numerous salesforce.com products (CRM, Mobile, Partner, etc.) and much, much more. Only Developer and Partner Developer Orgs can be used to create managed packages for distribution. You can sign up for as many Developer Orgs as you need by going to http://developer.force.com and clicking on the Get a Free Developer Edition link. Users can log into Developer Orgs at https://login.salesforce.com. Partner Developer Org This is a free Developer Org with more storage, features and licenses for companies enrolled in the partner program. Pre-release Org A pre-release Org is a limited time Org that allows you to test new features or functionality typically associated with a pilot program or an upcoming release. These are special cases and you will most likely need to signup for these Orgs or contact salesforce.com support. Users can log into pre-release Orgs at: https://prerellogin.pre.salesforce.com.
52
Salesforce Handbook
Where Should You Develop? Developer Sandbox Type
Config-Only Sandbox Essentially a copy of your production Org without data.
Testing
Configuration-only sandbox intended for development by a single developer. Best used for developing extension app. Daily refresh. Unit and Apex
Staging
Not well suited
Applicable if using subset of production data.
Integration Testing
Not well suited
Special case testing with sample or subset of data.
Development
Best used for general dev with sample data. Daily refresh. Feature and regression testing with sample data
Full Copy Sandbox
Developer Edition
Exact replica of your production Org including config and data. Slower to copy from production every 29 days. Best used for production debugging and testing. Best used for validation with production data and config. Best used for integrating full data sets from production and external systems.
Free, separate development instance. Best used for standalone app dev. Small scale, ad-hoc application testing.
Not well suited
Not well suited
Jeff Douglas & Wes Nolte
53
Getting G Sttarted witth Salesfo orce.com m
N
ow that yo ou have a good d understandin ng of what saleesforce.com iss and what thee platform consists off, let’s really dig d into it. In this chapter we’ll discuss the major feaatures and benefits of usingg the Force.co om platform as a well as som me of the majo or design consiiderations thaat must take pllace in a multittenant environ nment.
Managing M Ussers Every userr that has acceess to the plattform is identiified by a userrname, passwo ord and a sin ngle profile. Y You can acceess the list off all users in your Org by clicking Se etup -> Ad dministrati ion Setup -> Manage Users -> Users. Thee user record maintains no ot only personaal information n such as phon ne number andd manager butt platform setttings such as time zone, em mail encoding,, approval setttings and mob bile configurattions1. Users ccannot be deleted once theey are created but can be deeactivated. Youu can change a user’s usernaame once creeated as long aas it remains un nique. Salesforce.com usernam mes must be unique acrosss all producction and sandboxes environmentss. For instancee, two producction Orgs can nnot have the same username
[email protected], but it can exist iin both a production n and a sandbo ox Org. Users can grant login permission fo for administrators so that they can impersonatte users and trroubleshoot ap pplication issuees, security setttings and record acceess easier. Useers must go to Setup -> Personal P Se etup -> My Perso onal Information -> Grant Logi in Access and enter an expiratio on date to gran nt login accesss. Prrofiles Profiles typ pically model a user’s job fun nction (e.g., saales manager, marketing m assisstant) and 2 useers can only b be assigned to o a single proffile . A profilee defines the objects that a user can acccess as well ass the settings and a permission ns for variouss functions on the platform.. You can acccess profiles b by clicking Set tup -> Admi inistration Setup -> > Manage Us sers -> Pr rofiles.
Each profiile is assigned a specific license that provvides access to t specific feaatures and fun nctionality. M Many of the more m granular settings for th he platform (e.g., ( Schedule Reports, Im mport Leads, V View Setup an nd Configurattion) and con nfigured at thee profile levell. Profiles determine: 1 2
users prrofiles
•
CRUD peermissions perr object determ mining the userr’s ability to crreate, read, ediit, and delete reccords
•
Which staandard apps, custom apps an nd tabs the useer can view
•
The speciific page layout the user sees per object
•
The fieldd-level securityy settings that determine th he user’s abilitty to view andd edit specific fiields for each object o
•
Record tyypes available per p object to th he user
•
Login resstrictions such as specific login hours andd from which IP addresses a user can login from
•
Admin an nd general userr permissions for f managing tthe Org and ap pps within it
•
The Apexx classes that a user is authorrized to executte
•
The Visuaalforce pages a user is alloweed to access SSalesforce.com m includes a nuumber of standdard profiles in n every Org. As only ccertain settingss can be changged on standard profiles, it iss highly recom mmend tthat you clone standard profi files before usin ng them.
Roles Used U in combiination with yo our sharing seettings, roles co ontrol the actuual records thaat can be view wed by users1. Users at any given g role levell can view, editt, and report on o all data own ned by or sharred with users below them in n the hierarchyy, unless your Org’s sharing model for an o object specifiies otherwise. For example, if your role hiierarchy contaains a “VP Salees, North America” and a “VP Sales, E Europe” role with w additionall roles undern neath (e.g., Ch hannel Sales, D Direct Sales, Government) then all record ds owned by users u under thee VP Sales roles will be acceessible to the users assignedd to the VP Sales S roles. Ho owever, users w will not be ablle to access reecords d by other userrs above them in the role hieerarchy. This eensures that bo osses have access to owned all reco ords owned byy their subordiinates and som me that are privvate to them. All A users that reequire visibiliity to the entiree Org should belong b to the highest h level in n the hierarchyy. The T role hierarrchy is not neccessarily your org chart but it may be simiilar. You can aaccess your Org’s O roles by clicking Setup -> Admin nistration Setup -> Manage M User rs > Rol les. It is nott necessary to create individ dual roles for eeach title at yo our company, rrather each role in the hierrarchy should represent a levvel of data acccess that a useer or group off users needs. A role is option nal but it is a best b practice to o assign each user u one. Everyy user sshould be assiigned to a rolee, or their datta will not disp play in opporrtunity rreports, forecast roll-ups, and d other displayys based on rolles.
1
roles
56
Salesforce Handbbook
Groups Groups are sets of users that can contain individual users, other groups, the users in a particular role or territory, or the users in a particular role or territory plus all of the users below that role or territory in the hierarchy1. Groups can be either public (created by administrators but accessible by everyone in your Org) or private (created by users for their own personal use). Groups are typically used for defining sharing rules, manual record sharing and configuring access to Salesforce CRM Content workspaces and actions in Salesforce Knowledge.
Securing and Sharing Data One of the first tasks when setting up a new Org is to define the sharing model2. This is a balancing act between restricting data, thereby limiting risk of stolen or misused data, and providing access to data so that users can do their jobs effectively. The choices you make with the sharing model will drive a number of decisions for viewing data, access to specific fields, reporting and analytics down the road. With all of the permutations of Org-wide defaults, sharing rules, overrides and profile access, this is arguably the most complex topic in salesforce.com to wrap your head around. Object-Level Security Profile-based or object-level security provides the broadest way to control access to data in salesforce.com. By configuring a user’s profile, you can prevent them from seeing, creating, editing, or deleting any instance of a particular type of object. Object-level security allows you to hide entire tabs and objects from particular users, so that they do not even know that type of data exists. Field-Level Security Field-level security is configured again from a user’s profile and controls whether a user can see, edit, and delete the value for a particular field on an object. For instance, for an Administrative Assistant profile, you may want to remove access to payroll and social security information for obvious reasons. A common mistake when restricting access is to simply remove a field from a user’s page layout. This method only controls the visibility of the field on detail and edit pages for the object. To be absolutely certain that a user does not have access to a specific field, you must lock down the field with field-level security. This removes all access to the field for the API, related lists, list views, reports and other parts of platform. Record-Level Security After setting profile access to objects and individual fields, you’ll need to determine your Org’s level of record-level security. For instance, you may want everyone in your Org to be able to view all Accounts but restrict Lead records so that Sales Reps can only see Leads they own. The first step is to lock down object access to the most restrictive level using Org-wide defaults. 1 2
groups security-data Jeff Douglas & Wes Nolte
57
You caan then use ro ole hierarchies,, sharing rules,, and manual ssharing to opeen up the recorrds to other users u who need to access. Org-wide O defauults specify th he default levell of access to records and caan be set sepaarately for mo ost standard an nd all custom objects. Organization-wide sharing settinggs can be set tto the follow wing: •
Public R Read/Write - All A users can view, v edit, and rreport on all reecords.
•
Public R Read Only - Only O the ownerr and users abo ove them in th he role hierarch hy can edit recorrds. All other users u can only view v and repo ort on records.
•
Private - Only the own ner and users above a them in n the role hieraarchy can view w, edit and reporrt on records.
•
Controlleed by Parent - A user can only o view, editt and report on a detail reco ords if they havee access to thee associated paarent record. F For example, a user can onlyy view Activities for a Contact if they access to that Contacct record.
•
Public R Read/Write/T Transfer - App plicable for Leeads and Casess only. All userrs can view, editt, transfer own nership, and rep port on all reco ords.
•
Full Acccess - Applicaable for camp paigns only. U Users can view w, edit, deletee, and transfer o ownership of records. r Users can share reccords with oth her users but cannot grant them m Full Access.. A Administratorss and users with w the View w All Data a or Modify All D Data profile permissions checked c have full access to o all records o of the sselected objectt type, regardleess of the shariing settings forr the object.
Figure 2 - 1. Org-wide defaults d decision n model.
After A you havee defined the Org-wide O defaults, you can sspecify whetheer users have aaccess to datta owned by or shared witth their suborrdinates in th he hierarchy. Similar S to, buut not necesssarily an Org ch hart, a role hieerarchy represeents the level o of data access that t a user or ggroup of useers have. Thee role hierarcchy ensures that t a superviisor always has h access to their subord dinate’s recordds regardless off the Org-widee default settin ngs. In addition n to role hierarrchies, 58
Salesforce Handbbook
you can also implement territory hierarchies as an account sharing system that grants access to accounts based on the characteristics of the accounts. Sharing rules allow you to make automatic exceptions to your Org-wide defaults based upon some criteria to give access to specific groups of user for records that they do not own. For example, if you have a Private sharing model for Leads you could create a sharing rule that shares all Leads owned by the “North American” sales group with all users in the “North American” legal group. Sharing rules are the most effective when they are defined for a particular set of pre-defined users (e.g., public or personal group, a role, a territory, or a queue). Just like roles hierarchies, sharing rules are used to open up record access to users, and can never be more restrictive than your Org-wide defaults. For dynamic or frequently changing sets of users, programmatic Apex sharing rules may be a viable alternative. Apex managed sharing allows developers to write Apex code to programmatically share objects based upon some criteria. However, if sharing rules or Apex managed sharing does not fit the bill, record owners can use manual sharing to give read and edit permissions to users who would not have access to the record any other way. For records where sharing is an option, users will see a “Sharing” button on the record detail screen. They can then manually share the record with individual users or group of users. You can also provide record access to multiple users by using queues and teams. Queues are available for leads, cases, and custom objects. Once records are assigned to a queue (the queue is the actual record owner), they remain in the queue until they are assigned to a user or “accepted” by one of the members of the queue. Any queue member or users above them in the role hierarchy have access to the records in the queue and can take ownership of them. For accounts, opportunities, and cases, record owners can define teams of users to grant access to their records. A team is a configurable group of users that work on an account, opportunity or support case. When configuring a team, the record owner can define a role (e.g., Support Rep, Sales Engineer) and the level of access (e.g., read/write, read-only) to the record.
Jeff Douglas & Wes Nolte
59
2 Security and sharing s examplee by object. Figure 2 - 2.
Field Accessibility Since S access to o fields can be a confusing combination c o of page layoutss, field-level seecurity and prrofile permissions, salesforcee.com has a haandy little secttion called Field Accessibilitty that allows you to view field access by b profile or field f for a parrticular object.. You can findd this section n by clicking S Setup -> Ad dministrat tion Setup -> Securit ty Controls s -> Field d Accessib bility. You u can choose a field and vview its accesssibility by diff fferent profilees and record ttypes. You can n also choose profile and viiew field accessibility for diff fferent record d types.
60
Salesforce Handbbook
Figuree 2 - 3. Account field f accessibilitty for a particulaar field, profile, or record type.
You can th hen click a fielld to modify th he accessibilityy for that field d based upon field level seccurity and/or p page layout.
Jeff Do ouglas & Wes No olte
61
Figure 2 - 4.. Modify the fielld access setting gs for field-level security and paage layouts.
Recorrd Types Record R types aare an extremeely powerful feeature of salesfforce.com thatt allow you to offer differeent business prrocesses, segm ment data and personalize th he UI based on o user profiles1. By defaultt, objects do n not use record types. Once yo ou add a recorrd type for an object, o the plaatform will ad dd a new field called RecordT TypeId to the object. You ccan determine which profiless have access to individual record types and display different d page layouts to useers based upo on the record d’s record type.. You can also determine thee picklist valuees that are availlable for the picklist fields on o the object ffor a specific record type. When W a user crreates a new reecord they willl be presented with a picklistt of available rrecord types for f the objectt and will be required r to choose the type of record theey are creatingg. The platforrm will automaatically display the page layouut based upon their profile. For F example, a use case for record types may m be a comp pany that repaairs equipmentt. The compaany repairs two o types of equuipment, gasolline and diesell engines, so they t create a rrecord type fo or each one. W When employeees create a new w record they sselect the typee of engine (gasoline or diesel) and enter data about th he engine baseed upon the rrecord type. For F gasoline en ngines 1
record d-types
62
Salesforce Handbbook
theere may be a fi field that allows the user to en nter the date tthe engine was last serviced, while this fieeld does not ddisplay for diessel engines. Th here may also o be a field for the user to select the oriigin of the equuipment. For gasoline g enginees the picklist values may bee “North Ameerica” and “South America”” while for dieesel engines th hey may be “North America””, “South Ameerica” and “E Europe” (they o only sell diesell engines in Euurope). When a useer views a piecce of equipmen nt in the UI, tthe platform will w automaticallly display thee correct page layout for thee user’s profilee based upon tthe record typee of the recordd. Record typ pes are extrem mely useful in th hat you can crreate views, rep ports, workflo ow or Apex trigggers that seggment or operrate only on specific record tyypes. For users tthat typically use u only a singlle record type you can set a default recordd type for eacch object thuus allowing theem to skip th he record type select proceess when creaating new reccords. Again, p profiles can bee assigned acceess to specific record types, which does not impact seccurity in any w way. Users can n still view reccords irrespecttive of record types (based upon the shaaring model o of course) and d even change the record tyype to any avaailable record ttype. The reccord type limittation imposed d by profiles is only enforcedd when a record d is created.
Au utomate Bu usiness Proccesses with Workflow Workflow iis one of the most m widely used and loved ffeatures of saleesforce.com1. W Workflow givves you the abiility to automaate and enforcee key business processes with hout the need to write a sin ngle line of codde. our business reequirement caan be met You should always checck to see if yo using workkflow before writing w Apex co ode. All workflo ow rules are acccessible by cliicking Setup -> App Se etup -> Cre eate -> Wo orkflow & Approvals -> Workfl low Rules. Workflow ru ules are configgured per ob bject, fire basedd upon changges to record values, v filter reecords based upon u some typ pe of rule criiteria and then performs some s sort of action immeddiately or at a point in th he future. Workflow rules ccan be configuured to fire: •
When n a record is crreated, or when n a record is edited and did not n previouslyy meet the rule criteria
•
Only when a record d is created
•
d is created or edited e Everyy time a record
Records prrocessed by wo orkflow rules must m also meeet a rule criteriion. You can cchoose to n the rule if a certain criteriaa is met (i.e., Sttatus equals “R Rejected”) or a formula that you write run evaluates to true (i.e., OwnerId d LastMod difiedById).
1
workflow w Jeff Do ouglas & Wes No olte
63
Figure 2 - 5. The name, description, and d criteria to trig gger your workflo ow rule.
One O of the m most agonizing decisions youu make when creating a new w workflow rrule is determ mining when th he workflow rule r should firre. If you wantt the workflow w to fire only when the record is created then choosee (obviously) the Only wh hen a reco ord is created optio on. If you w want a rule to fire each timee a record is created and updated u (repeaatedly) regard dless of the ruule criteria, then choose Ev very time a record is created d or edite ed. The only caveat with this t option is that you cann not add time--dependent acctions. Perhap ps the most w widely used op ption is When n a record d is create ed, or whe en a recor rd is edit ted and di id not pre eviously m meet the rule r crite eria.
Choosse this option to include new w records and updates to exiisting records, unless the rulle just ran an nd still meets th he rule criteriaa. The rule is not n re-triggereed on edits thaat do not affecct rule criteriaa. For examplee, if setting a lead’s l status to o “In Progress”” causes the ruule to fire, witth this option n, the rule willl only fire aggain if the leaad’s status chaanges, then ch hanges back to o “In Progreess” — no mattter how manyy times you ediit the record. When W workflo ow rules fire, you y want som me sort of acttion to be perrformed. Worrkflow actions can be conffigured to hap ppen immediattely or at som me point in thee future. Immediate workfllow actions aree self-explanattory but with tiime-dependen nt workflow actions you coulld, for examp ple, have salesfforce.com auto omatically send d an email rem minder to a sup pport case ow wner if 64
Salesforce Handbbook
thee case has not been modified d in the last tw wo weeks or crreate a task forr the VP of Saales to call a customer c 5 dayys before an op pportunity is scheduled to close. Time-depen ndent workflo ow is not analo ogous to a systtem scheduler where w a proceess runs at som me date in thee future to fin nd records thatt meet a speciffic criterion. When W a recordd is saved, thee platform cheecks to see if the t record meeets the workflo ow rule criteriaa. If so, it scheedules the acttion(s) to takee place at som me point in the future. If th he record is aggain updated and it no lon nger meets thee workflow rulee criteria, then n all affected acctions are canccelled. When workkflow rules firee they can auto omate the follo owing types off actions: •
Field d Updates - Update the valuue of a field on n a record. Forr example, auto omatically changge the lead’s ow wner to a queuue or another uuser based upo on the value o of the lead statuss.
•
Emaiil Alerts - Sen nd an email to one or more rrecipients. Forr example, auto omatically send aan account maanager an emaiil notification w when a supporrt case closes.
•
Tasks - Assign a new task to a user, role or record owner. For example, autom matically assign n a follow-up task for the aaccount managger to call andd thank a custom mer one week after the oppo ortunity closes.
•
Outb bound Messag ges - Send a secure, s configuurable API meessage (in XML L format) to a ddesignated listtener. For exaample, automaatically notify an a external H HR system when a user updatess their home phone p number.
Developing A Approval Prrocesses Approval p processes are an a extension of o workflow an nd are often taalked about in the same 1 context . An ap pproval processs is an autom mated process your compan ny can use to o approve reccords in salesfforce.com. App proval processses build upon n workflow by allowing you tto specify a sequence s of ssteps that are required to approve a a reco ord. The proccess specifies the steps necessary for a rrecord to be ap pproved, who must approvee it at each steep and the actiions to be takken when a reecord is submiitted for appro oval, approvedd, rejected or recalled. r You can build complex approvval processes th hat dynamicallly evaluate andd route approvvals based upon specific proval process for purchase requests that rroutes the criiteria. For instaance, you coulld build an app approval to an em mployee’s man nager for requeests under $10000 while requeests over $1000 are sent to the purchasingg manager. You can allso enable approval via emaiil. This allows users to simplly reply to an email byy typing appro ove, appro oved, yes, reject, re ejected, or no in th he first line of the t email bodyy and adding comments c in th he second line.
1
ap pproval-processes Jeff Do ouglas & Wes No olte
65
Figurre 2 - 6. A sample approval proccess.
Setting S up an aapproval process involves many m steps andd quite a bit of o planning to do it correctly. You may w want to visuallly design yourr process with h all stakeholdeers to ensure tthat it nts. This will help h you translaate the processs using the Stan ndard Setup W Wizard meets all requiremen mp Start Wizardd. Some of thee steps involveed in setting up p an approval process p include: or Jum
66
•
Determin ne records th hat should bee processed ffor approval - Your processs can either incclude all recorrds for a partticular object or you can fiilter them by entry criteria. T This criterion can c either be a combination of field valuess (i.e., Lead Staatus = “Negotiattion/Review”) or a formula that evaluates to true (i.e., Amount > 10,0000).
•
Specify w which users are allowed to submit reecords for ap pproval - Youu can configuree the process so that only thee record owneer or creator, members m in a p public group or users in a speccific role can suubmit records for approval.
•
Specify the sender of approvall requests - By default, approval reequest ons are sent from the useer submitting the request. You can speccify a notificatio different “from” addresss if required by b your businesss processes. Salesforce Handbbook
•
Who will be responsible for approving or rejecting requests? - Each independent step in the process can be configured to determine who can approve or reject the approval request. This can be the submitter’s manager, a user or queue that the submitter chooses, a queue specified by the administrator, a user listed in the submitter’s custom hierarchy or any combination of users or related users specified by the administrator.
•
Should delegates be allowed to approve requests? - An approval request can be approved by a designated delegate for the approver. For example, a VP of Sales may allow his assistant to approve requests when he is on the road. The Delegated Approver field must be configured on the user’s record with the delegate.
•
What actions should be taken when a record is first submitted for approval? Records are automatically locked when a user submits them for approval. Using the Initial Submission Actions section, you can also configure workflow actions such as field updates, email alerts, tasks and outbound messages that are fired when first submitted.
•
Determine if users can edit records awaiting approval - Administrators and all users with the Modify All and Modify All Data permissions can always unlock and edit records. However, to possibly make the approval process flow smoothly you can also specify that the currently assigned approver can also edit the record.
•
Email templates to be used - By default salesforce.com uses a standard email template when notifying users that an approval request is assigned to them. If your business requires more details you can create your own email templates including standard merge fields.
•
Configure approval page layout - Part of the approval setup process is determining what information on the page layout that users will see. You can determine the individual fields, approval history related list and security settings.
•
Configure automatic conditional response - For each step on the process you can specify an entry criteria that automatically approves, rejects or skips the process based upon some criteria. For instance, you may configure the process so that purchase requests under $100 are automatically approved.
•
What actions should take place when a request is approved or rejected? When a record has received all necessary approvals or is completely rejected, you can configure up to 10 actions each (40 total) of a new task, email alert, field update or outbound message.
Items waiting to be approved can be easily configured to display on a user’s Home tab layout.
Jeff Douglas & Wes Nolte
67
Figure 2 - 7. Ittems to approvee displayed on th he Home tab.
Y You can also write Apex triggers t to auttomate approvval processes based uupon some vaalue on the record. For insttances, you may want to staart an aapproval proceess when an op pportunity reacch 30% probaability. See chap pter 6 ffor a detailed example. e
Form mulas Formulas F are a prevalent feaature in the declarative development areaa of salesforcee.com. The reeason for theiir popularity is because they are a simplee way for non n-technical useers to translaate business reqquirements intto application logic. l Dependiing on their co ontext, formulaas can be useed to present dynamically calculated c field d values, deterrmine default field values, eensure 1 data in ntegrity or dettermine execution criteria . Although it’s important to discuss the vaarious contexxts, it’s worthw while introducin ng the commo onalities such aas syntax. A As you’ll see laater, the declaraative developm ment areas thatt use formulas don’t rrequire any Ap pex code or unit u testing. T This often maakes them easier to m maintain or change, and veryy quick to impllement. It is fo or these reason ns that iit’s highly advised that you consider c using these features as an alternattive to p programmatic development where w possiblee. Syntax x Formulas F are eessentially equuations that arre executed at runtime e.g. when w a page loads. Key to o know at this point is that these t equation ns aren’t just m mathematical, but b can also in nvolve the evvaluation of lo ogic. Although h it is beyond the scope of this book to detail the topics of mathem matics and thee languages of logic, considerr the followingg simple examp ple: Your Y business requirement iss that you need d a field that w will display a discounted d valuue for a purchased item if yyour customer spends more than X dollarss. The T first step required to trranslate this reequirement intto application logic is to word it using something callled pseudo co ode. Essentiallyy you need to break your prroblem into ph hrases separaated by logicaal operators and (if requuired) mathem matical expresssions. The aabove requireement might b be phrased as: IF I custome er A spend ds GREATER R THAN X dollars TH HEN they will recei ive a Y% di iscount ELS SE they don’t receiv ve a discou unt.
1
intro-tto-formulas
68
Salesforce Handbbook
Here the w words in capitaals are the loggical operators.. The phrase between b the IF F and the TH HEN is the exxpression to evaluate, e and the t two logic-b branches will deliver the ap ppropriate ressults (a discoun nt or no discouunt). Once yourr business requuirement is ph hrased in this way then it’s simple to tran nslate this pseudo code into o formula codee. The above example e can bee written as in Listing 2 - 1. Listing 2 - 1. Sim mple Conditiional Formulaa IF( Sale e_Amount__c c > 2000, Sales_Amount__c c * 0.9, Sales_Amount)
The detailss of formula syyntax is extensively documeented in the reeference docum mentation buut it’s valuablee to understan nd the categoriies that the grroups that syn ntactic compo onents fall intto: •
U to includde the value of other fieldds in your Referrences to objject fields - Used formuula. Note thatt you can refeerence related object record d fields very eeasily too! More on this later.
•
Operrators - As mentioned m befo ore these can be either loggical operators (used to determ mine the truth h of a statemeent) or mathem matical operato ors (used to ccalculate a value))
•
Literaals - These aree values that yo ou hard-code, such as pieces of text or num mbers
•
Funcctions - The platform offeers a number of built-in functions f for common operaations. Many of o these are similar s to tho ose offered in Excel and faall into 4 catego ories: Date and d Time, Text, Logical L and M Mathematical
•
Globaal Variables - Provide acceess to system o or other convvenient inform mation. An examp ple is the $Orgganization.Nam me
Figuree 2 - 8. Various Formula F Syntaxx Components Jeff Do ouglas & Wes No olte
69
Cross Object Form mulas Often O you’ll fin nd that you neeed to refer to fields in records that are reelated to the cuurrent record d that the form mula is being ap pplied to e.g. th he formula migght apply to a Contact record, but in thatt formula you might want to o refer to the related Accouunt record. Lucckily salesforcee.com has maade this very siimple and the feature is aptlyy named Crosss Object Form mulas. N Note that it is only possible to access the fields in the direction d of ch hild to p parent i.e. youu will not be able a to retrievve the data of child records from ttheir parents. The T syntax forr these referen nces is natural and precise. C Consider the situation s wherre you need to t create a forrmula for a Co ontact record, but you need to refer to th he related Acco ount’s parentt Account’s naame. In this caase the syntax would be Acccount.Parent.n name i.e. you aaccess the fieeld value by uusing the relateed field namess (separated byy periods) unttil you arrive aat the object field in questtion. For custo om objects thee syntax is sligghtly differentt e.g. if the formula appliess to a custom object and neeeds to interroggate the paren nt object’s nam me field througgh the Parentt__c relationsh hip field, the syyntax would bee Parent__r.naame. This T is very p powerful, espeecially when you y consider that you can n traverse up to 5 1 relationships deep (y (you can mix sttandard and cuustom objects relationship). Wheree Do I Use Th hem? Formulas F can b be used in a number n of areaas within the p platform as preeviously mentiioned, and deepending on th heir context can n be used to achieve differen nt types of resuults. Formu ula Fields These T are readd-only fields with w values deffined by the uunderlying form mula. Data in these fields are a not persistted but is calcuulated on the fly f when the ffield is accessed. Creating formula fields can c be done frrom the same area a as the oth her field types. At A creation tim me you’ll need d to select thee “type” that you wish the field to adop pt e.g. curren ncy, date, and ttext. The type you choose afffects the fieldd display, but also a how the fi field is seen by b any Apex orr API interrogaations. U Using formulaa functions yo ou implicitly h have access to some “sub” fieldttypes includingg hyperlinks an nd images. You Y are free to o use any com mbination of fo ormula compo onent in formuula fields as lo ong as the resultant value iis of the pre-determined tyype. This way you have a powerful p slate upon which you can use conditional lo ogic to presen nt a range of ddynamic valuee types to youur end users. 1
cross-object-formulas
70
Salesforce Handbbook
Never use a formula fieeld as an indexxing or filterin ng value. If yo ou need a field value to be dynamiccally calculatedd but know thaat it will be useed to filter data througgh API calls or o in the WHE ERE clause off any SOQL sstatement, consider using u static fieelds in combin nation with workflows w insttead. The reason herre is that the calculation o of formulas caan be especiaally taxing “under thee hood” to thee platform in these conditio ons and will rresult in a performance loss. Deefault values When declaaring most fielld types you have h the opporrtunity to declaare a default value. This can n either be as simple as a liteeral value or allternatively a fo ormula of any complexity. Iff no value is specified s for th he field when a record is creaated then it wiill be assigned said default vaalue.
Fig gure 2 - 9. Using g formulas in deffault values
Jeff Do ouglas & Wes No olte
71
Validation Rules Validation Rules do not result in dynamic values but instead determine whether the data in a specific field obeys your pre-defined data integrity rules. These can be either rules that force data in a certain field to conform to some standard, or they can enforce simple business or workflow rules. Validation rules are executed when records are edited and created, and if the error condition is calculated to be true the user will be prevented from committing the record. Consider the data integrity example where all account numbers must be numeric. Listing 2 - 2 shows the appropriate validation rule. Listing 2 - 2. Data Integrity Validation Formula AND( ISBLANK(AccountNumber), NOT(ISNUMBER(AccountNumber)) )
Listing 2 - 3 is an example of a business rule that prescribes that the number of worked weekly hours must be less than 40. Listing 2 - 3. Business Validation Formula Monday_Hours__c + Tuesday_Hours__c + Wednesday_Hours__c + Thursday_Hours__c + Friday_Hours__c > 40
Notice that formulas can only have logical operators as their outer most “action”. This way they will only result in a true or false value. You’ll have seen during the creation of validation rules that you must also provide an error message; if the outer most operation results in a value of true then that error message will be presented to the user. Be sure to run through the documented examples as they list a number of commonly used formulas in Validation Rules1. Workflows & Business Rules Salesforce.com supports a number of common business processes such as workflows, approvals, escalations, assignments and auto-response rules. Each of these requires the system to execute business logic to determine whether the rules should be applied, and that’s where formulas enter the picture again. In this way formulas within these rule-types are similar to validation rules but instead of preventing a user from changing data an appropriate rule-action will take place.
1
validation-rule-examples
72
Salesforce Handbook
Visualforce Visualforce is the Force.com programming language for building user interfaces. The application of formulas in this context could thus be considered a programmatic one. Formulas in Visualforce are used to evaluate expressions, and in doing so be used as logical operators e.g. whether a certain page should be displayed, or they can deliver values such as literals, global variable values or even static resources1. Listing 2. 1 Formulas in Visualforce Pages - Conditional Display of OutputPanel $CurrentPage.Parameters.Id
Although the syntax of formulas here is slightly different (you’ll have access to number of other functions, operators and global variables) the overlap is so large that you’ll have no trouble implementing formula logic in your pages. Limitations The formulas that you create are compiled into SOQL code and it is this code that is executed when the formula is referenced at runtime. To ensure that each tenant in the Force.com platform doesn’t abuse the shared pool of resources, it is necessary to impose certain limits on formula field usage.
1
•
Standard, custom and other formula fields can be referenced, but formula field selfreferences are not allowed.
•
If a formula is dependent on a certain field, that field cannot be deleted until the reference is removed or the formula field is deleted.
•
Formula fields cannot exceed 3900 characters in length (including spaces and line breaks). The backend SOQL compiled as a result of your formula cannot exceed 5000 characters in length and the only way to check this is to press the Check Syntax button.
•
Cross-object formulas can travel no more than 5 relationships.
•
You can reference 10 unique relationships per object across all formula fields for an object.
•
No more than 10 uses of the VLOOKUP function can be used across all formula fields per object.
delivering-static-resources Jeff Douglas & Wes Nolte
73
Best Practices It’s common to exceed the length for formula fields and it’s usually not because people are writing exceptionally long formulas! The issue is that if formula field A references formula field B then the length of formula field A is effectively (the character length of A) + (the character length of B). It’s therefore very important to bear this dependency in mind and adhere to some of the common best practices for keeping formulas short. 1.
Refactor your mathematical formulas using Algebra. Using the fields A and B described above you might’ve written the value of A as: A = B + B * (0.1)
This would result in the formula representation of field B being pulled into the compiled version of field A twice. We can write this as: A = B * (1 + 0.1) = B * 1.1
In this new representation the formula represented in field B will only appear once in A making your formula shorter by as many characters are in formula B. 2.
Often you’ll need to validate that a user has entered one of a number of valid values e.g. country or area codes. Sometimes this validation is necessarily complex but often all you need is a picklist field. By their nature they help users avoid erroneous input values and you can avoid writing or referencing formulas.
3.
Effective use of the available functions can help reduce the length of formulas so be sure to read through the list from time to time, making sure you understand what each does. For example if your formula examines two numeric field values and presents which ever has the smallest value you might write the following: IF ( X < Y, X, Y )
A quick look through the available functions you notice one called MIN allowing you to rewrite this formula as: MIN( X, Y)
This of course is a simple example but treating each part of your formula with such thrift will certainly pay off in the long run. 4.
This point repeats some of the message above but the use case is so common that it deserves independent mention. Oftentimes you’ll be tempted to use a number of IFstatements when trying to determine which value a formula field should display. This can be further complicated if the value you’re examining belongs to a picklist. Such an example might be: IF (ISPICKVAL( Type__c , “Annual”), 10, IF (ISPICKVAL( Type__c , “Semi-Annual”),
74
Salesforce Handbook
20, IF (ISPICKVAL( Type__c , “Quarterly”), 30, IF (ISPICKVAL( Type__c , “Monthly”), 40, 80 ) ) ) )
At 197 characters this isn’t a whopper of a formula but it’s good to keep your house in order. In this type of situation it’s more economical to use a CASE-statement such as: CASE(Type__c , “Annual”, 10, “Semi-Annual”, 20, “Quarterly”, 30, “Monthly”, 40, 80)
Not only is this easier to read, at 93 characters it is less than half as long as the original formula. 5.
Sometimes you’ll just have to use a formula that can’t be accommodated by the limits of formula fields. In such cases you have two options, you can either use Workflow or Apex Triggers. For each you’ll need to create an object field of the type you’d like to present. The Workflow or Trigger would then update this value at creation, update or both of object records. With Workflow you’d do this by using Field Updates, and specifying the formula required. Note the formula restriction here is much larger than for regular formula fields. For triggers you’d have to translate the required logic into the Apex and write the value to the record’s field. As seasoned developers, we’d highly recommend writing formula code in a text editor with some concept of syntax highlighting and bracket matching. You’ll also save a lot of time if you lay your formula code out neatly, indenting it where necessary as well as breaking to a new line to visually delimit function calls and conditional return values.
Examples Although formulas are bespoke and can be fairly complex in nature you’ll find that even the most intricate requirements often reuse combinations of smaller, common formulas. Jeff Douglas & Wes Nolte
75
Salesfo orce.com has taken the time to documen nt many of theese and we’d recommend p poring 1 over th hem as a start, or even as a reference to mo ore experiencee formula userss .
Valid dating User Input In I addition to workflow and d formulas, vaalidation rules are one of the most widelyy used featurees on the platfform. Validatio on rules help ensure e data inttegrity by veriffying that the ddata a user en nters meets ceertain standard ds. Validation rules r fire when never a user attempts to insert or changee a record. Theese rules preveent incompletee or “junk dataa” from being entered by miistake, which in turn causess more issues to creep up dow wn the road. To T get startedd using valid dation rules, click Setup -> Custo omize, selecct the approp priate object frrom the menu,, and then clickk Validatio on Rules. A validation ruule can contain a formula or o expression that evaluates the data in o one or more fields and retuurns a value of “true” or “ffalse.” The valiidation rule caan be configurred to displayy a custom errror message to o the user, eith her at the top o of the page orr next to a speecified field. A validation ruule will fire an nd display an error e message even if the offfending field is not displayyed on the pagge layout.
Figure 2 - 100. Configurating g a validation rulle to fire if an em mail address is not n entered. 1
useful-validation-formuulas, formula-cheatsheet
76
Salesforce Handbbook
Validation rules are a plaatform level service and no ot simply for the t UI. Validation rules apply to all new and updated records r for an object even w when processed d by one of the APIs or duuring the data loading process. Administraators must be b aware thaat adding new w validation rules in production n may break exxisting processses and integrations. Alwayss test in a sandbox en nvirnoment beefore making p production chaanges.
Bu uilding Pub blic Websitees Force.com Sites allows you to exten nd your salesfforce.com app plications andd data by creeating public w websites and ap pplications thaat run natively on the platforrm1. Since youur sites are ho osted on the Fo orce.com serveers, there are none n of those pesky data inttegration issuess allowing you focus on ccreating highlyy interactive, scalable s websiites. Force.com m Sites are buuilt using Visualforce and Apex, and th hus can leveragge the data, co ontent and loggic that residees in your Orrg. You can sset up your site to be wid de-open to thee public or reequire a usern name and password to acccess it (via Cuustomer or Partner Portals).. Force.com taakes care of yyour site’s inffrastructure heeadaches freein ng you up to co oncentrate on building appliccations such ass: •
Corpo orate websitee - create a public-facing p w website using standard web elements such aas CSS, Flash and a JavaScriptt frameworks ((e.g., jQuery, YUI) Y
•
Emplloyee intraneet - set up a company c intran net that uses single sign-on n, restricts accesss by IP address and/or time of day
•
Colleect new ideass - host a pub blic community forum for sharing and vvoting on Salesfforce Ideas reggarding your co ompany’s prodducts and serviices
•
Micro osites - createe microsites to o collect feedb back or allow w people to siggn up for webin nars or marketiing informatio on
•
Expo ose product information i - publish youur company’s product cataalog on a subdo omain of yourr existing website with detaiiled descriptio ons, current prricing and produuct images all pulled p seamlesssly and in real--time from youur Org.
Setting up a new Force.com Site is rrelatively easy.. Start by cliccking Setup -> App Se etup -> Dev velopment -> - Sites. Choose C an avaailable Force.co om domain naame, enter thee name of youur site, pick a siite administrattor and the platform spins up p a new site fo or you in a maatter of secondds. You can th hen create pagge templates to o give your sitte a consistent look and feeel that matchees your corporrate branding.. Your site tem mplate provides the page laayout and styylesheet for yo our site and ovverrides formaatting inheritedd from any asssociated portall that you maay use. You can then start ad dding standard d or Visualforcee pages by asso ociating them with your site. Apex contro ollers and classses provide thee logic for your site.
1
siites Jeff Do ouglas & Wes No olte
77
Configuring C peermissions for your site lookks relatively fam miliar1. Visitorrs to your site use a Guest t user license and a Sites-sp pecific profilee. You configuure the permisssion for this Sitesspecifiic profile like yyou would anyy other profilee in salesforce.com. You can n configure tab b and record d type access, p page layout asssignments, field d-level securityy for standard and custom objects and ob bject permissio ons (read, creatte, edit and dellete) for each ssite’s users. It is i important to o note that saalesforce.com does imposee some additio onal access reestrictions for Sites visitorss. For instancce, while visito ors can read, create, c edit and d delete custom m objects theyy can only read and create standard objeects. Some objeects such as prroducts and prrice books onlly offer read aaccess. Be surre to check thee documentatio on before desiggning your Forrce.com Site.
Figure 2 - 11. Configuring C perm missions for Stan ndard objects.
Sites S impose llimits based upon u edition but they are fairly liberal. For instance,, with Enterp prise Edition th he maximum page p views perr month is 5000.000 and the bandwidth b limiit (per rollingg 24-hour perio od per site) is 40 GB. You can purchase more page viiews if neededd. The numbeer of individuaal Force.com Sites you can create is deterrmined by youur edition. Yo ou can run yo our site off of a Force.com domain name (hhttp://acmecorp.force.com/intrannet) or use yourr own compaany branded do omain set up with w a redirect via DNS. Y You can moniitor Sites userss by adding th hem to the Deebug log. How wever, ffor public web bsites this onlyy provides a ggeneric view off their actions. You ccan also previeew a site as an n administrator and view deebug info by aadding ssome tags to th he Visualforce footers.
Going Global With W more an nd more globaal companies adopting saleesforce.com, itt’s no surprisee that internaationalization an nd localization is an importan nt aspect of thee platform. Saleesforce.com sup pports geograaphical segmenttation, advanceed multi-currency and translatiion of the UI in nto 20+ languaages. 1
profilees
78
Salesforce Handbbook
Diivisions Divisions aallows you to segment your data into orgaanizational “buuckets” providding users 1 with a view of data that is relevvant to their needs n . You can n set up divisio ons any way th hat makes sen nse to your company such ass geographicallly, line of busin ness (i.e., com mmercial or govvernment) or any other typ pe of internall corporate grrouping. Divissions do not restrict r data aaccess but maakes data easieer to manage and a find for laarger Orgs. Fo or instance, a sales managerr in South Am merican may w want to run reports r or forrecast sales on nly for South American an nd not be concerned with E European dataa. Contacts salesforce.com m Support to o enable divvisions for yo our Org. Divisions are a meant for segmentation s p purposes only and do not en nforce any type of security constrain nts. When divisions are enab bled, a divisio on called “global” is autom matically createed and all reccords are autom matically assign ned to this divvision by defauult. You can create up to 1000 divisions buut you should ccarefully plan your y strategy in n advance for h handling multiiple divisions. You will alsso need to set the default divvision for each h user. This is the t division th hat applies to all newly created accounts, leads, l and custtom objects fo or which divisiions are enableed (unless thee user explicitlly chooses a division). d You can also enab ble the Affec cted by Div visions permission for p profiles so that users can set their t current ““working” divission. Users can n set their “w working” divisiion using a drrop-down list in the left sidebar thus lim miting search results to reccords in the seelected division n. Users witho out this permisssion still havee a default divvision, can vieew division fieelds, change th he division for a record and specify a divission while creaating new reccords. Howeveer, these users will always seee records in alll divisions. The permission aalso filters listt views by diviision and allow ws users to run reports for a ssingle or all divvisions. Lo ocale A user’s L Locale setting affects the fo ormatting of n names, numbeers, date and ddate/time fieelds and calenddars. The Localee determines the t order that first and last names are dissplayed for useers, leads, and contacts. Fo or instance, Miike Smith in th he English (U United States) locale l displays as “Mike Sm mith”, while the same name in i the Chinese (China) localee displays as “SSmith Mike”. Dates and ttimes are also displayed per a user’s Locale. A date in thee English (Unitted States) loccale will displayy as “04/28/20000” while it diisplays as “28/004/2000” in th he German locaale. Times in the English (U United States) lo ocale display using a twelve-h hour clock with h AM and PM (e.g., 3:00 PM M), while in thee German localee, they display using u a twenty--four-hour clocck (e.g., 15:00). Dates are stored s in the database d in GM MT and converrted on-the-fly using the user’s Locaale. To importt data for a useer with EST, use u the formatt 2010-0625T18:25:000.000-04:00 with w the 4 hourrs time zone offfset.
1
in nternationalization n Jeff Do ouglas & Wes No olte
79
Curren ncies The T Force.com m platform has support for multiple curreencies baked in i from the grround up1. It provides addvanced supp port for multiiple currencies for opportuunity manageement, forecasting and repo orting. With multi-currency m enabled each h international division can track, forecast and reportt on opportuunities in locaal currencies, while providiing enterprisee-wide forecasting and repo orting in a singlle common cuurrency. C Contact salesfo orce.com Supp port to enable multiple curreencies for yourr Org. O Once enabled, the link willl visible and you can man nage currenciies by cclicking Setu up -> Ad dministrati ion Setup p -> Com mpany P Profile -> Manage Cur rrencies.
Once O multiple currencies aree enabled, you’ll need to set up a “corporaate currency” w which reflectts the currencyy used by the corporate heeadquarters. Yo ou can then create c and maaintain multip ple currencies in which yo ou do businesss and their cconversion raates relative to o the corporrate currency. Every user must m have theiir “personal ccurrency” conffigured. When n new record ds are created, the user’s perssonal currency is automaticallly used unless another curreency is selecteed manually. T The personal cuurrency is also o used as the uuser’s default currency c for quuotas, forecasts, opportuniities and reporrts, however other o active cuurrencies are also a available. Only active currencies can n be used in cuurrency amoun nt fields.
Figure 2 - 12. Configurin ng multiple currrencies.
When W adminisstrators changge an existingg conversion rate, all currrency amountts are immed diately updatedd with the neew rate across the entire Org. This incluudes all converrsions within n opportunities, forecasts, and a other am mounts that uuse the curren nt conversion n rate. Previo ous conversion n rates are not stored and you cannot trackk revenue gain or loss based upon curren ncy fluctuation ns. If currencyy changes seveerely impact yyour companyy, you may waant to investiigate using Datted Exchange Rates. A An opportunitty’s currency cannot c be mo odified once a product has been aadded to it witth the default currency. Youu will need to remove all prroduct rrecords first beefore you can modify m the opp portunity’s currrency.
1
curren ncy-management
80
Salesforce Handbbook
Ad dvanced Currrency Manageement Advanced currency maanagement allows you to manage dateed exchange rates for op pportunities. D Dated exchangge rates allow w you define a conversion n rate for a specified currency’s date range. For exxample, a com mpany’s exchan nge rate in th he 3rd quarterr and 4th quuarters are 1 U USD to .60 EU UR and 1 USD D to .75 EUR R, respectivelyy. All opportun nities that clo ose in the 3rd quarter use th he 3rd quarter exchange rate (1 = .6) whilee those that clo ose in the 4th h quarter use the 4th quarteer rate (1 = .775). This retain ns the historical conversion rates and ten nds to be very beneficial to most m large com mpanies. Dated exch hange rates aree used in conjunction with opportunities, opportunity products, op pportunity prodduct scheduless, campaign op pportunity fieldds and reports related to these objects and fields. Staticc conversion rates, instead of dated exch hange rates, are a used in fo orecasting, currency fields in n other objectss and currencyy fields in otherr types of repo orts. When advaanced currency managemen nt is initially en nabled, your existing e static exchange rattes automaticallly become youur first set of dated d exchange rates. These rates are validd until you define another set of exchangee rates. Dated exchange ratees are defined using a conveersion rate and a start date. Each conversiion rate is effective until the day before thee next start datte for that currency or untill either the end d of time.
Figure 2 - 13. Creating a new dated eexchange rate.
When advvanced currenccy managemen nt is enabled, Visualforce inputField and outputtField compon nents cannot ddisplay currency fields. If yo ou enable advanced currency c manaagement, you cannot create roll-up summ mary fields that calculaate currency on n the opportun nity object. Enabling multicurrency m m have some unintended consequences may c regarding SOQL queeries and aggreegate functionss. Be sure to ch heck the docum mentation for the imp plications of en nabling multicuurrency. Jeff Do ouglas & Wes No olte
81
Transslating the Usser Interface Salesforce.com S m allows users to work in th heir language o of choice with h a simple lan nguage attribuute on the userrs’ record. Thee salesforce.co om UI is availaable in Danish h, German, En nglish, Spanissh, Finnish, F French, Italian n, Japanese, Korean, K Dutcch, Portuguesee (Brazil), Ruussian, Swedissh, Thai, Chin nese (Simplified d) and Chinesee (Traditional). To translate customization ns that you’vee made to yo our Org or to t override trranslations fro om managed packages, use the Transllation Workbench to translate virtually eveerything from custom pickliist values to cuustom fields into a suppo orted language1. These custo omizations arre also availab ble for partner and custom mer portal userrs. As A an administrator you add d translatable languages to yyour Org and optionally asssign a user reesponsible for translating cuustomizations. The admin intterface allows you to translaate the text fo or buttons andd link labels, cuustom fields, standard s field h help, record tyypes, picklist vvalues, web taabs and plus m much more.
Figurre 2 - 14. Translaating picklist vaalues in the Tran nslation Workbeench.
Once O enabled, the Translatio on Workbench h imposes som me changes to your y salesforcee.com Org:
1
•
Picklist vvalues must be b edited indivvidually and yyou can no lo onger mass uupdate picklist vaalues (mass add d is still availab ble)
•
When sorrted alphabeticaally, picklists aree sorted alphab betical by the Org’s O default lan nguage
•
Reports m may have a langguage drop do own for certain n filter criteria
•
Web-to-L Lead and Web-tto-Case requiree a language seleection before generate g the HT TML
translaation-workbench--overview
82
Salesforce Handbbook
Not everth hing in salesforrce.com is tran nslatable. You are a currently n not able to translate Visualforce V tabs, homepage ccomponents elements e or record type description ns.
Using Analyttics You’ve sp pent a lot off time, effort and money putting yourr important ddata into sallesforce.com aand you want to o be able to viiew it, report o on it and analyzze it in a coherrent, userfriendly mannerr. One of thee advantages of the Force.com platform m is that it in ncludes a complete system m for building reports, r securing and scheduuling them and d assembling ccollections of them into user-friendly dasshboards. It’s not as powerful as say Cryystal Reports b but it also do oesn’t have the steep learningg curve and asssociated price ttag. While the ttopic of analytiics is extremelyy important, a deep-dive is beyond b the sco ope of this bo ook. Reportingg is well docum mented in the user u guide andd there are num merous tutoriaals to help gett you started1. The best wayy to learn abo out analytics iss to simply staart building rep ports and asssembling them m into dashboards. We’ll coveer some topicss from a high leevel. The Winterr ‘11 release sp ports a new an nd greatly improved visual, real-time r reporrt builder. Th he new reportt builder allow ws you to add d, reorder, and remove collumns, summaary fields, forrmulas, and grroupings with ease. e You can even change tthe report form mat and displayy options, add a chart and p preview data in n real-time.
Figure 2 - 15. Creating a new n Account and d Contact reportt with the real-tiime report build der.
Choosing tthe format off the report drrives a numbeer of options that t are availaable when acttually building the report. Th here are three types t of reportts you can cho oose from: •
1
Tabu ular - Tabular reeports are analo ogous to spreaddsheets and aree best for creatiing lists of recordds or a list with h a single grand d total. They co onsist simply off an ordered seet of fields in coluumns, with eacch matching reecord listed in a row. Tabular reports can’t b be used to createe groups of dataa or charts, and d can’t be used iin dashboards unless rows aree limited.
reeports Jeff Do ouglas & Wes No olte
83
•
Summaryy - Summary reports r are the most widely uused report typ pe. These are similar to tabularr reports but also allow useers to group rrows of data, view subtotalss, and create chaarts.
•
Matrix - Matrix reportss are similar to o summary rep ports but are much m more pow werful and comp plex. This form mat allows yo ou to group an nd summarize data by both rows and coluumns. This fo ormat is partticularly usefuul for comparring related ttotals, especiallyy if you have laarge amounts of o data to sum mmarize and yo ou need to com mpare values in several differrent fields, or you want to look at data by division an nd by product, aaccount rep, or sales region.
When W saving a rreport one of the t confusing aspects a is providding access to the t report. Theere are a num mber of public rreport folders into which youu can save youur report. How wever, if you w want to restrictt access to the report you do not configure this at the repo ort level. Insteaad, you must crreate a new report r folder aand grant access to it for specific Publiic Groups, Ro oles and Roles and Subord dinates. Only th hese specified users u will have access to the fo older and any reeports in it. You Y can schedule reports to run and have the t results automatically emaailed salesforcee.com users. T The informatio on a users seess in a report is only the data to which theyy have aaccess. This in ncludes recordss they own, reecords to which h they have reead or rread/write access, records th hat have been shared with th hem, records o owned b by or shared with w users in roles r below th hem in the hierarchy, and reecords ffor which theyy have “Read” permissionss. Therefore, reports r may ddisplay ddifferently baseed upon the usser running thee report. Runniing Dynamicc Reports Salesforce.com S m has a little un ndocumented and a unsupportted feature thaat allows you tto run 1 reports dynamically . Typically if you would likke to display tthe number off widgets soldd by a specifiic account for a practice, yo ou would havee to run the reeport and choo ose these selecctions from the t individual p picklists. To T run these reeports dynamiically you simp ply add a custo om link or buttton to the acco ount’s detail page that passses these variaables to the reeport using meerge fields or other o coded vvalues. Createe the report in n the format th hat you want but b leave the vvalues for the criteria blankk. You then append a the varriables to the URL U where pv v0 is the first p parameter, pv1 1 is the secon nd and so on. The code for the URL for your y custom lin nk or button w would look likee: https://na2 h 2.salesforc ce.com/[ID of the Report]?pv0 R 0={!Account t.Id}&pv1={ {!Account.Practice__ _c}&pv2={!A Acco unt.Product u t__c}
The T URL passeed to run the report r would th hen look like: https://na2.salesf h sforce.com/000000123AJUY344?pv0=0000000456ABCBD& &pv1=EMEA&pv2 =LAPTOP = 1
reportts-dynamic
84
Salesforce Handbbook
Cu ustom Reportt Types Salesforce.ccom come witth a large set of report types pre-defined. The T first step in n creating any report is cho oosing a reporrt type. But wh hat if you wouuld like to provvide your userss with the ability to reportt on data bassed upon youur customizations or from different aspects? For insstance, if yourr Org contain ns a shipmentt custom objeect, you may want w users to o run and customize reporrts based on accounts with h open opporrtunities and shipments s thaat include specific fields fro om all three ob bjects. Salesforce.ccom enables you y to create cuustom report ttypes that allow w you to conn nect up to 1 fouur related objeects in order to t expand thee scope of youur Org’s reporrting ability . O Once you havve defined a cuustom report type, t users can n create custom m reports from m it. You can create new custom report tyypes by clickingg Setup -> App Setup -> Create -> Report Types.
F Figure 2 - 16. Deefining the objecct relationship ffor a custom rep port type.
When creatting a new cusstom report typ pe, the objectss available for you to choosee from are based on the p primary objectt’s relationship ps to other o objects. For exxample, if you choose acccounts as thee primary object, then youu can only ch hoose standarrd and custom m objects asssociated with aaccounts (e.g., contacts, opp portunities). Th his also applies to subsequen nt objects added to the ccustom reportt type. So, iff account is sselected as th he primary ob bject and op pportunity is seelected as the secondary s objeect, then you ccan only selectt objects associiated with op pportunities as the third object for your cusstom report typ pe. Daashboards A dashboaard is a collecttion of compo onents (reportts, Visualforce pages and S--Controls) thaat graphically displays a snapshot of key k metrics an nd performan nce indicators2. Report components can n display as gaauges, tables, horizontal andd vertical bar charts, line ccharts, pie 1 2
cuustom-report-typ pes dashboards Jeff Do ouglas & Wes No olte
85
charts,, donut charts and funnel ch harts. You can n select up to 220 different co omponents forr each dashbo oard but only ssummary and matrix m report formats f can bee used with theem. As A with reportts, folders con ntrol user access to the dasshboards how wever the Run nning User determines acccess to the actu ual data. The running r user fo or the compon nent can be: •
A named d user – The dashboard d run ns using the seecurity settingss of a single, n named user. All users with acccess to the daashboard see tthe same data,, regardless off their own perssonal security settings. Use this approach for sharing th he “big picturre” of support ccases across a division, or motivating a sales team m by showingg peer performan nce within a teeam.
•
The currrent user – These T dynamic dashboards d run using the secuurity settings o of the user curreently viewing the dashboard d. Each user sees the dashboard accordiing to their own n security and access settings. Use this app proach to sharre one commo on set of dashbo oard componen nts to users wiith different leevels of access.
Salesforce.com S m recently intro oduced the Daashboard Buildder1, a drag-and d-drop interfacce for creatin ng and modify fying dashboarrds. The new builder is a dramatic improvement oveer the previo ous multi-screeen approach an nd allows you to drag-and-drrop componen nts and datasources; configgure, rename aand move com mponents; edit component tiitles, chart typ pes and settinggs and configgure dashboardd properties.
Figure 2 - 17. Drag-and-d drop Dashboard d Builder.
Y Your Org can n have up to o three dynam mic dashboard ds which muust be rrefreshed man nually. You can n’t schedule reefreshes for dynamic d dashb boards sso ensure that you plan accorrdingly. 1
dashbo oard-builder
86
Salesforce Handbbook
An nalytic Snapsh hots Reporting iis a static funcction by its verry nature. Wheen you view a report it repreesents the current state of yyour data in saalesforce.com. If the underlyiing report dataa changes, a m minute or a dayy after the rep port for instancce, the existingg report does n not reflect theese changes. Byy creating analytic snapshots you can report on trendin ng and changin ng data in your Org1. For insttance, you maay set up an aanalytic snapsh hot to track daily d inventoryy levels in youur warehouse aand allow useers to report o on it. You can crreate new analyytic snapshots by clicking Se etup -> Adm minstrative e Setup -> > Data Mana agement -> > Analytic Snapshots. To create a new analytic snapshot you essentially crreate a new reeport and then pipe the outp put of the repo ort on a scheduuled basis to a custom objeect that you deefine. Users caan then use the data in this custom c objectt to create rep ports or constrruct dashboard ds. Triggers an nd workflows on a target object are not exxecuted as a reesult of an analytic snapshot run. In n fact, you aree not allowed to use an objeect with a trigger as the target of a snapshot. Addding a trigger to t a target objeect results in the snap pshot run failin ng.
Overriding L Link, Tabs and a Labels Salesforce.ccom allows yo ou to rename taabs, objects an nd fields to maake the UI mo ore closely refflect your co ompany’s terrminology. Fo or instance, you can reename “Accounts” to “O Organizations” if your co ompany operaates with thiis terminologgy. Click Set tup -> Cu ustomize -> > Tabs and d Labels -> - Rename T Tabs and Labels L to m make these Orrg-wide changees.
Fig gure 2 - 18. Renaaming standard ffield labels.
Salesforce.ccom also provid des a way to ovverride the beh havior of standaard buttons andd links for eacch object2. So instead of displaying the staandard details page when you click on a liink for an op pportunity’s dettails, you can haave each opporrtunity display iin a customized d Visualforce page. Overrides aare global thro oughout the saalesforce.com UI as they co ontrol the actio on behind thee each button and link. Forr example, if you y override tthe View link on opportuniities, your rep placement action takes effectt wherever thaat action is avaiilable: 1 2
an nalytic-shapshots ovverriding-links-buuttons Jeff Do ouglas & Wes No olte
87
•
The opporttunities tab ho ome page
•
Any opportunities related d lists on otherr objects such as accounts
•
Any link reepresenting thee record displayyed in the UI
•
Any browser bookmarks for this salesfo force.com pagee
To T use a Visualforce page insstead of the staandard details page, click thee Override b button for thee View link. In n the Override Properties seection, select tthe Visualforcee Page radio b button to disp play the list off available Vissualforce pages for the opportunity objecct. Only Visuaalforce pages that implemen nt the opportun nity standard controller c will be displayed in n this list.
Figuree 2 - 19. Overriding the standard d view page with h a Visualforce page. p
The T standard b buttons and lin nks section willl now show th hat your Visuaalforce page is being used in nstead of the default salesfo ore.com detailss page. You caan click the Re eset link to rrevert back to o the default ddetails page.
Fiigure 2 - 20. Stan ndard Buttons and a Links sectio on with the overrridden display Visualforce V pagee.
88
Salesforce Handbbook
Sending Mass Email Salesforce.com has the ability to send mass emails but is not designed to be an email marketing solution1. Your email distribution lists can consist of contacts, leads, person accounts, or users that are accessible to your user in salesforce.com. However, you can only send email to a maximum of 1,000 external email addresses per day and the number of external email addresses in your list is dependent on your edition. You can, however, send an unlimited amount of email to internal users. For use with mass emails, you can create email templates using plain text or HTML2 (with and without letterheads) that include record-specific data via merge fields, graphics and attachments. Mass emails can be sent immediately or scheduled for delivery. Users can view and cancel mass emails they schedule by clicking Setup -> Email -> My Mass Emails while Administrators can view and cancel mass emails scheduled by all users in their Org by clicking Setup -> Monitoring -> Mass Email. Some potential issues with sending mass email from salesforce.com include: •
The “from” email field is automatically generated with the sending user’s email address and cannot be changed.
•
You cannot send a mass email using a Visualforce email template.
•
You can only track the first date an email was opened, the number of times it was opened and the date it was most recently opened.
•
Salesforce.com has some issues with whitelisting of mass emails that may cause your mail to in up in the recipient’s spam folder.
If your Org has more complex mass email requirements or needs to send very large volumes of mail, you will need to look at one of the many mass email applications available on the AppExchange. Pricing typically depends upon volume but these applications do offer some attractive features such as the ability use pre-designed templates, easily build segmented lists, track post-launch statistics (opens, clicks, bounces, unsubscribes, etc.) and opt-in/out management all from within salesforce.com.
Importing Data Importing data into your Org is almost a required task for new implementations or ongoing maintenance. There are a number of options and avenues that you can use to get data into your Org3. Salesforce.com offers a number of import wizards to easily import records for accounts, contacts, leads, solutions and custom objects using CSV files. The wizards attempt to dedupe records but the matching functionality is limited. All users can use the Import My Contacts wizard however only administrators can use the Org-wide Import My Organization’s wizards to import accounts, contacts, leads, solutions, or custom objects for multiple users. Individual users may only import data into fields that are accessible via their mass-email email-templates 3 importing-data 1 2
Jeff Douglas & Wes Nolte
89
page laayout or field-level security settings s while administratorss can import in nto any of the listed fields regardless r of security settings. Salesforce.com S m offers a clien nt application for inserting, updating, upserting, deleting and extractting records ccalled the Dataa Loader. Thee Data Loaderr can move daata into and o out of virtuallly any type off object using CSV files. To o prevent dupllicate records from being crreated duringg the import p process, you can c use an ID D from an exxternal system (referred to as an “extern nal ID”) as a unique key. An A external ID D is a custom field that has the “Externaal ID” attribuute checked. W When you seleect the upsert option duringg the import process, p the im mport wizard d and Data L Loader will detect existing records r in sallesforce.com that t have the same extern nal ID and upseert the record matching reco ords instead off creating a new w one. M Make sure thaat the user performing thee import has the Modify All D Data permissiion checked on n their profile for the objectss being importted so tthat any sharin ng rule checks are a skipped. You Y can dow wnload the Windows W versio on of the D Data Loader from f Setup p -> Admin nistration Setup -> Data Manag gement -> D Data Loader r while the Maac OS X verrsion, LexiLoaader, is availab ble at http://w www.pocketsoap.com. Both verrsions of the Data Loader use the samee Web Servicess API so the on nly difference is the client in nterface.
Fig gure 2 - 21. The OS O X version off the Data Loadeer extracting data.
90
Salesforce Handbbook
The Data L Loader can alsso run unatten nded from thee command lin ne (aka Comm mand Line Intterpreter) in sscenarios where human interaction is no ot required. The T CLI uses the same en ngine as the G GUI interfacee thus supports the same operations for f inserting, updating, up pserting, deletin ng and exportiing data. The Data Loader L has buiilt in support ffor the Bulk API A providing a fast and efficient way w to upload extremely largge sets of dataa. You can alsso import attachmentt and documen nts into salesfo orce.com usingg the Data Loaader. A number of third-party applications are a available on n the AppExch hange (mostly for a fee) forr loading, updaating, dedupin ng and cleansin ng data. Deman ndTools from m CRMfusion is a widely po opular favorite among admin nistrators. How wever, if pricee is an issue, you y can also b build your ow wn data loadin ng application n using any cllient-side langguage that is supported s by the Web Services API. For loading extremely large sets of data, salesforce.com m offers a RE EST-based Buulk API with m management an nd monitoring features built into the salesfforce.com UI.
Deploying Co ode to Prod duction Salesforce.ccom requires you to write your Apex co ode in a sandb box or develo oper Org, pro ovide unit tessts to ensure your code performs as in ntended and then t deploy itt to your pro oduction Org. Even though h it is possiblle to make co onfiguration ch hanges directlyy in your pro oduction Org,, the best practtice is to do th his is a sandbo ox or developeer Org and theen test the im mpact. There arre a number of o ways that you y can deployy code and co onfiguration ch hanges to your production Org. Fo orce.com IDE E The Force.com IDE is a free, salesforcce.com supported Eclipse pluug-in that facillitates and sim mplifies develo opment on thee Force.com platform. p The F Force.com ID DE has a built in wizard forr deploying co ode, resources and a other conffiguration chan nges to producction. Fo orce.com Mig gration Tool This migrattion tool is a command linee, Apache Antt tool for scrip pting deploym ments. The pro ocess of using tthe Force.com Migration Too ol is more comp plex that deplo oying with the F Force.com ID DE and may reqquire some Javaa experience. This T tool is welll suited for repeetitive deploym ments such as testing deploym ment plans or in nstalling code into i production n Orgs during setup. s The Forcee.com IDE an nd the Force.ccom Migration n Tool will bee covered fully in lateer chapters.
Jeff Do ouglas & Wes No olte
91
Unmaanaged Packaages Unmanaged U paackages are th he “old schoo ol” way to deeploy code an nd componentts. An unman naged package contains comp ponents such as a code, objectts, reports, or email templatees, for instancce, which can b be uploaded to o share with otthers privately or publicly. Chang ge Sets Change C sets arre the newest method for deploying d codde and components and pro ovides some enhanced fun nctionality1. Ch hanges sets usee packages in the backgrouund but providde the ability to move codee from not onlly sandbox to production, b but from sandb box to sandbo ox and producction to sandb box. While W deploym ment with the Force.com F Miigration Tool aand the Force..com IDE are tasks typicallly performed by developers, change sets are a focused m more for admin nistrators. For larger compaanies this allo ows multiple developers to t create chaange set thatt are deployeed by administrators who o may have more intimatte knowledge of their en ntire salesforcee.com landscape. Before B deployiing change setts administrato ors must setup p trusted deplo oyment connecctions betweeen their Orgss. Deploymentt connections can’t be creaated between arbitrary Orggs. By defaultt a deploymen nt connection is created betw ween all Orgs affiliated with h a production n Org (e.g., sandboxes). s Co onnections aree created betw ween each sanddbox and betw ween each san ndbox and prroduction Orgg. A deploymeent connection n alone doesn n’t enable chan nge sets to bee sent betweeen Orgs. Each h Org must be authorized to o send and receeive change seets. This addedd level of secuurity enforces code promotio on paths and keeps k an Org’ss metadata from m being overw written by misstake.
Figu ure 2 - 22. Chan nge Set showing outbound chan nges to productio on.
When W sendingg changes from m your curren nt Org to another Org, youu create an outtbound changee set. The proccess to create and a deploy a change c set is reelatively straigh htforward. Youu first create a new changee set and then walk through a series of screens adding the t componen nt that
1
changee-sets
92
Salesforce Handbbook
you want to dep ploy. Once youu Upload the change set, th he receiving Orrg sees it as an n inbound change set and ccan accept and deploy it with h a few clicks. A change set is deployed as a single tran nsaction. If the deployment fails for any reeason, the en ntire change seet is rolled bacck. After a dep ployment completes successfully, all changges in the sett are committeed to your Orgg and the modiifications cannot be rolled baack. Unfortunattely, as of Winter W ’11, chaange sets do not support ddeploying componen nts with respecct to profile ssecurity. Thereefore, new com mponents will not automatically be available to n non-SysAdmin users. You wiill need to edit each profile p individ dually and adjuust the field-leevel security an nd access levels as required for each h component deployed.
Sttoring Appliication Mettadata Salesforce.ccom recently introduced i Cuustom Settingss in Winter ‘10, which allow ws you to sto ore custom daata sets and associate a them m on an Org-w wide, profile or o user basis1. Custom Settings are essentially custom m objects thaat are exposed in the application cachee and are acccessible via th heir own API.. They are maanaged by cliccking Setup -> App Se etup -> De evelop -> C Custom Sett tings.
You can ceertainly build your y own custtom objects to o store settingss (many peoplle do) but usiing custom settings is much h quicker (agaiin they are sto ored in the app plication cachee) and do no ot count again nst SOQL limiits when fetch hed. You can also use custo om settings in n formula fieelds, validation rules, Apex co ode and the Web W Services AP PI. List Custom Seettings List custom m settings allow you to storre Org-wide sttatic data that is frequently used. For insstance, salesfo orce.com does not have ISO country co odes baked into the platforrm. Many companies main ntain this list of o countries an nd their ISO ccodes in a sepaarate custom o object. So wh henever they n need this dataa they have to o query this ccustom objectt, which bringgs with it additional overh head pertainingg to the SOQL L limits. Usingg a list custom m setting comp panies can sto ore these codees and use them m virtually anyywhere neededd and retrieve them quickly from the application cachee. When you create a new w custom settting the platfo orm creates a custom objeect in the background for you. You then n add addition nal fields to the custom settiing in the sam me manner thaat you do for custom objectts (you are lim mited to checkb box, currency,, date, date/tim me, email, nuumber, percentt, phone, textt, text area an nd URL fieldss). After you’vve set up youur custom setttings and added your fields,, you can selecct the Manage e link on the Custom C Settinggs page to add, edit and dellete records. List custom m settings havve their own instance meth hods to allow easy access tto cached vallues. // retur rns all lis st hierarch hy values Map mapC Codes = ISO O_Country__ _c.getAll( ); 1
cuustom-settings Jeff Do ouglas & Wes No olte
93
// / display the ISO co ode for Afg ghanistan System.debu S ug(mapCodes s.get(‘AFGH HANISTAN’).ISO_Code_ __c);
Hieraarchy Custom m Settings Hierarchy H custo om settings alllow you to perrsonalize your applications for f different prrofiles and/or users. The in nterface has baked-in logic that t drills dow wn into the Orrg, profile, andd user ( upon tthe current user) and returrns the most specific or lo owest value in the level (based hierarcchy. Hierarchy H custtom settings are extremelyy useful for tthose “one off” o occasionss. For instancce, suppose yo ou want to auth horize your saales teams to b be able to offerr a specific discount to custtomers. You m might set up an n Org-wide cuustom setting o of a 1% discouunt that everyo one is authorrized to offer. Now, of courrse, you have a set of high-p producing salees people that are in their own o profile an nd are able to offer a 5% discount. d How wever (and heree is the “one off”), there is i that one salees person in th hat same profille that has lobb bied the VP of Sales to be aable to offer a 15% discouunt. With hierrarchy custom m settings youu can accomm modate all of these scenarrios. After A you’ve sset up your custom c settinggs and added your fields, you can selecct the Manag ge link on thee custom settin ngs page to ad dd, edit and ddelete values fo or the entire O Org, a specifiic profile or inddividual users.
Figure 2 - 223. Hierarchy seeting with 1% Org O discount and d settings for thee Standard Emp ployees profile and a a specific usser.
Developers D caan programmaatically accesss hierarchy cuustom settinggs based upon n the runnin ng user and reeturn their mo ost appropriatee value (Org-w wide, profile or o user) in formula fields, validation rulees, Apex code and the Force.com Web Serrvices. Y You can onlyy access hierarchy custom m settings in formula fieldd and vvalidation ruless. List custom settings are so omewhat limiteed and not avaailable ffor formulas orr validation rulles. The T generic syn ntax for using a hierarchy cuustom setting in n a formula fieeld is: {!$Setup.Cu ustomSettin ngName__c.C CustomFieldName__c}
94
Salesforce Handbbook
Figure 2 - 24. Using U a hierarch hy custom settin ng in a validatio on rule.
Monitoring M yyour Org Salesforce.ccom provides some level of insight intto the platform m with various debug scrreens and job qqueues. Deebug Logs For applicaation developm ment, the debuug log is your b best source of information to o uncover wh hat is actually ttaking place on n the platform. The debug lo og records dataabase operations, debug staatements, warn nings, system processes, p and d errors that occur when exeecuting a transsaction or wh hile running uunit tests. Thee platform gen nerates a debuug log every time a user eexecutes a traansaction that is included in the filter criteria. You can specify to geneerate debug loggs for any useer on the platfform to help trrack down issuues with particuular user or pro ocesses. Em mail Logs Email logs provide access to all emails sent and receiived through the t platform fo or the last 30 days. The logg files containss both to and from f addressees, date and tim me sent or receeived, the sallesforce.com uuser and any asssociated error information. Lo ogin History This log displays the last 20 user loginss (successful an nd failed) via browsers, b SAM ML, APIs, Reemote Access Clients and paartner productts. You can alsso download the t login historry for the lasst six months. Viiew Setup Aud dit Trail The setup audit trail traccks recent setuup changes th hat administrattors have madde to your Orrg. The last 200 changes are displayed d by deefault but you can download d a CSV files ccontaining all changes for the last six months. m The lo og tracks a w wide range of changes includding App Jeff Do ouglas & Wes No olte
95
Exchange installs, security modifications, password changes, new fields added to objects, changes to the user interface and import wizard usage, just to name a few. Time-Based Workflow Queue This queue displays any time-dependent actions that were created by workflow rules. You can filter and view pending actions for more information plus cancel them if necessary. Scheduled Jobs The All Scheduled Jobs page displays all jobs scheduled by users including analytic snapshots, Apex jobs, emailed reports and dashboard refreshes. With the right permissions, users can also delete scheduled jobs. Outbound Messages An outbound message is a workflow, approval, or milestone action that sends information to an external service via a SOAP message. The Outbound Messaging Delivery Status page displays messages queued for delivery plus failed messages with delivery debug and retry information. Apex Job Queue The Apex job queue lists all Apex jobs that have been submitted for execution. This includes jobs fired from Apex @future methods, Scheduled Apex, Batch Apex and Apex sharing recalculations. Import Queue Displays the details of data imported into your Org and allows you to cancel a pending import. Mass Email Queue Displays the status of scheduled mass emails and cancel them if necessary. Case Escalation Rule Queue This queue displays any time-dependent actions that were created by case escalation rules. You can filter and view pending actions for more information plus cancel them if necessary. Entitlement Process Queue This queue displays any time-dependent milestone actions that were created by entitlement processes. You can filter and view pending actions for more information plus cancel them if necessary.
96
Salesforce Handbook
Bu ulk Data Load d Jobs This page ddisplays the staatus of currentt and recent buulk data load jo obs created byy the Data Lo oader and otheer Bulk API cliient application ns. The page aalso displays yo our Org’s currrent batch im mport quota forr the current 24-hour period.
Go oogle Integ gration It’s no surp prise that salessforce.com and d Google havee a close relatiionship given ttheir long hisstory of compllimentary prod duct offerings and the fact th hat both domiinate the cloudd space. A nuumber of Goo ogle services are baked intto the Force.ccom platform m allowing youu to take 1 advvantage of theem without leeaving the saleesforce.com en nvironment . Administrators A s typically need to simply activate these feeatures to get started s using th hem. These servvices are design ned for busineess users and require a Goo ogle Apps account. The T Google Ap pps domain you set up in salesforce.com s m must be the domaiin you registeered with Goo ogle for yourr company ratther than consumer account a (i.e., Gmail.com). G Ad dd Google Do ocs to Salesforce.com When activvated, the Add Google Docs to Salesforce..com service alllows you to co ollaborate and share Googlle docs with an ny user in yourr Org; use Goo ogle Docs & Attachments A ass a related listt on any salesfforce.com reco ord to create, edit, e or view G Google docs an nd easily assocciate them to a record; use the “Add Goo ogle Doc to Saalesforce.com”” browser buttton to associatte Google do ocs with salesfforce.com reco ords even wheen not currenttly working in the salesforcee.com UI; cen ntralize the addministration of o Google doccs by allowing salesforce.com m, Customer P Portal and Paartner Portal ussers to add Go oogle docs to Salesforce S CRM M content. Go oogle Docs T Tab When activvated, the Goo ogle Docs tab allows a you to aaccess all of yo our Google do ocs from a sim mple docs home page with hout leaving the t salesforce..com UI. Thee home page not only dissplays all docuuments, spread dsheets and prresentations th hat you have created c by all docs that havve been shareed with you. You can even n create a Go oogle doc fro om within thee tab and asssociate it to an ny record in sallesforce.com with w a few simp ple clicks. Gm mail to Salesfforce.com Gmail to Salesforce.com allows you to seamlessly rouute emails sen nt from the Gm mail UI to reccords in salesfforce.com. On nce set up, thee Force.com p platform will generate g a uniqque email address for yourr account. Simp ply add this em mail address to the bcc field of o your outgoiing Gmail meessage and it w will be routed d to salesforce.com and creaated as an actiivity on match hed leads, contacts, opporttunities, and otther records th hat support acttivity history. Gmail G to Salesfforce.com wo orks for chats aas well. 1
go oogle-services Jeff Do ouglas & Wes No olte
97
Gmail Buttons and Links Gmail Buttons and Links is a quick and convenient way to use Gmail from within the salesforce.com UI. The service adds a Gmail link next to email fields on all records and a Compose Gmail button on the Activity History related lists for leads and contacts. When you click one of these two buttons, the salesforce.com UI pops up a new window, automatically logs you into your Gmail account and populates the To field with the correct email address. Google Talk Sidebar Component If your company uses Google Talk for instant messaging, you can enable the service to display below the sidebar search on the left pane of the salesforce.com UI. The Google Talk interface allows users to stay within the salesforce.com environment and allows them to toggle it off, on or even expand into its own window. Chats for contacts and leads can also be easily logged as an activity their records. Google AdWords For marketing efforts, Salesforce for Google AdWords connects salesforce.com with Google AdWords, allowing you to track the effectiveness of your online advertising investments. When a visitor clicks on your Google ad they will be directed to your website that hosts a Web-to-Lead form. When the visitor enters their information into the Web-to-Lead form, a lead is created in your salesforce.com Org. Leads that originate from Google AdWords have a Lead Source value of “Google AdWords” and an activity record that shows the Google AdWords campaign, ad group, ad headline, and keyword that drove the lead to your website. You can then track the effectiveness of your advertising with a Google AdWords dashboard and several Google AdWords reports are pre-built in salesforce.com. There are also a large number of Google-related apps on the AppExchange for additional functionality such as synching contacts and calendars, integrating with Google Maps and using Chatter with Google Alerts.
Working Remotely Force.com Connect for Microsoft Office This product integrates Microsoft Office with salesforce.com and has add-ins for both Word and Excel. The Word add-in is used for creating mail merge templates for use with the salesforce.com mail merge utility. You create Word templates that contain salesforce.com merge fields, upload the template and then simply choose the template when running the mail merge from the salesforce.com UI. The Excel add-in is used for delivering salesforce.com reports into Excel so that you can customize the report with formulas, charts or pivot tables, for example, to extend the reach of your salesforce.com data. These reports can then be distributed, analyzed or archived depending upon your business processes.
98
Salesforce Handbook
Salesforce for Outlook In Winter ‘11, salesforce.com released Salesforce for Outlook, a huge upgrade from its previous product called Connect for Outlook. Salesforce for Outlook is a free, fully supported Outlook add-in that provides the following functionality: •
Send out-bound email and associate it with a contact in salesforce.com
•
Attach in-bound email to a contact in salesforce.com
•
Create support cases from in-bound emails
•
Synchronize contacts between salesforce.com and Outlook
•
Synchronize calendar appointments between salesforce.com (as events) and Outlook
•
Synchronize to-do items between salesforce.com (as tasks) and Outlook
•
Upload email attachments to salesforce.com
Force.com Connect for Lotus Notes Connect for Lotus Notes is an add-in for IBM® Lotus Notes® that allows you to interact with salesforce.com conveniently from Lotus Notes. It offers the following functionality: •
Use leads and contacts from salesforce.com as email recipients
•
Associate email messages to accounts, assets, campaigns, cases, contacts, contracts, custom objects, leads, opportunities, or products in salesforce.com.
•
Create support cases from in-bound emails
•
Synchronize calendar appointments between salesforce.com (as events) and Lotus Notes
•
Synchronize to-do items between salesforce.com (as tasks) and Lotus Notes
•
Upload email attachments to salesforce.com
Force.com Connect Offline Connect Offline is a client application that provides browser-based access to a subset of salesforce.com data while disconnected from the internet. You can use Connect Offline to view, edit, create, or delete accounts, activities, contacts, opportunities, leads, and custom object records (including relationship groups). Administrators control a user’s access to data with “briefcase configurations”. These profile-specific configurations determine which actual records and types of records are available offline for specific groups of users. When online, users sync their records with salesforce.com to ensure that everyone has access to the latest information. There is also a built-in conflict resolution tool in the event that updates conflict with newer versions of the same record.
Jeff Douglas & Wes Nolte
99
Programmatic Development Tools & Strategies
I
n previous chapters you’ve seen how salesforce.com removes a lot of the cost and complexity around software development infrastructure. Now imagine that as a developer you never need to worry about database connectivity, whether the web stack is up or whether there may be servers that need to be bounced before taking an improvement live. This would leave you with a lot more time to do the “real work”. Wouldn’t that be great? Salesforce.com’s Platform as a Service (PaaS), also known as Force.com, does exactly this and that’s only the tip of the iceberg. Force.com is comprised of a set of tools, APIs and programming languages that enable administrators, developers and architects to build anything from small- to large-scale enterprise applications quickly, and without compromising quality. They have catered for IT personnel at all levels providing tools and support specific to those roles. Of course tools work better with processes to support them and salesforce.com together with a few community evangelists have grown a number of best practices that govern areas such as unit testing strategies; collaborative development; object-oriented principle implementations, and much more. In this chapter you’ll learn more about the tools and strategies required to build, test and deploy applications on Force.com. Not only that but we’ll advise which tools are required when and provide usage best-practices where required.
A New but Familiar Development Infrastructure Traditional software development tools and processes are mature and have been widely accepted. Salesforce.com has taken what might be considered the best of these approaches and tools, and built their platform on this sturdy foundation. That’s Old School In a simple traditional development topology, one or more engineers develop on desktop computers whilst sharing and integrating code through a Version Control System (VCS). Next, code is tested in a Quality Assurance (QA) environment, and then moves into a User Acceptance Testing (UAT) environment. If the software successfully passes each stage it is finally packaged and deployed to a production environment.
Figure 3 - 1.. Typical Softwaare Developmen nt Topology
Develloping in the Clouds Force.com F usees a similar settup but we fin nd that insteadd of having ouur environmen nts sit within n the usual hardware infrastruucture they are now cloud-b bound. In figuure 3 - 2 we see that develo opers still create code locallyy, but something to note is that code isn n’t compiled lo ocally. Instead d it is deployeed (in real-time by default) to t developer eenvironments, which compiile the sourcee-code and form m our develop pment runtimee environmentss. D Developers caan also create and edit appllications directtly in their bro owser tthereby leap-frrogging the local developmeent step, but this t is generallly not aadvised for largge applicationss and/or collab borative develo opment. Thankfully T youu still have thee option of co ommitting codde to your favvorite VCS andd it is generaally advised. A packaging sttep is not reqquired with thee Force.com platform p as w we can deployy directly into aany developer and/or produuction environm ment.
102
Salesforce Handbbook
Figu ure 3 - 2. Force.ccom Developmeent Topology
In figure 3-3 we’ve no oted an altern native setup w with a build manager han ndling the deployments direectly from the VCS reposito ory. Using buildd managers caan be a neat prractice for a number n of reassons includingg predictable deeployment rhyythms, code quuality checks, aautomated tessting and buildd/deployment history.
Figure 3 - 3. Alternative Force.com Devellopment Topolo ogy
Jeff Douuglas & Wes Nollte
103
From F what wee’ve seen, devvelopment maanagers usuallly employ a combination c o of the metho ods shown in figures 3 - 2 and 3 - 3 wiith developerss deploying diirectly to deveeloper enviro onments and ussing build man nagers to deplo oy code to theiir production environment. e A As you’ll see laater, Force.com m projects can n be deployed using Apachee Ant. T This means thaat server applications such aas Hudson (httpp://hudson-ci.org rg) can b be used to man nage and deplo oy code. The Im mportance off Metadata In I previous chaapters you saw w that metadatta plays a very important role in salesforcee.com. It desccribes the structure of objeccts and their fieelds, as well ass the page layo outs associatedd with them. In fact, metaddata describes many more sttructures in Fo orce.com but what w you migh ht ask is, “Why use metadaata at all?” Metadata M is a ssimple lightweiight language (based ( on XM ML) for describ bing the structuure of salesfo orce.com and F Force.com devvelopment arttifacts. Later o on you’ll see th hat Force.com m code can bee organized intto projects, wh hich are essenttially groupings of metadata files. Instead o of the traditio onal developm ment approach h of code-com mpile-package-ddeploy, with Force.com F youu only need to t code. The m magic here is that t the metad data is zipped aand transferred to the Forcee.com serverss (much fasterr than uploadin ng compiled co ode) where it iis unzipped and compiled on n your behalff. Not only is tthis super fast,, but your chan nges are immeediately availab ble through anyy web browser, and there’s no downtime at all!
The Right R Tool for the Right Job Now N that youu’re equipped with an overrview of how w your cloud-b based develop pment networrk might be orrganized, it is im mportant that you learn: •
What Forcee.com develop per tools exist
•
When it is aappropriate to o use specific to ools
•
How to usee these tools
In I this section n we will disccuss everythin ng you need to create, tesst and deploy your Force.com code wh hilst being min ndful of the above a points. We will also touch on deesktop m that you’ll need n when anallyzing and mo onitoring your code, applicaations or areass of Force.com as welll as the variouss support optio ons available to you. C Certain tools overlap severaal developmen nt tasks, and some develop pment ttasks overlap each e other. It’ss for this reaso on that the firsst two points aare so iimportant wheen discussing development d to oolsets. Develloping Appliccations on thee Force.com Platform P Creating C code iin any modern n language is ussually done thrrough an Integgrated Develop pment Enviro onment (IDE)) that offers a number of advantages a oveer coding thro ough a simplee text104
Salesforce Handbbook
editor or sometthing equally archaic. By th he end of th his section youu’ll know whiich IDEs Fo orce.com offers and when to use each of th hem. Fo orce.com App p Builder Too ols Salesforce.ccom has created one of the best browser--based develop pment environ nments in thee world and it delivers most,, if not all, of the t core functiionality you’d expect from a desktopbased IDE. Theere are two waays to access the t functionaliity, each of which w presents a slightly diffferent experieence. The first w way involves cliicking Setup -> Develop p as a logged in i user. From there you havve access to eaach Force.com m area of develo opment, nameely: •
Apex Classes
•
Apex Triggers
•
Components
•
Pages
S-Controls are now dep precated and aall the functio onality they prrovided is now availab ble through Viisualforce pagees.
on presents yo ou with a list of code units of that type in your y Org, as w well as the Each sectio op ption to edit th he list items, an nd - in the casee of Apex Classes, Components, and Pagees - create new code units. We won’t go into the languuage specifics right now (wee’ll cover each h language and coding com mponent lateer) but essenttially touch o on key areass of the devvelopment en nvironment to ddemonstrate th heir strengths. In figure 3 – 4 you can seee the list of Apex A classes th hat are created when you sign n up for a new Developer Edition (DE) Org1. Notice the link labelled Edit on the t left and th he button lab bel New at the top of the list..
Figure 3 - 4. The T initial list off Apex Classes iin a DE Organizzation
1
Developer-edition D n-signup Jeff Douuglas & Wes Nollte
105
If I you click thee New button you y will be presented with a screen similaar to the one shown in figuure 3 – 5. We’ve taken the liberty of decclaring a class and a single member m meth hod in order to demonstratte syntax highlighting. It has other featurees such as marrking syntax eerrors, search h and replace, aand tabbed ind dentation (nott such a simplee feat in a brow wser window). You’ll Y also nottice a button laabeled Versi ion Setting gs. You will only o need to m modify the vaalues on this tab if your class c needs to maintain speecific behaviorr not supportted in subseqquent releases.
Figurre 3 - 5. Creating g an Apex Class with Force.com m App Builder Tools T
Y You might havve already notticed the two save buttons, which might seem cconfusing. Thee difference is that the Save e button will saave any changees and ddrop you backk at the list-viiew page, whille the Quick Save button n will ssave your cod de and keep you y on the sam me page. Forr keyboard sho ortcut junkies, pressin ng Ctrl/Cmd-S will also qu uick save. Coding C Apex C Classes and Trriggers in this environment e o offers very sim milar experiencees but there are a some surprrises when devveloping code in i the Pages aand Components sections. It’s I in these secctions that youu can create an nd modify the pages (or pagge componentss) that your users u interact w with, and here the t browser ed ditor offers som me bonus feattures. In figuree 3 – 6 we’ve started codingg by typing an n open angle bracket b and havve been presented with a po op-up ns. list of code completiion suggestion
106
Salesforce Handbbook
Fig gure 3 - 6. Creatiing a Visualforce page with Forrce.com App Bu uilder Tools
This auto-ccompletion feaature is superb for beginnerss and is comprrehensive for th hese code un nit types. In adddition to this you’ll y notice an n extra button labeled Compo onent Reference at thee top of the p page which lin nks through to o a library doccumenting thee language com mponents alo ong with workiing examples. The secondd way to accesss the Force.co om App Buildeer Tools devellopment enviro onment is byy enabling Dev velopment Mode; M this can n be found by clicking Setu up -> My Pe ersonal In nformation -> Perso onal Information, cllicking Edit t and then checking De evelopment Mode as show wn in figure 3 – 7.
Fiigure 3 - 7. Enab bling Developm ment Mode
This featurre allows you to code and view v the comp piled results within w the samee browser window. It offerrs all the featurres we mention ned previouslyy but adds a reaal-time view off the code you’re amendingg or creating. In figure 3 – 8 you can seee that the devvelopment envvironment Jeff Douuglas & Wes Nollte
107
(also known k as the Development Mode Footerr) is unobtrusivve, and more than this it haas the compo onent referencce handy as weell as offering the t expected assistance when n syntax is inco orrect or if particular p depen ndencies are missing. m For alll these reasonss we proclaim this to be “Kiing of Beginn ner Development Tools”.
Figure 3 - 8. The Development Mode Footer
From F our commentary it’s quuite obvious th hat the Develo opment Mode Footer F is superrb for beginn ners, but somee would conteend that it’s allso just as goo od for quick changes. c We w would disagreee arguing thaat a good devvelopment inffrastructure loses a lot of value v without good develo opment practicces. We would consider somee of these to be: •
All changess must be testeed, and this usuually involves several test-ph hases.
•
All changess should be committed to a VCS V (at very laatest) prior to deployment. d
•
All changess should be vallidated and acccepted as correect by a colleaggue.
•
All testing should be valid dated and acceepted as correcct by a colleaguue.
These T principlles are especially important if you’re wo orking in deveelopment team ms as this in ncreases the p potential for overriding valid v code or working with h the wrong code version. IIt is easy to ovverwrite code in these brow wser-based envvironments and this h has the potenttial to cost ho ours or even ddays of work. Bugs can oftten be iintroduced wh hen making “quick” changees through th he browser ass little tthought goes in nto their impleementation.
108
Salesforce Handbbook
Fo orce.com IDE E Developerss will be pleassed to learn th hat they can usse the Eclipsee IDE to codee with the 1 help of the Forrce.com IDE plug-in p . The Force.com ID DE is a definiitive interface for rapid devvelopment, tessting and deplloyment of cod de on the Force.com platforrm. It also pro ovides the ability to exploree your salesforrce.com schem ma, as well as ttools to execuute database quueries and execute short co ode scripts on the t fly. The th heme of this seection is “How w to create codde” and as succh we’ll only eexplore that feaature for now. Once the IIDE is installed you will havve a new devellopment persp pective available to you. Op pen this up by clicking Wind dow -> Open n Perspecti ive -> Othe er -> Forc ce.com at wh hich point youu’ll be presenteed with a pagee detailing info ormation and other resourcees for the Fo orce.com IDE..
Figure 3 - 9. The Force.com m IDE
To get starrted coding, riight-click in th he “Package E Explorer” wind dow and click New -> Fo orce.com Pr roject. If you’ve y signed up for a DE E (or any) Orrg you’ll havee a set of creedentials that n need to be enttered in this wiindow. If you haven’t signed d up yet, click the Sign Up p Now! link to o the right of the t “Environm ment” drop-dow wn box. Many peop ple get confuseed, as they’re n not sure what the t difference b between a “Security Token” T and a “P Password” is. IIn Force.com jargon a securitty token is a randomlyy generated alph hanumeric strin ng that adds strength to your ccredentials in conjuncttion with your password. If yo ou don’t have a security tokeen you can get a new one emailed to t you by loggging into your target Org an nd clicking Setup -> > My Person nal Inform mation -> Reset R My Se ecurity 1
fo orce.com-ide-dow wnload Jeff Douuglas & Wes Nollte
109
T Token -> Re eset Securi ity Token. It’s also impo ortant to note tthat if
yyou change yo our password, a new securitty token is issuued invalidatin ng the p previous one. IIf you’re havin ng trouble loggging in and yo ou’re certain that t your usern name, p password and security token n are correct tthen the likelyy culprit is thaat the w wrong environ nment type hass been selectedd. Most develo opers will only work w with “Productiion/Developeer Edition” or “Sandbox” Orgs, O so tryingg each o of these shoulld solve the prroblem. As an n additional haandy tip, if yo ou use h http://logi in.salesfor rce.com to o login then n the first opttion is ccorrect, whereeas a login URL of htt tp://test.s salesforce.com m means that youu’re developingg in a sandboxx. Clicking C the Ne ext button in the t wizard pressents a page sim milar to that in n figure 3 – 10.. Here we enccounter metadaata once more, selecting thosee components you’d like to pull into your prroject. You caan select a defaault set of comp ponents, custom mize the selection or choose none. n
Figure 3 - 10. Selecting initial project co ontents 110
Salesforce Handbbook
A lot of w what you see in this windo ow might be unfamiliar att this point (ee.g. Apex Co omponent, Ap pex Trigger, Sttatic Resourcee) but you can n revisit this page p at any tim me during devvelopment and customize which w metadatta componentss you’d like to o work with in n Eclipse. Th he important cconcept here is that Eclipsee wants to do ownload a sub bset of your F Force.com application in tthe form of metadata into o a local pro oject, thereby setting up a two-way sub bscription to aapplication chaanges. The defaultt option is finee for now so yo ou can click Fi inish to com mplete the wizaard. Looking att figure 3 – 11 you’ll see that we’ve expanded our projecct and openedd the class thaat we created tthrough the Fo orce.com App Builder Tools IDE.
Figure 3 - 11. Viewing V an Apexx class
On the leftt, the project is i laid out in a neat folder sstructure, grouuping code uniit types in theeir particular ffolders. On thee right we havve the code ediitor where youu’ll notice thatt the code layyout and highliighting is conssistent with wh hat we saw beffore. At the bo ottom of the rright pane you can flip bettween the “So ource” view – where you addd actual codee – and the “M Metadata” vieew that shows how Force.com describes th his class, as dem monstrated in listing 3 – 1. Listing 3 - 1. Example of o Apex Classs Metadata > 20.0 Active
To create new code in the Force.com IDE right--click on any folder or filee in your Fo orce.com projeect and highligght New. The available optio ons are shown n in figure 3 – 12 and as you can see theere’s a mixturre of program mmatic develop pment and deeclarative proggramming eleements. Feel free to experiment with creating declarative eleements such aas custom objects as this will givee you feel forr how they’re represented uunder the hood. Beyo ond experimen nt though, we’dd advise steerin ng clear of editing these files by hand as it’s erro or prone, and can be tough to debug if ssomething goes wrongg.
Jeff Douuglas & Wes Nollte
111
This T chapter w will only cover the programm matic elements and since the creation wizarrd for each element is a litttle different, th hese will be discussed in laterr sections.
Figure 3 - 12. Force.co om IDE “New” Menu
Earlier E we high hlighted how integral metad data is to the platform and d how a Forcee.com project is a collection n of metadata files. To expan nd on this, eacch time you create or save a file in the Fo orce.com IDE E the metadataa representatio on of that filee is zip-archivved and sent tto the Force.com servers fo for compilation n. The result of o the compilattion is then retturned to yourr IDE to let you y know wheether it was suuccessful or wh hether there w were problems encountered. A All of this is achieved at brreak-neck speeeds via the Meetadata API, wh hich will be diiscussed at lenggth in a later chapter. T This process is similar to what w is usually termed deplo oyment, althouugh in tthe Force.com m programmingg paradigm th hat name is reeserved for an nother p process. Deplo oyment in the Force.com sen nse of the worrd will be disccussed llater in this chaapter. After A working w with the Forcee.com IDE forr some time yo ou will realize that t it’s much richer than th he browser-baased version offfering code completion forr Apex classes,, system classees and schem ma objects; veerbose syntax and compilaation error m messages; quicck code naviggation includiing keyboard shortcuts (ccourtesy of Eclipse); E betteer code orgaanization and VCS 112
Salesforce Handbbook
inttegration. Therre are also feaatures that enab ble deploymen nt, analysis and d testing. It is for these reaasons that thiss IDE is the only true pro oject developm ment tool availlable to us. Luuckily it’s excels in this rolee. As you mo ove from a beeginner through gh to an interm mediate, and fiinally to a guru Forcee.com developeer you’ll use th he Force.com IDE I more, an nd in most cases will stop s using thee browser-baseed IDE complletely. That’s n not to say the Force..com IDE is a tool for aadvanced deveelopers, more that the browser-baased IDE is a beginner-to-in b termediate levvel tool. If you’d likke more detail there is an offficial Force.com m IDE article1, as well as a ffrequently 2 askked questions (FAQ) docum ment and the IDE release n notes3. After you’ve y gotten your feet weet we’d suggestt checking them m out. An nonymous Blo ocks Anonymouus blocks provvide a way to execute Apexx code on thee fly. The codde that is executed in anon nymous blockss is not persistted in the way that you’ve seeen in the IDE Es; instead it is i lost when yo ou “close” the anonymous bllock. Because th hey execute im mmediately and d create debugg logs in their wake they aree valuable wh hen performin ng analysis, exxecuting data fixes on the fly, experimeenting with cchunks of fun nctionality, run nning batch jobs, or scheduliing jobs. There are tthree ways to access a the anon nymous block functionality namely: n •
System Log Console
•
Force.ccom IDE
•
A Web Services API call
Strictly speeaking the third method sitts outside of Force.com an nd as such wiill not be disscussed here. In a nutsh hell the system m log consolee is the brow wser-based meethod used to o execute anonymous bloccks, and the Fo orce.com IDE E has a pane th hat delivers thiss functionalityy from the desktop. Syystem Log Co onsole To access the system lo og console yo ou need to logg into your Org O and then click the
Sy ystem Log lin nk4. Figure 3 – 13 shows thee System Log C Console windo ow that pops up p.
fo orce.com-ide-doccs fo orce.com-ide-faq 3 fo orce.com-ide-reln notes 4 sy ystem-log-consolee-docs 1 2
Jeff Douuglas & Wes Nollte
113
Figurre 3 - 13 System Log Console (P Pilot)
Clicking C in thee input area in the top left corner c of the w window will po op up an addiitional window w that allows you to enter the code you wish to run. IIf you click th he Execute b button and yo our code runs successfully eaach of the windowpanes willl populate with h a different tyype of inform mation concern ning your script execution.
114
•
Logs - A line will appeear for each ap pplication transaction executted. Clicking o on any of these w will populate th he other paness with informattion about that transaction.
•
Stack - A top-down naavigable tree off items e.g. DM ML operations, trigger invocaations or metho od calls, as theyy are called in n the process o of executing yo our code. Thee pane below is tthe back trace, or bottom-up p view, of the ssame tree.
•
Executio on Log - This is similar to th he old bare-bon nes debug log and system co onsole output, b but with some important en nhancements. O Options in th his pane allow for a number o of filtering optiions making th he output easilyy readable.
•
Source - Displays the executed e sourcce code or mettadata definitio ons of items ussed in the execuution process. The pane is context sensitivve in that seleccting items in other panes filteers the output..
•
Executed d Units - A grranular view of the resources consumed byy individual prrocess items. Buuttons at the bo ottom of the taab allow you to o filter out unw wanted inform mation.
•
Limits - Shows the lim mits involved in n your code exxecution (by naame) as well ass how close you are to hitting them. Salesforce Handbbook
Besides beiing used to run n scripts as An nonymous Blo ocks the System m Log Consolee can also be used as a full fledge debuggging tool. As shown later youu can enable debugging d on a per user basis; if you’ve ddone this for your y currentlyy logged in useer and keep th he System Logg Console op pen during youur developmen nt and testing, log entries willl populate thee Logs pane. E Each entry willl detail every ttransactional event e during yo our application n interactions. This T is incrediibly useful in testing either user-flows orr the smallest application un nit. Using thiss tool you can n pinpoint eluusive bugs or eeven just narro ow down ineffiiciencies within n your applicattion. Fo orce.com IDE E The Force.com IDE pro ovides a cut down d version of the functio onality providded in the System Log Con nsole through the t “Execute Anonymous” A vview.
Figure 3 - 14. Execute Anonymous A in F Force.com IDE
In figure 3 – 14 we’ve exxpanded this pane p and run tthrough the prrocess of enterring some Ap pex code and clicking Exec cute Anony ymous. The llabels and pro ocess here aree a touch diffferent but thee result is similaar to that of th he execution lo og pane in the System Log Co onsole. nality is availab ble through thiis interface alth hough the help p for each Similarly filltering function op ption isn’t as exxplicit as in the web interface.. The choices aare quite straigh ht forward andd with you beiing able to set the verbosity (“+” ( is more veerbose while “-” is less) for each e “Log categgory”. Veersion Contro ol Unless youu’re a developeer working in isolation then n version conttrol is essentiall. Even if you are the sole developer verssion control syystems work ass effective backkups. Version co ontrol system are used to track changess in files assiggning each suubsequent change an increm mental version n number e.g. the initial file version migh ht be 1, the firrst change wo ould then beco ome version 2. 2 Typically th hese systems p provide functio onality to avoiid and/or meerge conflictingg changes, theereby allowing teams of developers to workk on overlapping source code. Additionallly these system ms record a hisstory of changges allowing co omparisons or reversion to a historical so ource code staate. This has laarge advantagees over traditio onal backup syystems as
Jeff Douuglas & Wes Nollte
115
the access is providded in real-time, usually with h line-by-line ccomparison to ools, and allow ws the develo oper to step baack further than n a single versiion. Force.com IDE The T Force.com m IDE providees a mechanism m to compare a local and seerver-side versiion of any fille, although in reality this isn n’t suitable as a full-blown V VCS. As an exaample consideer that you haave two developers workingg on the samee Apex class C ClassA. Each h developer in nitially has th he same versio on of the classs in their locaal project. Thee first develop per then createes the metho od doAction( ( ) in a shaared sandbox. Later the seccond developeer adds in a seecond metho od getBoolea an( ) withou ut first fetchin ng the updatedd code from th he server. Wheen she saves the t class she’ll get an error in n the IDE statiing: Conflict C fo ound while e preparing g to save ‘ClassA.cl ls’ to server. Remot te instance e has been n updated since last t save or sync. Use the Synch hronize Per rspective to t resolve the confl lict. Right-clicking R on the probleem file and th hen selected F Force.com -> - Synchro onise with Server briings up a diaalog box asking if you’d llike to the Team T Synchron nizing perspeective. Clickingg Yes, a new view v will appeaar with a little two-way red arrow a indicatin ng the
confliccted file. Doub ble click the filee to enter the “Text “ Comparee” mode, which h will look sim milar to figure 3 - 15.
Figure 3 - 15. Text Comp pare in Force.co om IDE
The T options reelevant to thiss type of confflict are availab ble in the top p-right hand co orner, offerin ng to overwritte the highligh hted local codee, with the so ource code on n the server. In n this situatio on however yo ou’ll want to merge m the chan nges into one file, so select the doAction n( ) metho od in the right p pane and copyy-paste it into the t left pane. SSaving the chan nge you’ll noticce the IDE doesn’t d yet kno ow the conflict has been reso olved. Right-clicck on the confflicted file and select Apply y Project t to Server. The file is no ow saved and you can returrn to the Forcee.com perspeective.
116
Salesforce Handbbook
When you move from any a perspective back to the Force.com peerspective the “Forcee.com Start Paage” is openedd and given foccus. This pagee is useful but this behavior b isn’t always desiraable. To prevvent this open n Eclipse preferences and click Force.com -> Start t Page and deselect Display when Force e.com Persp pective is opened.
The “Synch hronize with Server” feature can be used fo or incoming, outgoing o and cconflicting changes, as well as any combin nation of all thrree types. Su ubclipse There are a number of version contrrol server app plications on the t market an nd in this secction we’ll disscuss one of the t best, nameely Subversion n (SVN). If yo ou don’t havee an SVN serrver installed yyou can down nload the softw ware for free ffrom http://suubversion.apacche.org or you can use one of the on-dem mand SVN servvices such as G Google Code. Subclipse iis an SVN clieent that can be installed as a plug-in for Eclipse (availaable from htttp://subclipsee.tigris.org) andd which allows youur Force.com proj ojects to work witth an SVN serveer1. Working w with Force.com m and Subclipsee usually includdes: •
Copyiing your sourrce code to the SVN serrver. The cop pying process is called “com mmitting” and the t area where the code existts is called the “repository”.
•
Devellopment team m members will w import th he project co ode and markk it as a Forcee.com project by right-clickiing on the project and seleecting Force. .com -> Assi ign Force.c com Nature. .
•
Devellopment proggresses with engineers e reso olving conflictts, importing, merging, brancching, and taggging code.
•
The ccommit historry allows codee comparisonss and the abillity to revert to earlier versio ons of the sourrce code.
The topic of version co ontrol has tran nscended technical debate and a for some has even become philosop phical. The go ood part is that tools such as SVN and Subclipse S are platformind dependent so once you’re exxperienced thee skills are tran nsferrable. Thee bad news is that each has several bookks detailing how w to gain said experience. e Although the t details of forming a verrsion control strategy s are beeyond the scope of this t book it iss important to o note that Suubversion doesn’t work particularlyy well with larrge files. If a developmentt team is workking with metadata or o source code files larger th han 1000 lines you may have difficulty combiningg the changes. The value of version con ntrol systems is worth the ssteep learning curve. Signifiicant time n be saved (wh hen used prop perly) because of the version ning history, an nd tools to maanage and can meerge source co ode. Additionally it is posssible to have o other tools pllug into a souurce code 1
fo orce.com-ide-svn Jeff Douuglas & Wes Nollte
117
reposittory offering valuable serviices such as cchecking codee quality, feed ding informatio on to project managemen nt suites or automatically a b building comm mitted changees into produuction enviro onments. Deplo oying Applicaations on the Force.com F Pllatform Deployment D on n the Force.co om platform can c be summaarized as the process p of miggrating metadata from one Org to anotheer. Usually this feature woulld be used wh hen promotingg code from a sandbox or D DE Org into a production en nvironment. The T Metadata API facilitattes deploymen nt using eith her the Forcee.com IDE o or the Force.com Migration n tool. The Fo orce.com IDE E deployment p process is the simpler of th he two using a deployment w wizard. The Force.com Migrration Tool is a more advancced tool (at leaast for those without w Apach he Ant experieence) but its ow wn set of advan ntages. Assuming A you’’ve reached thee point where you’ve createdd and tested a collection of ssource code files, f the next step to deplo oy them to a QA, UAT orr production environment. We’ll demon nstrate the step ps necessary to o achieve this with w each tool.. SSalesforce.com m won’t allow you y to deploy cchanges to an Org unless thee total uunit test coverrage for all cod de in that Orgg is 75% or ab bove. Not onlyy does tthis ensure a high quality of o deployed co ode, it goes a long way tow wards m making sure th hat tenants on their platform m don’t write code c that negaatively iimpacts their neighbors. n Force.com IDE In I the IDE seleect the files yo ou wish to deplloy (hold CTRL L/CMD while clicking c for muultiple selectio ons). You can n also select entire e folders, or the projecct root folder. Right-click o on the selectio on and choosee Force.com m -> Deploy y to Server r. The T first page o of the deploym ment wizard willl appear and yyou’ll need to enter e your usern name, passwo ord and securiity token for the t target Orgg. The next pagge will allow you y to backup p your projectt and destination environmen nt, the defaultss (backup the target environm ment) are suffi ficient. Page th hree of the wizzard will list the files you are deploying. If yyou’d like to deeploy a subset of the files listed you’ll neeed to uncheckk the unwanted d files. The w wizard color co odes the changges to visuallyy let you know w if a source code file has chan nged (yellow), is new (green),, or has not changed (grey). Clicking on ““Validate Deplloyment” perfo orms a test dep ployment but doesn’t comm mit the changees. Clicking nexxt will attempt deploy your co ode and metaddata. O Often your dep ployment packkages have dep pendencies on other file elem ments, o objects and their fields. If th hese dependen ncies are creatiing issues or yyou’re ssimply perform ming pre-deplo oyment checkss, the Force.co om IDE is thee only ttool through which w you can perform key-w word searches through all off your m metadata.
118
Salesforce Handbbook
If all goes w well, the last page p will notifyy you if the deeployment succceeded, otherw wise you’ll arrrive at a page that details th he failures. Aftter a successfuul deployment your new fun nctionality willl be available iin the target Org. O Deploymen nts can take up p to fifteen miinutes to comp plete because aall current and new un nit tests are ruun as part of th he migration process. p Things that can slow down n deploymentts include a large numberrs of unit teests, large amounts of data in your Org, lots of ffiles, the types of componen nts, record locking, serrver availabilityy and inefficien nt unit tests. Th he Force.com m Migration Tool T The Force.com Migration n Tool uses th he Java-based b build tool calleed Apache Antt to move meetadata and so ource code fro om a directory on a local maachine to a saalesforce.com O Org. This pro ocess is more complex than n using the dep ployment wizaard in Eclipse but salesforcee.com has do ocumented the tool compreh hensively1. The officiaal documentatiion covers eveerything you m might need to use with the tool so a sum mmary shouldd be sufficientt. The tool usees configuratio on files to dettermine which h Org and creedentials to use in the conneection. It also uses a file callled package.xm ml (which you may have no oticed in your Force.com pro oject) to deterrmine what neeeds to be dep ployed. The deeployment becomes highly configurable through custo omization of these files allo owing granulaar control ovver what is dep ployed, where it’s i deployed to o, and even w which unit testss are run. Therre are also configuration filees that can destroy metadataa to the target Org allowing you to perforrm housekeeping prior to any deploymeent. Once the to ool is executed it behaves sim milarly to the deeployment wizaard in that it arrchives the filees, sends them to salesforce.co om for compilaation and postss the results to the t command lline. Ant is a po opular tool and d there are a number n of Javva-based serverrs and applicaations that can n execute and monitor Ant builds. b Using some s of these ttools you can have h deploymeents build automatically on n any VCS com mmits, monitorr the quality off code and gath her build statistics. Hudson was w mentioned in a previous chapter, and besides perforrming the role of con ntinuous integrration server iit supports a number n of pluug-ins that facilitates the t aforementtioned featurees. Some of these t can be found at http://wiki..hudson-ci.org/di display/HUDSO ON/Plugins. Paackages Packages o on Force.com are collectionss of code that can be distrib buted without using the Fo orce.com Migrration Tool or o the Forcee.com IDE. A At a minimuum all you n need is a sallesforce.com O Org and the URL U for the paackage to instaall it. Packagess come in two varieties, maanaged and un nmanaged, each h with its own purposes2. In short un nmanaged pacckages are used to organize code into com mpartments, yyou might thiink of them aas libraries orr templates. For F example th hey work verry well as opeen source 1 2
fo orce.com-migratio on-tool ap pplication-packagges Jeff Douuglas & Wes Nollte
119
projects. Managed packages are typically used d for commeercial productss as they hidde the applicaation source co ode from the package p consum mer and restrict certain custo omizations. B Be aware of the limitations of managedd packages beefore diving iinto a p project. Not all a application components ccan be packagged (although more h have become packageable with w each rellease), and daata is currentlyy not p packageable. This T typically means some post installatio on configuratiion is n necessary for th he package pro oducer. The T producerss of managed packages also o have some useful tools at their fingeer tips includiing license m management of o installed packages, the ability to puush upgrades, code depreccation and app plication versio oning. For a paackage to appeear publicly on n the AppExch hange it has to t be managedd. A Dep ployment Alteernative There T is anoth her method off migrating cod de, born moree out of proceess than techno ology. The method m we willl describe is fast, and because of the inclussion of a VCS minimizes thee risks associaated with miggrating code. Note N that thiss method onlly works for migrations m bettween sandbo oxes and/or D DE Orgs. For F this type o of deployment you’ll need tw wo Force.com IDE projects, each connectted to its ow wn Org but sh haring the sam me VCS repossitory. From ffigure 3 - 17 it i can be seen n that changees are made in n a developm ment project, committing c ch hanges to yourr VCS at mileestone points. When you arre ready, imporrt the required d changes into the deployment project andd push them to t the target O Org.
120
Salesforce Handbbook
Figure 3 - 16. Deployment viia Force.com ID DE Projects and d VCS
You mightt ask why nott use the Forcce.com IDE ddeployment wiizard or the F Force.com Miigration Tool. The answer to o both is that it’s a matter o of saving time and reducing rrisk. With thee Force.com IIDE deploymeent wizard youu need to find and enter creedentials for eaach target Orrg, and all testss are run on eaach deploymen nt, which can occupy your IDE for 15 minutes at a tim me. With the F Force.com Miggration Tool you’ll y need to manage deplo oyment descrip ptors and po otentially fiddlee with configuuration files. Both B of these methods also o allow you to o skip the VC CS step. We th herefore gain tiime because alll we need to ddo is move fro om one Force.com IDE pro oject to the oth her, and we reduce risk sincee the VCS form ms our deploym ment conduit. Note that yyou can have several s target deployment d prrojects all conn nected to the ssame VCS rep pository. Then n it’s just a matter of puulling source code into thee appropriate Org for “d deployment”.
Jeff Douuglas & Wes Nollte
121
Monitoring Deployments We previously noted that deployments could take upwards of 15 minutes to complete. If you’d like to monitor these deployments, or view a history of past deployments you can access such a control panel by clicking Setup -> Deploy -> Monitor Deployments. Developing Applications that Scale As larger and larger companies build applications on the Force.com platform, scalability and performance with large data volumes becomes something that administrators and developers need to be concerned about. Any of the following factors indicate that you should start to think about ways to scale your applications: •
Record ownership - If an Org has a private sharing model with individual users that own 10,000 - 100,000+ records, it may degrade performance due to the querying of the share tables and the number of records involved in those tables
•
Sharing model - Private sharing models tend to be slower that public models as objects need to do an extra JOIN to look up the sharing privileges for each record.
•
Role hierarchy - A deeply nested role hierarchy (10-12 levels) can impact scalability.
•
Number of territories - When an Org has to deal with thousands of territories that are deeply nested, it may degrade look ups, list views and reports associated with accounts. You should become concerned when your Org approaches 10,000 territories.
•
Public groups - Deeply-nested public groups (thousands of public groups) may cause performance issues as the platform has to traverse these trees to determine record access.
•
Large volumes of records - Once an object contains 1-2M records it starts to suffer from performance issues in a number of areas (e.g., search, list views, reports, SOQL queries).
There are a number of strategies you can implement to make your applications more scalable. Using Divisions Divisions are most often cited as the best way to speed up an Org. Using divisions associates users and their data into a structure similar to a database partition. Data should be divided into logical data sets that are meaningful to end users. For example, if your company operates from a regional perspective then divisions could be partitioned into three regions: East, Central and West. Divisions allows you to segment your data into organizational “buckets” providing users with a view of data that is relevant to their needs. You can set up divisions virtually any way that makes sense such as geographically, line of business (i.e., commercial or government) or any other type of internal corporate grouping. Divisions do not restrict data access but simply makes data easier to manage and faster to access. 122
Salesforce Handbook
Divisions sshould lead to o better respon nse times for tthings like listt views and rep ports, for exaample. Divisions are desiggned to scalee up to 100,0000 users forr Orgs based on data seggmentation in the 1M+ rangge. Salesforce.ccom specifies that you shoulld aim for lesss than 1M reccords per object per division n. See chapter 2 for more info ormation on Divisions. D Arrchive Data Determine if you can arcchive data in an nother custom m object or systtem for recordds that are typ pically only neeeded for historical purposees. It may nott make sense to force userss to wade thrrough millionss of record thaat are, say, 5+ years old wheen all they are really concern ned about aree leads that havve been created within the laast 6 months. Crreate Addition nal Indexes Any field marked as an a “External ID” will auto omatically creeate an index. If your application conssistently perforrms searches on o the “Emaill” field, then marking m that fi field as an “E External ID” sh hould significaantly increase response r time.. You can also o contact salesfforce.com Suupport and disccuss with them m the possibilitty of creating m multi-column or o additional in ndexes on an object to speeed up searchees and reportss. Salesforce.co om periodicallyy monitors quueries and triees to detect neew indexes that need to be crreated but youu may be betterr off making th he request forrmally via supp port channels. Creating in ndexes may siggnificantly incrreases data load and delete p processing times as these indexes haave to be mainttained.
Op ptimize Securrity Model Use private sharing models sparinglyy and strategiccally when po ossible. The F Force.com database is desiggned to be optiimized by reco ord owner to ddetermine whicch user can seee a record or group of reccords. Try to minimize m the number of sh haring rules per object. Perrformance n of shaaring rules app proaches 250. Also attemptt to avoid begins to degradde when the number nnecessary leveels of role hieraarchies, groups and territoriees as it has an impact on perrformance un as well. A wide-o open sharing model m will alw ways be more p performant duee to the lack o of security checks when fetcching records for display, listt views, reportts, etc. Trrain Users to Search Effecttively Provide en nd-user trainingg so that userrs constrain th heir searches to o provide bettter results with less time. So instead of seearching for “SSm*” across alll objects, havee users enter a keyword thaat is more sign nificant or imp pactful like a SSN S or phone number. Anotther techniquee to speed up p searches is tto use the neew advanced search to onlly search a sp pecific object. Utilizing divvisions will also o speed up seaarches as it usees the user’s suubset of record ds by default.
Jeff Douuglas & Wes Nollte
123
Use Asynchronous Apex Whenever possible, use Asynchronous Apex to process records or other operations in the background. If the user isn’t dependent on a process, don’t make them wait for it to finish. Perform it in the background while they go about their business. Asynchronous processes don’t compete with other running processes and kick-off when the server has free resources. Use Schedule and Batch Apex For processes that are resource intensive and which may collide with active user processes, schedule them to run periodically or nightly with Batch Apex. You can take advantage of higher governors and limits while resources are available. Experiment with Queries Use the Apex Explorer, Eclipse or SoqlXplorer to fine tune queries and see how changes to indexes or filters impact response times. For instance, with large data sets in a single object with no divisions, SOSL will actually result in better performance than SOQL. Avoid constructing SOQL queries that use non-indexed fields. Salesforce.com automatically indexes relationship fields, fields marked as an “External ID” and some standard system fields as well (e.g., Name, LastModifiedDate, CreatedDate). In general, queries using system fields in the filter criteria perform better than those using External ID fields. Using the LIKE expressions on an External Id field works well when the ‘%’ sign is not the first character in the expression. Bad Query SELECT Id from Account where Name LIKE ‘%ACME’
Good Query SELECT Id from Account where Name LIKE ‘ACME%’
Testing Applications on the Force.com Platform Software testing on the Force.com platform inherits many of its principles and tools from the traditional programming paradigm. Like it’s traditional counterpart you’ll find that your test environment setup depends on circumstance (read money and resources) as well as the projects you have in mind i.e. smaller projects can be developed comfortably within some subset of a “full” test environment architecture. An Adjusted Approach There are many aspects to testing which are largely platform-independent and as such we’ll only touch on the majority. Testing can be broken down into: •
Testing levels o Unit testing o Integration testing o System testing
124
Salesforce Handbook
o M Migration testin ng o R Regression testiing o U User acceptancee testing o Q Quality assurancce testing •
Testingg methods o Bllack box o W White box
•
Testingg processes o W Waterfall o A Agile
There are aadditional testiing levels, metthods and proccesses1 but wee’d argue that tthe above aree the most po opular, and tyypically a deveelopment team m won’t (altho ough they should) even em mploy all of the testing leevels and methods mentio oned above. Each E of these is well do ocumented, spaanning thousands of websitees and many a book, so we’’ll not detail th hem here. Instead we’ll intrroduce the areaas that are most popular with h Force.com developers. d Un nit Testing Unit testing is common in software development d aand in short could c be defin ned as the pro ogrammatic vverification of application code at a gran nular level, typ pically per fun nction or meethod. Often timee’s developerss confuse unitt testing with integration teesting and instead of determining whether w the fuunctionality provided specifiically by a code functtion works, theey instead test whether it works with otherr elements of the systtem. On the platform p both types of testin ng exist, but aare largely referred to by the same name. n m is a feature of Apex code and Apex trigggers, and Unit testingg on the Forcee.com platform willl be explored in their respeective sections.. It is importan nt to note thatt you cannot ddeploy (in thee Force.com sense) to an Org unless yourr unit tests exeecute at least 75% 7 of the souurce code thaat has been wrritten. Syystem Testing g Developerss will breathe a sigh of relieef to learn thaat many aspectts of system teesting are handled withoutt them having to lift a fingerr. Scalability, sstress, load, peenetration and reliability tessting are somee of the types of testing thaat you no longger need to wo orry about (ho oorah!) as theey’re salesforcee.com’s respon nsibility. 1
so oftware-testing Jeff Douuglas & Wes Nollte
125
Testin ng Environmeents and Arch hitecture One O of our faavorite testing features of th he Force.com platform is th he ease with w which you can c create reeplicas of your production n environmen nt. In traditiional develop pment topolo ogies this is uusually a nightmare as you need the harrdware, softw ware, licenses, staff, infrasttructure, etc. tto support thee duplicated en nvironments, and even then n they typicallly will not bee precise copiees. Note N that sanddboxes are onlly available to salesforce.com m customers who w have purcchased Enterp prise or Unlim mited Edition liicenses1. There are differentt types of sand dboxes that suupport copyin ng data, configguration or botth, and it is po ossible to have multiple, indeependent sandb boxes at once. IIf you do not have access to t sandboxes with your saleesforce.com eddition tthen you can sign up for a frree DE Org (hhttp://developer.fforce.com). You could ccreate a proceess that deployys code and ddata to this Org O giving youu near ssandbox capab bilities. For F the rest off this section we w will only mention m sandbox and produuction environm ments but bee aware that in n most situatiions it is tech hnically viable to replace “saandbox” with “DE Org”. It I is widely reggarded that devvelopment and d testing enviro onments shouuld be kept sep parate. This im mplies testers aand/or users can c evaluate fuunctionality witthout holding up developerss. This setup was w demonstrrated in topolo ogy of figure 3 - 2 and figure 3 -18 showss that each phaase of testingg also serves aas a feedback mechanism. m Iff new featuress are requested d or functionaality is faulty, the requiremeents are analyzed and develop pment returns to the first ph hase.
1
enviro onment-types
126
Salesforce Handbbook
Figu ure 3 - 17. Force.com Developmeent Lifecycle
This devellopment lifecyycle coupled with w a regulaar release scheedule would form the heartbeat of yo our software output effortts. Note that salesforce.co om has a boo ok called “D Development Lifecycle Guiide” that exteensively discuusses developm ment, deploym ment and tessting strategies1.
1
fo orce.com-develop pment-lifecycle-guuide Jeff Douuglas & Wes Nollte
127
SSalesforce.com m offer a freee cloud-basedd service callled the Forcee.com SSecurity Code Scanner1. Thiss developer tool will scan th he code in the target O Org for securitty (e.g., cross site s scripting, SSOQL injectio on) and code qquality ((e.g., DML staatements or SOQL/SOSL iinside loops, non-bulkified n Apex m methods) issuees and send youu a handy PDF F with the detaails. Analyysis and Maintenance on th he Force.com m Platform Now N you’re aw ware of the to ools available to aid you in n creating, tessting and deplloying applicaations, so whaat’s next? Whatt if somethingg goes wrong o or it’s requesteed that some p part of the ap pplication be cchanged or enh hanced? It’s th hen that you n need a sound knowledge off tools that caan help you analyze and/or maintain m your application a codde. Broadly B speakin ng the tools avvailable can be categorized ass data-analysis tools, code-an nalysis tools, or both. Somee tools are officcially supporteed by salesforcee.com while otthers are not. Force.com IDE – S Schema Explorer The T Schema E Explorer is a tool t used for data and scheema analysis, and a is conven niently located d within the F Force.com IDE E. Double-cliccking on the file called salesfforce.schema iin any Force.com IDE pro oject will open the schema fo or the connectted Org. Figurre 3 – 18 show ws the typicall DE Org scheema. Expanding E thee schema tree in the right pane you’ll seee all the objeects in your O Org, a descrip ption of each o object’s field, as a well as detaiils of object rellationships. Exxploring the scchema this waay is often mucch quicker thaan navigating th he objects thro ough the salesfforce.com UI. L Looking throuugh the list of o schema ob bjects you’ll seee objects suuch as A ApexClass and a ApexTri igger. Here you start to get g a feel forr how ddeeply metadaata penetrates the platform. For example Apex classees are ssimply metadaata (XML) pluus persisted ddata, making for f a powerfuul and iincredibly flexiible programm ming language. The T left-most pane in the Schema Explo orer let’s you run SOQL queries q against that particuular Org. Youu have the opttion of typingg out the querry manually, but b for quick query buildin ng you can select the appropriate objecct fields in th he right-most pane and Scchema Explorrer will generate the query fo or you. Clickin ng Run Me willl yield the querry results just b below the quuery input area.. Force.com Exploreer The T Force.com m Explorer iss a Windows only tool offfering the sam me functionallity as Schem ma Explorer an nd more2. Afteer logging in you’ll y arrive att the main app plication windo ow as shown n in figure 3 – 18.
1 2
apex-ssecurity force.ccom-explorer
128
Salesforce Handbbook
The passw word that Force.com F Exxplorer expeccts is your password concatenatted with your security token n i.e. if your password p is “P Password” and your token is “Tokken” then youur Force.com Explorer passsword is “Password dToken”. You’’ll find that iff a tool does not n explicitly ask for a token it asssumes that youu supply it with h this concaten nated passwordd instead. The landingg tab is immed diately familiarr in that it mirrrors the Schem ma Explorer viiew. Note thaat the languagge used for quuerying here iss structured ob bject query lan nguage (SOQL L), which wee’ll discuss later. The next tab offers thee ability to test structured object search language (SO OSL) statemen nts, and helps to learn the language l with a search stateement builder similar to thaat first seen in Schema Explo orer. The “Daata Editor” tab b lets you exam mine data for an ny object, as well as armin ng you with so ome editing caapabilities. Last but not leastt the “Docum ments” tab letts you interroggate a special object called Document. You can sto ore binary largge objects (BLOB) in the D Document ob bject; this allow ws you to uplo oad images, offfice files, or m most other larrge file types. For the mo ost part Forcee.com Exploreer falls into th he “Analysis” category c and aalso helps tho ose starting offf with the Fo orce.com queryy and search llanguages (bessides the queryy builders theere are sample queries availab ble from the application a men nu).
Figure 3 - 18.. Force.com Exp plorer Jeff Douuglas & Wes Nollte
129
SoqlXplorer SoqlXplorer is a Mac application offering similar features to those of Force.com Explorer built by one of salesforce.com’s brilliant minds1. It doesn’t yet offer all the features available in Force.com Explorer but it is frequently updated and the schema exploring feature adds some nice eye candy. Excel Connector This Force.com tool sits within Microsoft Excel (who would’ve guessed) and facilitates querying objects with the result written straight into spreadsheets2. This is incredibly convenient for local data-manipulation, as well as reporting and data logistics. Additionally you can write information back to your object giving any person familiar with Excel a bidirectional interface to salesforce.com objects. This tool straddles the analysis and maintenance roles, and is versatile in that you can hand the documentation to your admin staff and start building a team of salesforce.com super-users. Additionally developers find value in the Excel Connector when data consolidations or other complex data activities are required as Excel has features beyond the scope of other Force.com tools. Data Loader Also known as Apex Data Loader it will become one of your closest allies in analysis and maintenance on the platform. As the name suggests it’s used to push data into a salesforce.com Org. Moreover you can extract, delete and modify data using Data Loader. Data is extracted and imported using comma-separated value files, making them workable from most spreadsheet applications. You can download the tool from a logged in salesforce.com session by clicking Setup and under Administration Setup -> Data Management -> Data Loader. Data Loader falls more into the maintenance category, and presents a simple wizard based interface for beginners, but includes a command-line interface for custom executions or for automating the extraction and/or uploading of data3. Note that Data Loader is a Windows only tool. If you need similar functionality for Mac, you’ll need the ported version called LexiLoader4. Workbench This community built application stands out from the aforementioned tools. It’s webbased (although you’ll need to get it hosted) and performs most of the functions available in Force.com Explorer, Data Loader and anonymous blocks.
soqlxplorer excel-connector 3 dataloader 4 lexiloader 1 2
130
Salesforce Handbook
Not only ddoes it suppo ort describing, inserting, upddating, deletin ng, undeleting,, purging, quuerying and exxecuting Apex,, the interface is arguably better than in the t other tools and the do ocumentation is in-depth and d precise1. Since mostt of the featurees available fro om this applicaation have been n covered already it’s not necessaryy to revisit them m. Don’t be deeceived by the length of this summaary though, Workbench W is th he bee’s knees as it’s a web-b based one stop shop. Fo orce Metadataa JDBC Driveer for SchemaaSpy A superb ttool created byy a rising star of the Force.com commun nity, it generattes entityrellationship diaggrams for your Org. Moreoveer it generates an interactive local site that describes your schema from m the highest level down to the smallest ddetail. The tool sits firmly withiin the analysis arena, and its implementatio on might be reegarded as meedium to diffficult, althouggh Jeff Douuglas has writtten up an article that m makes its im mplementation clear2.
Fig gure 3 - 19. A ScchemaSpy Generrated ERD 1 2
workbench w fo orce-metadata-jdb bc-driver-schemaaspy Jeff Douuglas & Wes Nollte
131
Debug g Logs Logging L is parrt-and-parcel of o any develo oper’s life. Deebug logs for Force.com caan be accessed through a salesforce.com m instance byy clicking Set tup, and und der “Administrration Setup”” clicking Moni itoring -> > Debug Log gs. Debug D logs can n’t run continuuously and insstead are requeested on a perr user basis, wiith 20 logs being b provision ned at a time i.e. one log “file” “ will be ccreated for eaach user transaaction which for a typical p page or API traansaction woulld include: •
Any contro oller code run on o a page load d
•
Any contro oller code run as a part of an AJAX A request
•
Any triggerr, workflow, vaalidation rule or o database acttivity initiated from f the page
Transactions T caan also be morre nuclear, and d not necessarilly user-initiated. After A clicking N New and selectting a user you u have the abillity to delete, reset r or apply filters to the request. The delete option n is obvious, the t “reset” option will refreeshes the debuug log requesst so that you once again havve 20 logs avaailable, and thee filter option works preciselly like those seen s in anonym mous blocks i.e. it controls th he log verbositty. A Although only 20 logs should d be available at any time, it seems that forr each cclick on Reset t an additionaal 20 logs are p provisioned. Don’t D tell anyon ne we ttold you thouggh. The T output of the log is neceessarily compleex as it has to ttrack code at several s levels, aand to be of any use, needss to be granulaar to the sub-aatomic level. W We would high hly recommendd that instead d of just readin ng through thee logs line-by-lline that you in nstead fire up the System Co onsole Log (S System Log g) as the tools available theree make for a fa far superior deb bugging experrience. Note that t you will sttill need to havve the official log output guiide1 close at haand until you ggain a fair am mount of experrience. Tools to Assist Pro oductivity & More M Every E developeer has tools th hat whilst not used directly iin their develo opment aid them in one waay or another. List here are a notable few. Force.com Utility B Belt This T Google C Chrome Extenssion provides shortcuts to so ome of the most commonlyy used salesfo orce.com docuumentation, a quick q search in nterface for mo ost salesforce.ccom documentation plus a large numberr of other sitess (e.g., Messagge Boards, Snip pplr, Code Shaare, AppExchaange), links to o number salesforce.com ressources and a 15-digit 1 salesfo orce.com ID converter.
1
undersstanding-debug-lo og
132
Salesforce Handbbook
Avvailable from http://blog.jeffdo h uglas.com/force-ccom-utility-belt Trrapdoor This neat M Mac OS tool will w keep trackk of your salesfforce.com cred dentials. As an n example wee currently “ow wn” more than n 20 salesforce..com Orgs so tthis tool is han ndy.
Avvailable from http://www.pock h ketsoap.com/osx//trapdoor Seetup Enhanceer for Salesforce Those fam miliar with GreaseMonkey are a aware thaat it’s a browsser plug-in th hat allows devvelopers to create JavaScriptt tweaks to weebsites. The Seetup Enhancerr is one such script, and it simply injects a search dialo og box into th he top of the navigation paane in the setuup menu. Tyyping in the seearch box will filter the setuup menu items in real-time. This T simple to ool makes thee setup menu lless intimidatin ng, and helps beginners b find the proverbiall needle in the haystack.
Avvailable from http://userscripts h s.org/scripts/show/60438 Ap pplication Sup pport on the Force.com F Pllatform Many platfforms have falllen flat simply because of support issues, Force.com F is n not one of theese. Support iss available in a variety of form ms and you’ll ffind that salesfforce.com, as w well as the devveloper comm munity, are alwaays willing to extend e a helpin ng hand. Offficial Supporrt Channels Fo orce.com Disccussion Boards A live, evo olving support option, this channel is invaaluable for begginners. The fo orums are bro oken into man ny channels, an nd you’ll eventually learn the names of the experts in each section. We’d like to streess that no quuestion is too silly s to ask as most people that browse th he boards answering questiions were educcated from thee forums.
Yo ou can find thee discussion bo oards at http:///boards.developerf rforce.com
Jeff Douuglas & Wes Nollte
133
Directt Support There T are levells of direct sup pport offered by salesforce.ccom. The basiic support opttion is availab ble to all custo omers and incluudes telephoniic, email and ccase-based chan nnels. At the h higher levels of support tthe turn-aroun nd times are much shorterr, and even offer o administtrative servicees. To drill do own into the suupport offerin ngs open up th he below URL L and check ouut the links under u “Relatedd Documents”..
Availab ble from https://www.salesforcce.com/ap/servicees-training/custoomer-support Twitteer One O of the n newer supportt options, thiis channel is available for concise quesstions. Turnarround times o on questions asked a via twitter are typicallyy fast, althouggh due to its n nature questio ons cannot bee complex or require long explanations. e T There are also o a number off subchanneels each availab ble from the below b URL.
Availab ble at http://tw witter.com/Salesfforce Docum mentation Documentation D n is one of thee most importaant support “cchannels”, and d salesforce.com m has lots off it. Google caan help you fin nd the right do ocumentation a lot of the tim me, but some o of the jewels of the platform m are found in n PDFs that arren’t Google-in ndexed1. Most ddeveloper docuumentation is available a from m http:///wiki.developerforrce.com/index.phhp/Documentatioon Visiting V the paage the first few times seems like an inforrmation overlo oad, so we’ll liist the docum ments you’ll m most need to sttart out with (assuming ( youur intention is to become faamiliar with th he Force.com p platform languuages).
1
•
Introductio on to Force.com - Core Reso ource Articles
•
Force.com Workbook: Getting G Started Building Yourr First App in the Cloud
•
Force.com Fundamentalss: Custom App plication Development in thee Cloud
•
Visualforcee Quick Start Tutorial T
officiaal-documentation
134
Salesforce Handbbook
•
Apex T Tutorials
•
Under Reference Guiides o A All documents under u “Generaal” o A All documentss under “Ap pex and Visuualforce” (corre language reference do ocuments)
•
Force.ccom Cookbookk: Code Samplles and Best Prractices
•
All doccuments underr “Developer Cheat C Sheets”
Un nofficial Supp port Channelss Bllogosphere A number of talented in ndividuals havee setup blogs tto share their experiences an nd advice 1 with the Force.com commun nity . The top pics here rangge from the saalesforce.com CRM to advvanced topics of integration. Tw witter Many Forcce.com develo opers that youu can befrien nd through Tw witter will freeely offer sup pport and addvice. It was realized by Quinton Walll that perhap ps anyone loo oking for community supp port should usse the #askforcce hash tag, an nd this has plaayed out quite well. For mo ore in-depth qquestions it’s customary c to post p on the Fo orums and theen link to the issue in a tw weet with said h hash tag. Saalesforce.com Certification ns Message bo oards, LinkedIIn and staffingg firms are co onstantly tryin ng to fill salesfforce.com po ositions with qqualified profeessionals. The industry is bo ooming and that t is great fo or people loo oking for jobs.. One of the best b ways to deemonstrate to p potential emplloyers that youu have the skiills and experrience necessaary to do the job is to beccome certified d. Salesfoce.co om offers cerrtification for consultants, ad dministrators and a developerss. There are fivve levels of cerrtification — two for admin nistrators, two o for developerrs, and one forr consultants. Training videos v for DEV-401, D DE EV-501 and Admin A to H Hero with Force.com are available for free on iT Tunes. Simply search the iTuunes store for “salesfo orce.com”. t prepare youu for the certifi fication test buut they are Salesforce.ccom offers traaining classes to no ot required. Trraining is recom mmended but nothing preveents you from m studying on yyour own (sttudy guides arre freely availaable) and takiing the test aat a local test center or on nline. The cerrtification exam ms feature muultiple-choice and multiple-select question ns (60-70) thaat cover a 1
co ommunity-blogs Jeff Douuglas & Wes Nollte
135
broad range of topiccs in that area. The Advanced d Developer eexam also incluudes a program mming assignm ment and sho ort-answer esssay exam. Most certification n exams cost $200 howeveer the Advan nced Developeer certification exam is $400. You’re Y consideered qualified once you’ve successfully p passed your exam. e However, to maintaain your certifiication over suubsequent releaases, you are reequired to takee interim exam ms that test yo our knowledgee of the new release featurees. The cost o of these interiim release exaams is included in the initiaal certification fee for 1 yearr. After that yeear, maintainin ng your certificcation requirees a yearly maiintenance fee of o $100. Visit http://www.salesf sforce.com/servicees-training/trainiing_certification/ /certification for more inform mation.
136
Salesforce Handbbook
Programmatic Development Languages
I
n this chapter you’ll learn more about how to create and maintain applications on the Force.com platform. In doing so you’ll encounter Apex, Visualforce, Structured Object Query Language (SOQL) and Structured Object Search Language (SOSL), which together form the core languages that are used to create software on the platform. These will be explained within the context of the Model-View-Controller pattern; a prolific architectural pattern that calls for the separation of application logic, data and user interface in order to reap the benefits of easier collaboration and maintenance. By the end of the chapter, not only will you be aware of what you need to develop applications using Force.com, but you will also have a feel for the best practices in each area.
MVC in the Cloud We’ve addressed the topics of software development models and the tools that you’ll need as a Force.com developer. A natural next step is the exploration of the languages and technologies that you’ll use to take your projects from specification document to real-world application. Model-view-controller (MVC) is a prevalent architectural design pattern in modern software development. In short it promotes the separation of an application’s logic, userinterface, and data storage from one another. This architecture has risen in popularity as this isolation of data (the model), user-interface (the view) and logic (the controller) allows each component to be developed, tested and maintained independently. The Force.com platform’s development architecture fits conveniently within the MVC pattern allowing development teams to take advantage of the separation of responsibilities. If you consider figure 4 - 1 and imagine the following scenario: You have created a Visualforce page (the view) with a text field and a “Save” button. The text field holds your last name, and this is persisted in a custom object (the model). When the page loads the field on the view requests the stored first name value from the custom object; this communication happens via the page controller. You might want to update your last name in which case you’d change the text field value and click the “Save” button. This click would trigger an event handler in the controller, which would feed the information from the page to the custom object.
Figure F 4 - 1. MVC C on Force.com m
The T model, the view and th he controller clearly c have sep parate domain ns of operation n and this alllows you to wo ork on each co omponent indeependently. Since S the Forcee.com platform m alludes to th his design patttern we will disscuss each platform languaage and techno ology within th he context of th hese roles. SSalesforce.com m is a multiten nant architectuure as explaineed in chapter 1. In o order to preven nt any applicattion from con nsuming more than their fair share o of the platform m resources th hey have introduced restrictiions on measuurable p program operaations. These restrictions r falll under the naames governorrs and llimits and togeether they forcce the develop per to create code that is effficient ssuch that all “tenants” “ get an a equal sharee of the resourrce pie. Devellopers ddon’t like Govvernor Limits very v much as their developm ment style is fforced iinto certain prractices used to remain witthin these lim mits. However these p practices ensuure a code baase that is neeat in architeccture and quiick in eexecution. Go overnor Limitss are applied differently to o each area o of the ddevelopment platform p and will w be discusseed those contexxts.
The Model M Within W the Fo orce.com platfform data perssistence is pro ovided througgh what are teermed Objectts. These comee in two broad d flavors as sho own in chapterr 2. Objects O are an excellent way to abstract aw way the database and it’s corrresponding fieelds as this alllows developeers to work witth data in an object-oriented o d way i.e. insteead of workingg with data ro ows, on the Fo orce.com platfo form data is en ncapsulated in a class-like struucture with thee data fields accessible via member variaables. If we peek into the co ontroller domain briefly you’’ll see,
138
Salesforce Handbbook
as show in listin ng 4 - 1, that objects can be b instantiated, and their meember variablees can be asssigned values iin much the saame way as classs variables. Listing 4 - 1. Object Maanipulation in n an Apex Claass Account myAccount = new Acco ount( ); myAccoun nt.firstnam me = ‘Zack’;
What do ddevelopers exp pect from the model? Usuaally you’d need d several abilitties to be exp posed: o Data Creation o Data R Retrieval o Data U Update o Data D Deletion o Data Seecurity The first fo our features arre sometimes referred r to as create, retrievve, update and delete or CR RUD. Data retrieval is the most m complexx of CRUD on n the platform m having two languages devvoted to this ssole purpose. The T other opeerations are sem mantically quitte similar, and vary only in syntax and ressult and therefo fore make a good starting poiint. Data securrity is configured using a com mbination of feeatures such as profiles, roles and field-level f secuurity. These to opics are discuussed in moree detail in chapter 2. n, Update and d Deletion Daata Creation, Manipulation With most types of dataabases you’ll en ncounter operrations to inseert1, update2 an nd delete3 data. Force.com m is similar in this regard, with w listing 4 - 2 demonstrating how to insert, up pdate and del lete a data record. r Listing 4 - 2. Insert, Up pdate and Dellete a Record d with Apex Code C Account myAccount = new Acco ount(firstn name=‘Zack’ ’); myAccount; // Insert a row of d data in Acc count object insert m myAccoun nt.firstnam me = ‘Jon’; ; update m myAccount; // Update the above record delete m myAccount; // Remove the record d from the data store
dm ml-insert-docs dm ml-update-docs 3 dm ml-delete-docs 1 2
Jeff Douuglas & Wes Nollte
139
Note the distinction between data manipulation and data update at the third and fourth lines. Line three is manipulating the value of the member field “firstname” and line four stores the changed value. There’s an additional command available that can perform inserts or updates, and knows which action is appropriate in a given situation. This command is called upsert1 and its usage is demonstrated in listing 4 - 3. Listing 4 - 3 Account myAccount = new Account(firstname=‘Zack’); upsert myAccount; // Insert a row of data in Account object myAccount.firstname = ‘Jon’; upsert myAccount; // Update the above record
Each of these commands is simple and extensively documented so there is little else we can add. Instead we’ll detail the more interesting topic of data retrieval. Data Retrieval using SOQL and SOSL Data retrieval from data stores usually requires a query language. Probably the most common is structured query language (SQL), which comes in many varieties, which are syntactically similar. The Force.com platform uses two languages for data retrieval, each of which has specific use-cases; essentially SOSL is capable of performing text searches across objects and returning several object types in the results whereas SOQL allows complex querying of data returning a single object type. Of the two you’ll find that structured object query language (SOQL), which has its roots in SQL2, is the one you’ll use more frequently. This is another topic that is covered by torrents of documentation, so we’d like to give you a guiding hand on where to start. SOQL Syntactically SOQL is more or less a subset of SQL3 with each individual statement structured as shown in listing 4 – 4. Listing 4 - 4 SELECT fields FROM object [WHERE conditionExpressions] [WITH [DATA CATEGORY] filter] [GROUP BY fieldListGrouping] | [GROUP BY ROLLUP|CUBE (fieldListSubtotalGrouping)] [HAVING havingConditionExpressions] [ORDER BY fieldList ASC | DESC ? NULLS FIRST | LAST ?] dml-upsert-docs soql-vs-sosl 3 soql-syntax 1 2
140
Salesforce Handbook
[LIMIT ?]
Qu uerying with SOQL Looking att listing 4 – 5 you can seee how this syyntax can be applied with the Apex pro ogramming lan nguage, as welll as how you can c work with tthe results of a query1. Listing 4 - 5 Account account = [SELECT id d, name FRO OM Account ame = ‘Zack k’]; WHERE na // Or if f we only require r the e account n name String n name = [SEL LECT name From F Accoun nt WHERE name = ‘ ‘Zack’].nam me;
Note that queries will always a return data as comp plete object reecords unless aggregate fun nctions are ussed (more on these later). In I the second query we’ve demonstrated d how you miight retrieve a single field vallue by derefereencing the nam me field. The above example assum mes that exactlly one record w will be returneed by the queryy, and this is often a dangerrous assumptio on to make. Iff the query weere to return zero or greater than one ressult, your appllication would throw a runtiime error. In ssome cases it would w be betteer to feed thee results of a qquery into a listt of objects as shown in listin ng 4 – 6. Listing 4 - 6 List acco ounts = [SE ELECT id FR ROM Account t WHERE last tname = ‘de e la Rocha’];
Here you ssee the Apex syntax s for lists of objects buut don’t panic, it will be revisited later in more detail. T This query is not capable of creating c runtim me errors; if no o records are ffound the listt will be emptyy, and if more than zero are found f they’ll b be added to thee list. There is an nother way to deal with a quuery that return ns zero results.. At times it’s better to t implement an a Apex languuage feature caalled exception n handling to avoid th his type of run ntime error; th his feature willl be examined in a later section. Ap pex Variabless in SOQL Once you dive into SOQ QL programm ming with Apeex you’ll often find the needd to filter your queries usin ng the value in n an Apex variaable. As an exaample considerr the query in llisting 4 – 6, but imagine th hat now, at deevelopment tim me, we don’t kknow what thee last name miight be as it’ss determined b by user input. In I this case youu’d use the syn ntax presented in listing 4 – 77. Listing 4 - 7 String l lastname = ‘de la Roc cha’; List acco ounts = [SE ELECT id FR ROM Account t WHERE name = :lastname]; ; 1
working-with-soql w l-results Jeff Douuglas & Wes Nollte
141
Here H we’ve deeclared the varriable that willl hold the lastt name value, and delimitedd said variablle with a colon n. Using a locaal variable with hin a SOQL statement is kn nown as a bindd, and they caan be simple vvariables (as shown above) orr formed by exxpressions1. Objecct Relationshiips & SOQL In I modern devvelopment most databases arre relational i.ee. records in one o table are related to records in other tables througgh an establish hed relationsh hip. The situattion is similarr with salesfo orce.com objeccts and we’ve seen in previo ous chapters th he types of relationships thaat can exist. On any platfo orm you’ll neeed a way to traverse t these relationships and salesforcee.com encapssulated this in a concise and powerful way. From F an objecct point of view w you can eith her be related to a parent orr a child objectt. The differeence in the syn ntax for each siituation is show wn in listing 4 – 8. Listing L 4-8 // / Syntax f for selecti ing all acc counts and d their chi ild contact ts List account ts = [SELEC CT Id, (SELECT first tname, lastnam me FROM Con ntacts) FRO OM Account] ]; // / Syntax f for selecti ing all con ntacts and d their par rent accoun nt List contact ts = [SELEC CT id, Account.name, Account t.firstname e, Account. .lastname F FROM Contact];
B Be careful wheen using the firrst type of SO OQL query as it i can be difficcult to p predict (and reestrict) the num mber of data ro ows returned i..e. each accoun nt can h have any numb ber of child co ontacts. Later w we’ll see that th here are operaational llimits on thinggs such as the number n of datta rows retrieveed by a single query o or within a tran nsaction. The T syntax fo or each of these query typ pes is quite ddifferent but simple s noneth heless. Accesssing the relatedd objects for each e type of reelationship is allso different as is shown in llisting 4 – 9 with w follows on n from listing 4 - 8. Listing L 4-9 // / Accessin ng child co ontacts of an account Account A a1 = accounts s[0]; List account tContacts = a1.Contacts; // / Accessin ng the pare ent account t for a contact Contact C c = contacts[ [0]; Account A a2 = c.Accoun nt;
Through T thesee Apex variab bles you woulld have accesss to the contents of eitheer the childreen or parent of the object in n question2. Bee aware of the syntax when dealing d with cuustom 1 2
soql-b bind-variables soql-reelationship-queriees
142
Salesforce Handbbook
object relationships. Consider the example in which we have a parent object called Father__c related to a child object called Son__c. Listing 4 – 10 shows the equivalent of the above code for custom object relationships. Listing 4 - 10 // Syntax for selecting all fathers and their specific sons List fathers = [SELECT id, (SELECT FirstName__c FROM Sons__r) FROM Father__c]; // Syntax for selecting all sons and their specific father List sons = [SELECT Id, FirstName__c, Father__r.FirstName__c FROM Son__c]; // Accessing sons contacts of a father Father__c f1 = fathers[0]; List sonsOfTheFather = f1.Sons__r; // Accessing the father of a specific son Son__c s = sons[0]; Father__c f2 = s.Father__r;
It’s important to point out that the nested SOQL statement within the first query interrogates Sons__r. This “object” name is the relationship name given when the link between the objects is first established. It can also be changed later by editing the relationship field. Figure 4 – 2 shows where this option is first presented.
Jeff Douglas & Wes Nolte
143
F Figure 4 - 2. Creeating a Relation nship Between C Custom Objectss
Dynam mic SOQL Dynamic D SOQ QL is a feature of the platform m lets an appliication dynamiically build a SSOQL 1 string at runtime . T This way the value v of a querry string can b be determined d by user-inputt as is essentiial with any daata centric appllication. The T syntax forr the query sttring is the sam me as that off SOQL but the t query execcution requirees a system meethod call as sh hown in listingg 4 – 11. Listing L 4 - 11 // / Declare a string to t be used in the query String S qs = ‘SELECT id i FROM Acc count’; // / Execute the query List account ts = Databa ase.query(qs);
Another A superrb feature of dynamic d SOQ QL is that the query results can be return ned as concreete objects (as above) or they can be retuurned as the ggeneric sObjecct data type akkin to listing 4 – 12. Variab bles of this ob bject type can hold h any type of object valuue, be it standaard or custom m. This allowss you to writte applicationss that cleverlyy reuse code and a deal with h data polym morphically. 1
dynam mic-soql-docs
144
Salesforce Handbbook
Listing 4 - 12 // Decla are a strin ng to be us sed in the query String q qs = ‘SELEC CT id FROM Account’; // Execu ute the que ery List sObj jects = Dat tabase.quer ry(qs);
Using dynaamic SOQL also a requires extra care as it involves more m coding aand error 1 checking, and po otentially expo oses your appliication to SOQ QL injection attacks a . All the same, it is a powerful too ol when used correctly. c SO OQL Governo or Limits SOQL Governor Limits2 are one of the t most discuussed topics in n the developeer forums and many of th he questions arre nearly iden ntical. The prim mary issues co oncern hitting the limit im mposed on: 1.
The to otal number of SOQL queries issued
2.
The to otal number of records returrned across your SOQL querries
The first llimit is typicallly hit when developers exxecute queries within some repeated strructure such ass a loop which will result in the t following eexception: System.E Exception: Too many SOQL S querie es
As it’s onee of the most common lim mits that beginn ners encounteer we’ll demon nstrate an exaample of the iissue in action n, as well as th he solution. Liisting 4 - 13 sh hows a SOQL L for-loop thaat contains ano other related query. q Listing 4 - 13 for (Acc count a : [SELECT id, , Owner_Fav vorite_Colo or__c FROM M Account LIMIT 101]) a.Owner_ _Favorite_C Color__c = [Select Fa avorite_Col lor__c FROM User Whe ere Id = :a a.OwnerId]. .Favorite_C Color__c;
Dependingg on the executing code’s eentry point th he Governor aand Limit value that is applied willl vary e.g. if tthe first code to execute is within an Apex class you can issuee 100 queries w within the lifettime of that in nvocation. If execution began in a trrigger howeverr you can only issue 20 queriies. This probleematic pattern n is to be avoid ded at all cost. Salesforce.co om restricts the number of queries because database round trips are expensive e and can quickly afffect the perforrmance of thee multitenant environment. The idiom ussed to resolve this is show in i list 3 - 15. N Note that you’ll need to b be familiar with h the Set and d Map collectio on types in orrder to undersstand and im mplement this p pattern effectivvely. 1 2
dyynamic-soql-exam mple go overnor-limit-doccs Jeff Douuglas & Wes Nollte
145
Listing 4 - 14 // create a set of all the unique ownerIds Set ownerIds = new Set( ); // Fetch all the account you’ll need to process List accounts = [SELECT id, Owner_Favorite_Color__c FROM Account LIMIT 101]; // Put all the ids into a set for easy querying for (Account a : accounts) ownerIds.add(a.OwnerId); // query for User records for the unique userIds in the records // create a map for a lookup / hash table for the user info Map owners = new Map([Select Favorite_Color__c from User Where Id in :ownerIds]); // iterate over the list of records being processed in the // trigger and set the color before being inserted or updated for (Account a : accounts) a.Owner_Favorite_Color__c = owners.get(a.OwnerId).Favorite_Color__c;
Although the code is commented we’d like to point out that the crux of this idiom is that there are no SOQL queries contained in any loops. The second limit is less likely to be caused by an efficiency flaw and is a natural consequence of a growing data set. One common solution to this problem is to fire asynchronous method calls to run over your data set in batches of 10,000 (The limit for the number of SOQL queries executed through Apex). Since these would run in their own transactional context, each batch would be subject to fresh limits. The process of creating and managing these batches can be complex and error prone, and if your situations allows for it you should take a look at using Batch Apex. Batch Apex will be discussed in the section titled “The Controller”, but in brief this technology is implemented using a certain type of Apex class, and the limit on the number of records fetched in these classes is currently 50 million. This covers the basics of data retrieval but you will certainly want to dive into more detail after just a few experiences with SOQL1. Important advanced concepts to get familiar with early on are aggregate functions2, working with very large queries3 and SOQL for loops4.
soql-primer soql-aggregate-functions 3 soql-very-large-queries 4 soql-for-loops 1 2
146
Salesforce Handbook
SOSL Structured object search language (SOSL) is a language used to make very fast, broadsweep searches through your objects’ fields. Many object fields are text-indexed for SOSL making this type of query faster than an equivalent search made using SOQL. When might you use SOSL instead of SOQL? An example might be when building search functionality into a Force.com Site. You need to let users find data based on keyword searches, and the results could be from a number of objects. Building an equivalent SOQL “search engine” would require a number of queries, as well as complex multi-level logical branches. It is also likely that SOSL will perform this type of search more quickly. Listing 4 – 15 shows the syntax of an SOSL statement1. Listing 4 - 15 FIND {SearchQuery} [ toLabel( )] [ IN SearchGroup [ convertCurrency(Amount)] ] [ RETURNING FieldSpec ] [ WITH DivisionFilter ] [ WITH DATA CATEGORY DataCategorySpec ] [ LIMIT n ]
Be aware that SOSL cannot search these objects or field types: •
Fields that are defined as not searchable. You can interrogate an object for this property by calling its describeSOjects( ) method and examining the value of the property named searchable.
•
Number, date and checkbox fields.
•
Textarea fields aren’t searched unless you specify ALL FIELDS for the search
group. •
Certain attachment records for some standard objects.
It’s important to know that you’ll use SOSL sparingly as its role is quite niche. However, when the time comes to build bespoke search functionality very few languages can compare with SOSL for simplicity and speed. Searching with SOSL SOSL search statements are human friendly as is apparent in listing 4 – 16. Listing 4 - 16 List searchResult = [FIND ‘hello*’ IN ALL FIELDS RETURNING Account (id), Contact];
1
sosl-syntax Jeff Douglas & Wes Nolte
147
The syntax is quite different from that of SOQL, and the search results are organised differently as well. Firstly the result is a list of lists of sObject types. The reasons here are: •
You are potentially searching multiple objects, and therefore need a list to house each object type. In the above example you would thus have one list of Accounts, one list of Contacts, and a list that holds each of these lists.
•
A variable of the SObject type can hold any other object type, so it doesn’t matter which objects your are searching through the results will always “fit” into this structure.
Listing 4 - 17 shows how you might assign the search results to variables of the specified types. Listing 4 - 17 List accounts = ((List)searchResult[0]); List contacts = ((List)searchResult[1]);
When planning on using SOSL it’s important to note that1: •
The lists of objects in the search results are in the same order as they appear in the query.
•
SOSL queries can only be issued from Apex code or anonymous blocks. They cannot be used in triggers.
•
Text searches for a single or no characters cannot be executed.
•
Unit tests for SOSL searches require initialization using Test.setFixedSearchResults(List testIds).
Searching with SOSL has its place and makes serving search functionality very simple and quick. Consider having to build a small application that searches all fields of the Telephone type within your Org. Listing 4 - 18 shows how easy this is with SOSL. Listing 4 - 18 FIND {MyLead} IN PHONE FIELDS
Knowing when to use SOSL as opposed to SOQL requires some thought initially, but with a little experience you’ll easily discern which tool to apply to specific situations. Apex Variables in SOSL Needing the use of dynamic bind-variables within SOSL statements is commonplace. You’ll find that the syntax requirement is similar to that of SOQL, with the only noticeable difference being their positioning with a statement2. Listing 4 - 19 is a contrived example showing the use of bind-variables in SOSL. 1 2
sosl-best-practices soql-syntax
148
Salesforce Handbook
Listing 4 - 19 String searchPhrase = ’PotOfGold’; String filterPhrase = ’Zack’; Integer lim1 = 1; String division = ’Long’; Integer lim2 = 2; List sr = [FIND :searchPhrase IN ALL FIELDS RETURNING Account (name WHERE name LIKE :filterPhrase LIMIT :lim1) WITH DIVISION =:division LIMIT :lim2];
Object Relationships & SOSL Currently there is no way to search a child and return the parent, or vice versa with SOSL. You would overcome this by searching through either child or parent objects and then discovering the counterpart through that object’s relationships and/or Id. Dynamic SOSL Again Dynamic SOSL operates in much the same way as Dynamic SOQL, and supports the same features as static SOSL as well as being constrained by the same rules1. Dynamic search statements are executed using the search.query(sosl_string) method where sosl_string is a string variable whose value is a valid SOSL searchstatement. Listing 4 - 20 shows such an example. Listing 4 - 20 String searchQuery = ‘FIND\’Zack*\’IN ALL FIELDS RETURNING Account’; List results = search.query(searchQuery);
Of particular interest here are the backslashes in the search string. These are used to escape special characters within the string so that they can be included in the string definition. In the above example the single quotes are a required part of the SOSL syntax, but if they weren’t escaped, the second quotation mark would “close” the string and the third would “open” a new string; this would not compile as it violates Apex syntax rules. The ability to dynamically build search statements based on user input opens up your code to injection attacks. A simple way to avoid this is to use the String.escapeSingleQuotes(myString) method, which adds a backslash to any single quote not yet escaped. Listing 4 - 21 shows such an example.
1
dynamic-sosl Jeff Douglas & Wes Nolte
149
Listing 4 - 21 String input; // variable value is set by user input String searchQuery = String.escapeSingleQuotes(‘FIND’+ input + ‘IN ALL FIELDS RETURNING Account’);
SOSL Governor Limits There are two SOSL limits that mirror the SOQL limits mentioned previously1. The first of these (regarding the number of search statements executed) is moot as one of the selling features of SOSL is its ability to search many objects and fields at once. The second limit (concerning the number of data rows retrieved) is quite small and is more difficult to work around. The two popular solutions call for either searching multiple times or (more commonly) using SOQL instead of SOSL.
The Controller The most complex area of the Force.com platform is largely regarded to be the Apex language and it’s implementation. Apex classes together with Apex Triggers form the Controller in the MVC pattern; they provide an interface to the Model and expose their logic and functionality through the View. In fact Visualforce is so heavily supported by Apex that as a newbie it’s prudent to learn about the Controller before discussing the View. The Apex Programming Language Apex code, Workflows, Formulae, and Approval and Business Processes provide application logic on the Force.com platform but only Apex code falls into the programmatic development category. Apex is a strongly typed, object-oriented language similar in syntax to Java or C#, and (in certain areas) Oracle PL/SQL. It provides the conditional logic, various looping constructs, data retrieval and manipulation, transactional control, expression evaluation and error handling common to its class of programming languages. We’ve shown how universal metadata is used within the context of the Force.com platform, and figure 4 - 3 shows its role within the Apex language domain.
1
governor-limit-docs
150
Salesforce Handbook
Figurre 4 - 3 Apex: Fro om Source Codee to End User
Here you ssee that a deveeloper creates code locally aand upon savee the source co ode file(s) aree sent to the p platform appliccations serverss. The code is then compileed into instructions that thee Apex runtim me compiler un nderstands. Th hese instruction ns are stored as a metadata an nd when a useer triggers th he Apex codee, these metaadata instructtions are inteerpreted and evaluated preesenting the usser with the results. Notice thaat only the Apex source co ode is written n locally, com mpilation and execution happens on the F Force.com plaatform. There is a llot of documeentation on Ap pex, and one o of the driving forces f behind this book has been the neeed to help deevelopers, business analysts and companyy owner’s focuus on the mo ost important resources. Thrrough this secttion we will higghlight the mo ost important aaspects of Ap pex, especially for those interested or begin nning with thee platform. If you’d y like to eexpand on thee tidbits we touuch upon, we’d recommend reading the do ocuments listed below. You can ffind all of th he following links l by usingg the officiall-documentatio on tag at delicious.com. Apex Codee: The World d’s First On-D Demand Progrramming Lan nguage A summaryy for anyone who w needs an overview o of thee Apex languagges features1. An Introdu uction to Force.com Apex x Code As the titlee suggests this is a primer on n the language including a ligght touch on th he syntax, Dyynamic Apex aand its role in the t Model and d View, unit tessting, web servvices2. 1 2
ap pex-ondemand ap pex-intro Jeff Douuglas & Wes Nollte
151
Apex A Cheatsh heet This T short refeerence documeent highlights important i synttax across the Apex A languagee1. An excelleent resource fo or developers at a all levels. Apex A Code Beest Practices This T wiki articlle should be used u in conjuncction with anyy code design and a review sesssions as it deetails common n patterns that will ensure your Apex code is efficient and d scalable2. Security S Tips for Apex and d Visualforce Developers D An A article that explores a number of securrity attacks andd how to a devveloper might avoid them. All developerss should read and a be familiarr with this docuument3. Force.com F Wo orkbook This T excellent, short book th hat covers morre than just the Apex languaage with 10 tuttorials 4 in totaal . Each tuto orial builds on n the last to build a wareh house application, but the most importtant Apex tuto orials are numb bers 5 and 6. Force.com F Co ookbook This T book exteensively docum ments many feeatures of the Force.com platform5. It con ntains scores of useful codee samples and best practices. All developerrs starting on the t platform should keep th his close at han nd as many beeginner questio ons are answered in this bookk. Salesforce.com S m recently laun nched a com mpanion websiite aptly calleed the “Forcee.com Cookb book”. This on nline version iss, of course, more m up to datee and recipes are submitted b by not only saalesforce.com but by commuunity memberss as well. Bookkmark this site.. New aand updated Fo orce.com codee recipes can bee founds at http:///developer.force.coom/cookbook Force.com F Ap pex Developer’s Guide Every E Apex deeveloper’s frien nd, this refereence documen nt details all areas of the lan nguage togeth her with a num mber of code samples6. From m beginner to guru you shouuld always keep this site at the top of youur bookmark liist. Development D with the Forrce.com Platfform: Buildin ng Business Applications A iin the Cloud d This T book by JJason Ouellettee of Appirio iss an extensive guide to build ding applicatio ons on the plaatform1. It is an essential guide g for anyo one looking fo or structured, concise way tto get apex-ccheatsheet apex-b best-practices 3 apex-s security 4 force.c com-workbook 5 force.c com-cookbook 6 apex-d developer-guide 1 2
152
Salesforce Handbbook
buusiness applicattions up and running. r It delvves into the depths of the laanguage, explo ores many advvanced topics and include nuumerous tips and a tricks not aavailable in oth her documentaation. Key Conceepts As a deveeloper your ro ole is often to o translate a set of businesss needs into technical reqquirements. On n the Force.co om platform, most m logic that supports thosee technical reqquirements willl be implemen nted with Apeex. In order to o create logic with Apex theere are certain n language arttifacts and consstructs that are required, a few w of which are sshown in figuree 4 – 4. Listing 4 - 22 /* Varia able Declar ration */ List cont tacts; // Declaring D a collectio on Integer count = 0; ;
// Declaring D a simple pr rimitive
/* Execu uting an SO OQL Query */ * contacts s = [SELECT T id, lastn name FROM C Contact WHE ERE firstname = ‘Z Zack’]; /* Contr rol Structu ure */ for(Inte eger st tatement
i
=
0;
i
<
contacts. .size(
);
i++){
/ //
Loop
contacts[i].lastname == ‘de la Rocha’) // / if statem ment if(c cou unt++; } /* Varia able Manipu ulation */ contacts s[0].firstn name = ‘Zac ck’; /* DML O Operation */ * update c contacts;
Much of w what is shown n will be fam miliar to devellopers. As Ap pex is a stron ngly-typed lan nguage, you’ll n need to expliccitly declare vaariables before you can referr to them. In tthe above exaample we’ve ddeclared a variaable that can hold h a numberr, or Integer r, as well as a llist of the typ pe Contact. In Java and d other languaages there are distinct collecction-types callled arrays and lists. In Apex theyy are interchaangeable in th hat you can declare a collection as an array (o or vice versa) and then refeer to the arrayy and it’s elements using u array nottation, or referr to it as a list and it’s elemeents using 1
development-forcee.com-platform Jeff Douuglas & Wes Nollte
153
tthe List mem mber methods. Next N in the lissting you’ll seee an SOQL sttatement (as sh hown previously). Followingg that we’ve included one of several loop p-structures avvailable in Apeex, as well as an a example of an ifstatem ment used for code branchin ng. Again both h of these willl be familiar to t most develo opers. Lastly we’ve shown vvariable manip pulation and th he execution off a database up pdate-statemen nt. Excep ptions You Y can expecct a large part of your develo opment effort to be focused d on preventin ng and dealingg with runtimees errors. Som me of these errrors are expectted behavior but b there are o others 1 that yo ou can’t anticip pate, and on th he Force.com platform p thesee are called excceptions . T There is somee jargon to gett familiar with h when workin ng with excep ptions. W When an excep ption happenss developers w will typically saay that an exceeption h has been throw wn. To deal with w an excepttion gracefullyy you would uusually ssay that the exxception needss to be “caugh ht”. An exceptiion that is cauught is cconsidered to be b “handled”. Some S situation ns where exceptions might bee thrown are: •
You attemp pt an insert op peration on a reecord that is m missing required d data.
•
Assigning a query result that t returns no o rows to a singgle variable.
•
Accessing a member variiable on an objject whose valuue is null.
To T catch excep ptions requires a special consstruct called a ttry-catch blockk; this is comm mon in 2 other languages andd works in much m the sam me way . The syntax of a try-catch blo ock is demon nstrated in listiing 4 - 23. Listing L 4 - 23 try{ t account = null; n Account a account.A AccountNumb ber = ‘007’; // Null lPointerExc ception } catch (Nu ullPointerE Exception e) e { // Catche es above ex xception xception e) ) { } catch (Ex // The ge eneral exce eption handler. // Catche es all type es of exceptions. } finally { 1 2
intro-eexceptions excepttion-methods
154
Salesforce Handbbook
// Opt tional ‘fin nally’ bloc ck. // Cod de here run ns whether exception is thrown n or not }
Best practiice dictates th hat you don’tt just catch exceptions; youu should han ndle them appropriately too o. This often depends d on thee situation butt as an examplee it might be ssuitable to sen nd an email to an administraator or write a record r to a cusstom object ussed for loggingg. Hitting a Governor G Lim mit will throw aan exception that t can’t be ccaught (all processing stops immed diately). To avvoid this situation you can n use the methods of o the Limit class to graceefully stop a process before a limit is encountereed1. There will be times wh hen you’ll neeed to throw an exception n based on p predefined conditions. To ddo this you’ll haave to first decclare a custom exception usin ng syntax simillar to that shown in listing 4 - 24. Listing 4 - 24 // Decla are a new type t of exc ception public c class myExc ception ext tends Excep ption {} // Throw w an except tion of the e new type if (true e == false) throw ne ew myExcept tion(‘True False’) );
Catching cuustom exceptio ons is done thee same way as shown in listin ng 4 - 23. CR RUD Operatiions Creating, reetrieving, updaating and deletting data is do one through Apex A commandds as seen preeviously. The most common n commands as a seen previo ously are inse ert, update, delete and upsert (tw wo that appearr less frequenttly are undel lete2 and mer rge3). We’ve also seen ho ow to fetch andd work with th he results of an n SOQL query.. Apex also has a system class called Database D , wh hich allows more m control o over these op perations, as w well as provid ding transactio on-control feaatures4. As an example con nsider the exaample in listingg 4 - 25. Listing 4 - 25 SavePoin nt sp1 = Da atabase.set tSavePoint( ( ); try{ eResult sr = Database e.insert(ac ccount, tru ue, Save lim mit-class dm ml-undelete-docss 3 dm ml-merge-docs 4 database-methods 1 2
Jeff Douuglas & Wes Nollte
155
Database.Dmlopt tions.Assig gnmentruleh header); } catch (Sy ystem.Dmlex xception e) ){ Databas se.rollback k(sp1); }
On O the first lin ne we’ve used a feature not seen s before, naamely Save Points. For thosee who play gaames on comp puters or consoles, this is likke a “saved gam me” and allow ws you to jump p back to a previous p pointt should you choose to. In I the try-partt of the try-ccatch block w we are attemp pting to inse ert a record in i a different manner from before. We have h used the insert metho od of the Data abase class with w the record d we want to insert as the first f parameterr. The next parameter p is op ptional and dettermines wheth her to allow p partial success of o the operatio on i.e. if you are inserting a list of records and one of those t records iis problematic,, should the prrocess move onto the next record or fail outright. The next parametter is also optio onal and allow ws you to speecify additionall DML option ns such as asssignment rule information. Note N that with h this metho od a SaveRes sult is return ned which con ntains informaation about an ny errors that might have occurred o and w whether the traansaction as a whole w was succcessful. Should S the abo ove DML operation fail, th hereby throwin ng an exceptio on, the rollback metho od of the Dat tabase classs will be invo oked and anyy DML perfo ormed between n the savep point and th he rollback will be undon ne. You will ffind this featuure important when insertin ng many interddependent records in a singlle transaction w where a failuree to insert any single record d should removve all related in nformation wriitten in that traansaction. A Anytime you insert a new reecord, the variiable used to hold h the recorrd will tthen also contaain that record d ID in the dataabase. Trying to t insert that rrecord a second time will yield an error stating th hat you cannot insert a recordd that aalready has an associated ID.. One O convenien nce most deveelopers don’t initially i realizee is that DML L can be perfo ormed directly on collection ns of objects; this helps con nserve DML o operations keeeping you safe from Goverrnor Limits (a while longer at a least). Additiionally objectss are passed byy reference meeaning that when w a variablee containing an a object is paassed around yyour applicatio on the variablle just contain ns a pointer to o the true objecct. We’ve dem monstrated this in listing 4 - 26. Listing L 4 - 26 List contact ts = [SELEC CT id, firstname FRO OM Contact LIMIT 1 10]; for(Contact f t c: contac cts) c.First tName = ‘Za ack’; update u cont tacts;
Here H you see th hat you can loo op through a list l of Contactss changing thee first name vallue of each in ndividually. On the last line you’ll notice we’ve w applied the DML opeeration to the entire list, an nd the result off this is that eaach contact in the list will haave their first name n updated tto the 156
Salesforce Handbbook
value “Zack”. Essentially we have “indirectly” modified the field value and committed all of these changes in a single DML operation. Dynamic Apex Dynamic SOQL, Dynamic SOSL, sObject and field describe information, and Dynamic DML are the headline technologies that fall under the umbrella of Dynamic Apex. The first two have been covered already so we’ll start with the third feature1. As mentioned previously all objects are specific implementations of the sObject type. This implies that all methods available to the sObject type are also available to any other standard or custom objects. It also means that a variable of type sObject can hold a value whose type is any standard or custom object. List 3 - 26 demonstrates some valid examples of these two implications. Listing 4 - 27 public void myMethod(sObject s){ // Create two sObject variables that hold concrete objects sObject sAccount = new Account( ); sObject sCustom = new MyCustomObject__c( ); if(s.getSObjectType( ) == Account.sObjectType){ /* At this point we know that the passed sObject ‘s’ is an Account object. Static equivalent of below might be: account1.name = account2.name */ sAccount.put(‘name’,s.get(‘name’)); // ... } else { Schema.DescribeSObjectResult sDescribeResult = s.getSObjectType( ).getDescribe( ); if(sDescribeResult.isCustom( )){ // ... } } } 1
apex-describe-info Jeff Douglas & Wes Nolte
157
Notice N that youu can ask an sObject whicch specific typee it has implem mented (as sho own in the if-statement). Th here are other methods availlable that allow w you to interrrogate just abo out all 1 of the metadata thatt describes an sObject s . Ad dditionally youu also have access to field describe inform mation2, which yields all field d related detailss such as the ddefault value, the t type of fielld, the field leength, whether it’s unique, etc. e By combining field andd object describe information n you can wrrite source code capable off dealing with objects in a ggeneric way th hereby creatingg neat reusab ble componentts. A common usse of field desccribe informattion is the pro ogrammatic rettrieval o of picklist valuues. Fetching this t informatio on directly fro om the object fields eensures that yo ou avoid hard-ccoding values in your sourcee code. It I is also sensib ble at this junccture to point out that Apexx describe inforrmation is spliit into two data d structures viz. sObje ect/field tok ken and sObj ject/field describe d resultt. An importtant differencee between the two is that a token is a refe ference to an actual a entity buut the describ be result is an object that co ontains all the describe prop perties for said entity. An exaample of refeerring to a tokken is shown in the if-stateement of the aabove listing, with a token being issued either side o of the equalitty operator. In I the else-brranch of the same listing we’ve demon nstrated the rettrieval and usaage of an sObj ject describe result. Not N only can you dynamicaally fetch and describe dataa (or data con nstructs), Apexx also supporrts the ability to perform DML D on this data. d Aptly term med Dynamicc DML3 this feeature also allows you to construct sO Objects dynam mically, and wrrite the resultting records tto the databaase. Listing 4 - 28 bring all off these concepts together: •
Dynamic SOQL to fetcch a record. The T type is dettermined at ruuntime by the string passed to the dynamic cDML( ) meth hod.
•
An sObject of the saame type as th he queried typee is instantiateed using the to oken’s newSObj ject( ) meth hod.
•
In the if-eelse statementt we determinee the object tyype, and copy the queried ob bject’s field valuues to the new w object. We use u the get( ) and put( ) field assign nment methods for the sObje ect type.
•
Without kknowing the object o type up front a recorrd is inserted into the appro opriate object.
Listing L 4 - 28 public p void d dynamicDm ml(String objName){ o // Dynami ic SOQL string String qu uery = ‘SELECT id FR ROM ‘+objNa ame+ ‘ LIMI IT 1’; sobjecct-describe field-d describe 3 dynam mic-dml 1 2
158
Salesforce Handbbook
// Store the query result sObject obj = Database.query(query); sObject newObj; // sObject var that will be returned // Assign a token for the queried type Schema.Sobjecttype token = obj.getSObjectType( ); // instantiate the object with the token newObj = token.newSobject( ); // Determine the object type if(token == Contact.sObjectType){ // Set field value appropriate for contacts newObj.put(‘lastname’, obj.get(‘lastname’)); } else if (token == Account.sObjectType){ // Set field value appropriate for accounts newObj.put(‘name’, obj.get(‘name’)); } upsert newObj; }
A little documented feature is the ability to use fields in the same generic manner as objects. The Object class is to fields what the sObject class is to objects. Listing 4 - 29 should make this concept clearer. Listing 4 - 29 // Retrieve any field of the sObject Schema.Sobjectfield field = newObj.getSObjectType( ). getDescribe( ).fields.getMap( ).get(‘name’); // Assign it to a var of the generic type Object Object o = newObj.get(field); // ... // Use the Object var to dynamically fetch other field tokens anotherSObject.put(‘name’, o);
Together the capabilities of Dynamic Apex form a flexible framework with which to build code components that are intelligent in design and reusable across projects.
Jeff Douglas & Wes Nolte
159
D Don’t feel thaat it’s necessaary to make every area off your applicaations rreusable and sm mart with Dyn namic Apex. Th he real world is i not perfect sso not aall project piecces are destined d to be reusab ble. It is imporrtant to be awaare of D Dynamic Apexx and it’s capab bilities during the application design proceess so tthat when an opportunity o ariises you are reaady. The Future F Annotaation As A you might h have guessed the t Apex languuage syntax inccludes a numb ber of keywordds and annotaations, but onee comes up so o often and has such great uutility that it deeserves independent mentio on. You Y would ann notate a metho od with the fu uture keyworrd when you need n said meth hod to operatte asynchronouusly from the context in which w it is calleed1. Some usee cases for future metho ods are: •
Your app plication needss to make a web w service caall to a third party p and to rreduce latency yo ou wish to makke the callout asynchronous. a
•
When invvoking an Apeex method thatt performs a ccallout from a trigger, the method must be aannotated with h the future keyword. k
•
Governorr Limits withiin triggers aree typically smaaller than thosse of Apex cllasses. Firing a f future meth hod from triggger code ensurres that all op perations withiin the context o of the future e method are subject to Ap pex class limitts instead of trigger limits. Two T method siignatures are shown in listingg 4 - 30; the firrst shows a sim mple annotatio on and the oth her indicates th hat the method d will perform a web service call out. Listing L 4 - 30 // / Future a annotation in it’s si implest form @future @ public p stat tic void my yFutureMeth hod( ){ // Method d Body } // / Future a annotation with argum ment showing that // / this met thod will make m a call lout @future @ (ca allout=true e) public p stat tic void my yFutureCall loutMethod d( ){ // Method d Body } 1
future-method
160
Salesforce Handbbook
Before arch hitecting soluttions that use future f calls it’s importantt to note somee of these im mposed limitatio ons: •
You ccan’t make mo ore than 10 fut ture calls perr Apex invocattion.
•
Metho ods annotated as future caan only take prrimitive types, collections orr arrays of primittive types as th heir parameters.
•
Metho ods annotated d as future must m be stat tic and can only o have void d as their return n type.
•
Getteers, setter and constructors c of Apex contro oller cannot usee the annotatio on.
•
You cannot call a future meethod from a future metthod either ddirectly or indireectly.
•
For each salesforce.com license in n your Org yo ou can make 2000 future caalls per 24 hourss. For examplee, if you havee 100 user liceenses then youu Org has a b bucket of 20,000 calls it can isssue in a rollingg 24-hour periiod.
A common n pitfall conceerns the secon nd to last poin nt above. Deveelopers will offten mark meethods that arre called from m triggers as future. If these method ds then perforrm DML staatements theree is a chance that t the callingg trigger might be fired agaiin. In this casee you will haave inadvertently created a recursive r loop1 and the futuure method willl indirectly bee invoked byy itself causingg a System. .AsyncExcep ption to be thrown. Forr clarity the p process is shown in figure 4 - 4.
Figure 4 - 4. Recursive Future C Call Out
One effectiive solution is to maintain a global static B Boolean variab ble whose initiaal value is sett to false. Th he value of th his variable is interrogatedd when the trrigger fires an nd if the appropriate the ccallout is made. Within the callout methodd the variable value is set suuch that if thee trigger fires again the Boolean value will w prevent thee callout being made. Listin ng 4 - 31
1
reecursive-future-caalls Jeff Douuglas & Wes Nollte
161
shows the source code for this design pattern and figure 4 - 4 demonstrates the corresponding application flow. Listing 4 - 31 // Global Variable Class global class Globals { global static boolean isFuture = false; } public class with sharing MyClass{ // Future annotation with argument showing that // this method will make a callout @future (callout=true) public static void myFutureCalloutMethod( ){ Globals.isFuture = true; // ... } } trigger AccountBeforeInsert on Account (before insert) { // Check global control variable to determine if // callout has already occurred. if(!Globals.isFuture){ // Invoke the future callout method MyClass.myFutureCalloutMethod( ); } }
162
Salesforce Handbook
Figure 4 - 5. Control Varriable used to Prrevent Recursion n
Be aware that t (unless built in) you w will have no way w of determ mining if a future caallout has been n made in an installed manaaged package. You thus cannot use the above dessign pattern n to avo oid the System.A AsyncExcept tion in such a case. Co ommon Systeem Utility Claasses The Apex programming language has a number off system classees that handle common devvelopment tassks such as parrsing XML or making HTTP P call outs. Th hese reduce th he amount of boilerplate co ode you can exxpect to write,, and in doing so speeds youur developmen nt efforts. Heere we will outtline some of the most comm monly used of these. Syystem Class A versatile class this is used u for all th he common syystem function ns such as determining sysstem time, killiing and scheduuling jobs, debugging, unit teesting, resettingg passwords an nd more1. DO OM Classes The Docum ment Object Model M (DOM) classes facilittate the creatio on and parsingg of XML strrings2. Usually the DOM reepresents a neested tree of X XML nodes. The T XmlStream classes 3 offfer some low llevel support to o the DOM cllasses .
syystem-methods dom-classes 3 xm mlstream 1 2
Jeff Douuglas & Wes Nollte
163
HTTP Classes This suite of classes presents the core functionality available in HTTP requests and responses1. All the typical features including request types, headers, contents, and status codes are available through these classes. EncodingUtil Class A simple class used to encode and decode strings as URLs, Blobs or hexadecimal2. Crypto Class Quite often used in conjunction with the EncodingUtil class, this class facilitates the creation of Message Authentication Codes (MAC), digests and signature through the use of standard algorithms such as AES, SHA and MD53. Furthermore it provides the ability to encrypt and decrypt information for secure transmission and internal security. Test Class Used to setup test information such as faux Visualforce page references and to force asynchronous methods to run synchronously4. Limit Class Since Governor Limit exceptions cannot be caught it is important to know how near a specific limit is within the running context5. This class provides a number of methods to not only retrieve how close you are to a limit within the current context, but also the maximum value of that limit (within the executing context). Cookie Class This class allows server side access to any HTTP cookies that are relevant for the current domain6. PageReference Class Used to retain a reference to an instantiation of a page (Visualforce or other), this class enables convenient access to the URL, parameters, header, cookies and content of the page in question7. PageReferences can be instantiated or - if they are Visualforce pages - fetched using the page name e.g. for a page called “MyPage” you could assign it’s value to a variable using PageReference pr = System.MyPage;
http-classes encodingutil-class 3 crypto-class 4 test-class 5 limit-class 6 cookie-class 7 pagereference-class 1 2
164
Salesforce Handbook
Message Class Use this class for collection data validation errors1. For example if you present your users with a form, several fields might require adherence to a pattern such as URLs. In this case your Apex code would validate the user input, and if it didn’t conform you would instantiate an error message and add it to the page. Apex Triggers Triggers are common in most modern databases and are typically code units that are invoked before, during and/or after DML have taken place. Apex triggers are akin to these but use the Apex language for their syntax2. In this way Apex triggers are associated with salesforce.com objects the same way that database triggers are “connected” to tables. Triggers are convenient and reduce risk in data consistency, which can be demonstrated with an example. Consider an application on a platform that has no access to triggers but still has the concept of data persistence. If it was required that for every record you insert, an audit record needs to be created, you would have to manually ensure that code existed to insert audit information after each insert action. If your code has 100 places where inserts might occur, you’d need 100 calls to insert the audit information. Imagine missing one insert! Imagine the testing involved! On the Force.com platform such a situation would simply require one Apex class that handled the audit inserts, and a trigger on each audited object that made calls to the Apex class. If you have 100 insert statements across 5 audited objects, you’d only need to maintain a few lines in 5 triggers and 1 Apex class; the bulk of your testing would run over the Apex class. So you’ve reduced your risk since triggers will always fire on DML operations and you’ve reduced redundancy in your code through Apex code reuse. That said, Apex triggers can be tricky especially when you have a number of them that run on different DML events and at different times. In summary triggers can be set to fire before or after the following DML operations: •
Insert
•
Update
•
Upsert
•
Delete
•
Undelete
•
Merge
There are also specific rules concerning which actions are available during particular trigger events and timings3; it is important to know when certain triggers fire, as well as where
message-class intro-triggers 3 trigger-order-execution 1 2
Jeff Douglas & Wes Nolte
165
they faall within the greater order of things. Anyy object-recorrd subjected to o a DML operration will move through th he following ordered events: 1. 1
The origin nal record is lo oaded from thee database (or initialized for an insert statem ment)
2. 2
The new record field vaalues are loaded from the reqquest and overw write the old vvalues
3. 3
System vaalidation occuurs, such as veerifying that alll required fiellds have a non n-null value, andd running any user-defined u v validation ruless
4. 4
All beforee triggers execuute
5. 5
The recorrd is saved to the t database, but b not yet com mmitted
6. 6
All after ttriggers execute
7. 7
Assignmeent rules execuute
8. 8
Auto-resp ponse rules exeecute
9. 9
Workflow w rules executee
10. 1 If there arre workflow fiield updates, th he record is up pdated again 11. 1 If the reccord was updatted with workfflow field upddates, before an nd after triggerrs fire one moree time (and onlly one more tim me) 12. 1 Escalation n rules executee 13. 1 All DML operations aree committed to o the database 14. 1 Post-com mmit logic execcutes, such as sending s email Y You would bee wise to keep the documen nts that detail the t order of ttrigger eexecution closee at hand as th he rules are complex and not always intuitiive. If yyou have beforre- and after- insert, i update,, upsert and deelete triggers o on the ssame object, each e data row will be subjecct to their worrkings, the ordder of w which will be key. k Syntax x Trigger T syntax is similar to that of Apex classes with tthe notable differences bein ng the triggerr definition an nd a number of context variables v onlyy available witthin a trigger. The declaraation of a triggger adheres to the standards shown in listin ng 4 - 32. Listing L 4 - 32 trigger t MyT Trigger on ObjectName e (trigger_events) { // Trigg ger Body }
In I the above trigger_ev vents is a comma-separat c ted list of on ne or more o of the follow wing: 166
Salesforce Handbbook
•
before insert
•
before update
•
before delete
•
after insert
•
after update
•
after delete
•
after undelete
Observe th hat there is no o before un ndelete as tthere wouldn’’t be any dataa available before the undellete operation has h occurred. The contexxt variables speecific to triggers allow your aapplication to determine wh hat type of triggger is firing, w whether the trrigger is firing,, the number o of records in the trigger invo ocation as weell as access to o the old and new values (iif appropriate)) of the record ds moving thrrough the triggger1. Triggers allways execute in bulk i.e. eaach trigger is passed p a list o of objects which are contained in n Trigger.n new, Trigge er.old or b both. It’s therefore important i to design your ttrigger code realizing r that anywhere from 1 to 200 records can c be processsed in a singlee transaction. D Designing triggers thuusly is called making m them “b bulk safe” and it’s essential tto get into this habit early e on or youu will encounteer issues down the road. Listing 4 - 33 demonstrrates the usagge of some triigger context variables in p preventing Acccount names tto be changed. Listing 4 - 33 trigger AccountBef foreInsertU Update on A Account (be efore insert, before update) { igger.isUpd date){ if(Tri up pdates
//
Only
run n
the
fol llowing
co ode
on
gh the set of Ids for r all // Loop throug counts. Not te this cod de will // updated acc pdates // work for 1 or more up ldMap.keySe et( )){ for(Id oldId: Trigger.ol / //
Get
the e
account
information
before
and
afte er
the
up pdate 1
trrigger-context-varriable Jeff Douuglas & Wes Nollte
167
Accou unt newAcco ount = Trig gger.newMap.get(oldI Id); Accou unt oldAcco ount = Trig gger.oldMap.get(oldI Id); // Pr revent the account na ame from being edita able. if(ne ewAccount.n name old dAccount.name) newAc ccount.addE Error(‘Acco ount names cannot be e changed.’); } } }
If I this trigger w were invoked via the insert DML com mmand and an ny Account rrecord had an n error addedd during triggger execution the entire op peration woulld fail althouggh all “erron neous” recordds would be marked so. Using U the Da atabase.ins sert( ) method 1 howevver you could specify that paartial success was w acceptablee . It’s also worth mentioningg that the sim mple compariison functionality is purelyy for demonsstration and a validation ruule is probab bly more apt in n a real world scenario. Trigger T contexxt variables also o have a numb ber of caveatss, most of whiich are logical when given some s thought2. Some importtant considerations are: •
trigger r.old and trigger.new cannot c be usedd in DML operrations.
•
You can only change the t value of objects o througgh the trigge er.new variab ble in before trigggers. Changin ng in it after triiggers has no m meaning and will w yield an errror.
•
trigger r.old is read--only.
•
trigger r.new cannot be deleted.
R Relationship lo ookup objects in triggers are null3. So a triigger on Child__c w will have acccess to all fields availaable on this object inclluding C Child__c.Pa arent__c but it w will not have h access to C Child__c.Pa arent__r.An nyField wi without queryying that o object. SSalesforce.com m does this to reduce r the overrhead involved d when runningg data tthrough triggerrs. Imagine thee resource wastte if they selectted all related o object ddata for every trigger t executio on! T There is no way w to delete or deactiviatte a trigger once o deployed to a p production Orrg. One workkaround is to run your dep ployment in E Eclipse ffrom a sandbo ox (not the onee you actually deployed the original code from) tto production. During the deeployment pro ocess, deselect everything andd then ccheck the boxx next to “Deelete” for the unwanted triggger. Executin ng the triggerr-exceptions contexxt-variable-considderations 3 trigger r-lookup-null 1 2
168
Salesforce Handbbook
deployment will delete the trigger. Controlling Recursion It was previously shown how easy it is to create recursive loops with triggers and future calls. This type of infinite loop can occur just as easily if we take the future calls out of the equation1. A contrived example might involve a “reminder” Task being created for every Task that is inserted. Without a control structure the inserted reminder would itself trigger the same event and try to insert another reminder. This would continue ad infinitum. Avoiding this recursion is achieved much the same way as was shown with future calls. Listing 4 - 34 displays the code necessary to prevent the infinite looping. Listing 4 - 34 public with sharing class ReminderTask { // Variable used to flag reminder creation private static Boolean remindersCreated = false; public static Boolean haveCreatedReminders{get{ return remindersCreated; }set;} public static Task create(Task t){ Task reminder; // Logic to setup reminder fields ... return reminder; } } trigger SetReminder on Task (after insert) { // List that will contain all task reminders List reminders = new List( ); // Only execute the following code if the // hasn’t been set if(!ReminderTask.haveCreatedReminders){ for(Task t: Trigger.new){ reminders.add(ReminderTask.create(t)); } 1
trigger-recursion Jeff Douglas & Wes Nolte
169
// Set the flag to prevent recursion ReminderTask.haveCreatedReminders = true; insert reminders; } }
Using the remindersCreated flag, your code can determine if a reminder has already been created and can deal with that situation appropriately. Bulkifying Triggers Although Governor Limits are applied throughout the platform they tend to be a bit tighter if your Apex invocation begins within a trigger. It is therefore even more important to learn the coding patterns that will make your code more efficient, as well as those that are to be avoided. In the section on SOQL Governor Limits we showed the importance of fetching data upfront as opposed to executing queries within loops. A similar pattern is essential when coding triggers that are bulk safe. This ensures that the number of queries issued within a trigger is constant, and independent of the amount of data passing through the trigger. In the same way you will need to make sure that a constant number of DML operations are executed for each trigger invocation. We’ll build upon listing 4 - 14 to first illustrate the wrong way to write a trigger. Listing 4 35 details such an example. Listing 4 - 35 trigger AddOwnerColor on Account (before insert, before update) { /** EXAMPLE OF HOW TO -- NOT -- WRITE A BULK TRIGGER **/ // iterate over the list of records being processed in the // trigger and the color before being inserted or updated for (Account a : Trigger.new) a.Owner_Favorite_Color__c = [Select Favorite_Color__c from User Where Id = :a.OwnerId].Favorite_Color__c; }
Running 101 records (or 21 records if the entry point is a trigger) through this trigger would yield the same error as in listing 4 - 14, namely: System.DmlException: Insert failed. First exception on row 0; first AddOwnerColor: 170
Salesforce Handbook
error:
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY,
execution of BeforeInsert caused by: System.Exception: Too many SOQL queries: 101
Again you would get this error because you are violating the Governor Limit that restricts the number of SOQL queries you can issue. In this flawed design the number of queries is directly related to the amount of data moving through the trigger and can be remedied by fetching all the required data outside of a loop. As previously mentioned, in order to write bulk safe triggers it is critical that you understand and utilize sets and maps1. Sets are used to isolate distinct records, while maps are name-value pairs that hold the query results retrievable by record id. The correct way to bulkify this trigger is shown in listing 4 - 36 and is similar in many ways to listing 4 - 15. Listing 4 - 36 trigger AddOwnerColor on Account (before insert, before update) { // create a set of all the unique ownerIds Set ownerIds = new Set( ); for (Account a : Trigger.new) ownerIds.add(a.OwnerId); // query for all the User records for the unique userIds in // the records create a map for a lookup / hash table for the // user info Map owners = new Map([Select Favorite_Color__c from User Where Id in :ownerIds]); // iterate over the list of records being processed in the // trigger and set the color before being inserted or updated for (Account a : Trigger.new) a.Owner_Favorite_Color__c = owners.get(a.OwnerId).Favorite_Color__c; }
When the above trigger fires, you initially create a set containing every distinct OwnerId for the records being processed. Then you query to find all of the User records for each OwnerId in the set. This returns a map with the UserId as the key and the User object as the value. You then iterate over the list of Accounts in the trigger, use the map’s get method to fetch the correct User object by its OwnerId and write the User’s favorite color into a custom field (Owner_Favorite_Color__c) on the Account. 1
bulk-trigger-idioms Jeff Douglas & Wes Nolte
171
In using this idiom you will have guaranteed that no matter the number of records that are pushed through the trigger there will only be a single query executed. Testing Triggers One of the most common questions asked by new developers is, “How do I test triggers?” Although unit testing (modular pieces of code that test your source code) will be detailed in a later section it makes sense to introduce some of the concepts here. In order to test the above trigger you’d need to contrive a set of scenarios which might cause the trigger to fire, as well as know the expect outcome of each of those scenarios. We’ve written one such unit test in listing 4 - 37. Listing 4 - 37 @isTest private class TestAccountColorTrigger { static testMethod void testBulkInsert( ) { List accounts = new List( ); Profile p = [select id from profile where name=‘Marketing User’]; // create a user to run the test as User u = new User(alias = ‘test123’, email=‘
[email protected]’, emailencodingkey=‘UTF-8’, lastname=‘Testing’, languagelocalekey=‘en_US’, localesidkey=‘en_US’, profileid = p.Id, country=‘United States’, Favorite_Color__c=‘Buttercup Yellow’, timezonesidkey=‘America/Los_Angeles’, username=‘
[email protected]’); insert u; Profile p1 = [select id from profile where name=‘Standard User’]; // create a user to own the account User u1 = new User(alias = ‘test123’, email=‘
[email protected]’, emailencodingkey=‘UTF-8’, lastname=‘Testing’, 172
Salesforce Handbook
languagelocalekey=‘en_US’, localesidkey=‘en_US’, profileid = p1.Id, country=‘United States’, Favorite_Color__c=‘Pretty Pink’, timezonesidkey=‘America/Los_Angeles’, username=‘
[email protected]’+System.now( )); insert u1; // add 200 accounts to the list to be inserted for (Integer i=0;i MAX_PRESSURE){ throw new OverfilledException( ‘Exceeded maximum pressure.’); } // Use the ‘this’ keyword to refer to member variables // in ambiguous situations this.pressure = pressure; } // Method used to ‘inflate’ the tire by the units // of pressure stipulated by the passed parameter public void inflate(Integer units){ // “inflate” the tire //
Shorthand
for:
currentPressure
=
currentPressure
+
units; pressure += units; // If the tire is overfilled throw an exception if(pressure > MAX_PRESSURE){ Jeff Douglas & Wes Nolte
181
thro ow new Over rfilledExce eption( ‘E Exceeded ma aximum pressure.’); } } d used to ‘deflate’ ‘ t the tire by y the units s // Method // of pre essure stip pulated by the passed d parameter r public vo oid deflate e(Integer units){ u // Defl late the tire by the e amount sp pecified // if t the tire has h suffici ient pressu ure left if(pres ssure >= units){ u // Shorthand for: curr rentPressur re = curr rentPressur re – units s ssure -= un nits; pres }else{ If the numb ber of unit ts is more e than // I // t the current t tire pres ssure, just empty th he tire. pres ssure -= pr ressure; } } }
Essentially E we’vve explored th he property off tire pressure and some actiions we mightt want to exp pose as methods. From the code you can n see that a Ti ire has an in nitial pressure and a maxim mum pressure, and can be inflated or deflated. d Theree are rules arround inflation n and deflation, and if a Ti ire is overfilleed it might bu urst i.e. an Ove erfilledExc ception is thrown. As a ruule you need aat least 3 test methods m for thiis class, one fo or each of the public p methodds and anotheer for the consstructor. Y You might think that testingg such a simple constructorr is unnecessarry but tthe simple act of setting up the t unit test w will aid in the design process. Later w when other deevelopers add d functionality to the consttructor they w will be gguided by the sturdy s foundattion you will haave laid. After A creating such a class you need to consider how w you might test each of these metho ods. • 182
For the cconstructor thee test is simplee, pass in an arrgument and check c that the value of the meember variable pressure iss the same as th hat of argumen nt. Salesforce Handbbook
•
For tthe inflate method the obvious situattions to test are inflating tthe Tire within n the maximum m range, and filling it too m much. Other tests t you migh ht want to perforrm are filling the Tire byy zero units, o or filling it to o exactly the m maximum pressuure. These lasst two tests are a called bordder case tests and are imp portant as develo opers often maake logical erro ors on these frringes.
•
Testin ng the deflat te method is similar to sim milar to testing inflate. Yo ou’ll want to test deflating the Tire by a sm mall amount th hat results in so ome pressure b being left, deflatting the Tire by more units of pressure th han it contains and deflating it by zero units. It was men ntioned beforee that salesforcce.com requirees at least 75% % unit test code coverrage but what does d this mean n? In short youu’ll need at least 75% of your code (excluding uniit tests) to be executed by co ode that is invvoke from within a un nit test. For exxample in the iinflate method d there are threee lines of code that could c be execuuted; the line tthat throws thee exception wiill only be run by a teest method if th he exact condiitions of the suurrounding if-statement are met. Iff the condition n isn’t met on nly 2 out of 3 lines will be executed when the method m is calleed giving a codde coverage ratte of 66%.
Now that yyou know wh hat you need to t test, the neext step is to figure out how w to test. Beefore we discuuss the unit tesst code it’s wo orthwhile exam mining some of o the best praactices1 in thiis regard:
1 2
•
For aall conditional logic you neeed to execute all code bran nches e.g. in tthe above deflate method you y need to execute both th he if and thee else branch hes of the metho od body
•
Execuute both positive and neggative tests2 ii.e. test your methods witthin their thresh holds, but also force errors to o occur
•
Don’tt just catch exxceptions, han ndle them prop perly i.e. send d an email or “log” the error
•
Alwayys check the reesults of your code c execution n using Syste em.assert
•
Each class method should have att least one unitt test method
•
Comm ment your tests in detail statiing what you’ree testing and th he expected ouutcome
•
Coverr as many liness of code as yo ou can, although it’s not neccessarily best p practice to achievve 100%
•
If a b bug is uncovered write a unitt test specificaally for that buug to ensure th hat it isn’t accideentally reintrod duced
write-good-unit-te w ests un nit-test-example Jeff Douuglas & Wes Nollte
183
•
Each unitt test should have h a neatly defined test crriterion and sh hould only tesst one aspect of your code at a time
•
Unit test should functio on independen ntly of each oth her O On the last point you migh ht find that yyou’ve hardcoded some pieece of iinformation - such s as a URL L - into your aapplication cod de and this neeeds to cchange from environment e to o environmen nt. In this casee consider repllacing tthis value a Cuustom Setting (as ( mentioned in chapter 2).
With W these poiints in mind we’ve w created th he unit tests th hat cover the important i scen narios with reegards to the T Tire class. Listiing 4 - 43 conttains the unit teest code. Listing L 4 - 43 @isTest @ private p cla ass TireTes st { static testMethod d void post tiveConstru uctorTest( ) { /* Pa ass in a va alid Intege er for the pressure par rameter and check pu ublic var */ ger pressur re = 10; Integ Tire tire = new w Tire(pres ssure); he System.a assertEqual ls method outputs th he value of f // Th // bo oth parms in i the even nt of a failure Syste em.assertEq quals(tire. .pressure, pressure); } static testMethod d void nega ativeConstr ructorTest( ( ) { /*
I Initialise
the
tir re
with
m more
press sure */ try{ 300); Tire tire = new Tire(3 ch (Tire.Ov verfilledEx xception o){ }catc Sy ystem.asser rtEquals(o.getMessage e( ), ‘Exceeded maximum pr ressure.’); ; } 184
Salesforce Handbbook
than
the
maximum
} static testMethod void positiveInflateTest( ) { /* Test that if a tire is inflated within the threshold that the pressure is correct */ Integer initialPressure = 90; Integer inflationAmount = 20; Tire tire = new Tire(initialPressure); // Inflate the tire tire.inflate(inflationAmount); // Check that the current pressure equals the sum of // the passed values System.assertEquals(tire.pressure, initialPressure + inflationAmount); } static testMethod void negativeInflateTest( ) { /* Fill the tire by more than the maximum threshold; exception should be thrown */ Integer initialPressure = 90; Integer inflationAmount = 200; Tire tire = new Tire(initialPressure); // Over inflate the tire and catch the exception try{ tire.inflate(inflationAmount); }catch (Tire.OverfilledException o){ // Check for correct exception message System.assertEquals(o.getMessage( ), ‘Exceeded maximum pressure.’); } } static testMethod void positiveDeflateTest( ) { Jeff Douglas & Wes Nolte
185
/* Deflate the tire by an amount less than it contains; expect the amount to be subtracted */ Integer initialPressure = 150; integer deflationAmount = 50; Tire tire = new Tire(initialPressure); // Call the member method to deflate tire by argument amount tire.deflate(deflationAmount); // Check that the result is as expected System.assertEquals(tire.pressure, initialPressure - deflationAmount); } static testMethod void negativeDeflateTest( ) { /* Deflate the tire by more pressure than it contains; expect the tire pressure to be 0 */ Integer initialPressure = 150; Integer deflationAmount = 200; Tire tire = new Tire(initialPressure); // Call the member method to deflate tire by argument
amount
tire.deflate(deflationAmount); // Check that the result is as expected System.assertEquals(tire.pressure, 0); } }
We’ve added a positive and negative unit test for each method including the class constructor although there are other negative tests you could add e.g. passing method parameters that are null. You will find that in sufficiently complex methods you could write hundreds of unit tests to cover every possible scenario although this is not always necessary; instead test to a level that makes you confident in your code and if you do find bugs, add a test to explicitly cover that section of code.
186
Salesforce Handbook
A high ratee of code coverage and thorrough unit tessting are not n necessarily the same th hing. It’s quitee easy to achieeve high code coverage ratess since all you need to o do is executee 75% of the aapplication cod de. However a thorough set of unit tests might ruun over the sam me code manyy times, testingg granular aspects off the functio onality in vaarious ways. The distinction and combinatio on of these faccets is vital, an nd if your unitt tests are thorrough it is likely that you y will haven n’t more than suufficient code coverage. Daata Initializattion for Unit Tests T The translaation of the carr parts analogy into applicatio on code does well w as an introdduction to thee initial conceepts of unit teesting. To advaance your abillity to effectivvely test code it is now im mportant to intrroduce the bestt practices wheen testing meth hods that work with object record data. Consider th he simple triggger in Listing 4 - 44. This affter update triggger adds a Ta ask to an up pdated Accoun nt if the Indu ustry is “Softtware Develop pment”. Listing 4 - 44 trigger AddTasks on o Account (after upd date) { c so o that you don’t have e to // Declare a constant he value yo ou’re looki ing for // hardcode th S = ‘Software Developmen nt’; final String SOFT_DEV t the tr rigger will l create // The tasks that sks = new List( L ( ); List tas rough all the t updated d accounts // Iterate thr new){ for(Account a: Trigger.n / // De evelopment’
Check
if
the
account
y industry
is
‘So oftware
ystem.debug g(a.Industry); Sy if f(a.Industr ry == SOFT_DEV){ Task t = new Task( ); t.WhatId = a.id; ption = ‘Co onvert to C Cloud.’; t.Descrip tasks.add d(t); } } // insert all the tasks at once Jeff Douuglas & Wes Nollte
187
System.debug(tasks); insert tasks; }
One obvious positive test case is to ensure that the Task record is correctly created for such Accounts. To do this you need to mimic the way your application would initiate the firing of this trigger, and then check the end result. There are two mistakes that developers commonly make in this regard and the unit test code in Listing 4 - 45 demonstrates both of them. Listing 4 - 45 @isTest private class AddTasksTriggerTest { static testMethod void testAddTasks( ) { // Populate an Account object Account a = [SELECT id, name FROM Account WHERE Industry = ‘Software Development’ LIMIT 1]; // Update the account so that the trigger fires a.Description = ‘Cloud Service Provider’; update a; // Find the associated task Task t = [SELECT accountId, description FROM task WHERE whatId = :a.id ORDER BY createdDate DESC LIMIT 1]; // Check that the task is the one created System.assertEquals(t.description, ‘Convert to Cloud.’); } }
If you have the correct data in the environment that you’re coding in this test will pass; deploy it to an environment where there is no data, or there is the wrong type of data and it will fail. This is because you’re populating the Account variable with data selected from your objects and are thus dependent on the environment data and will most likely fail on deployment. The second issue here is that you should always test data-driven code (and especially triggers) in bulk working with as many test records as possible. Although the trigger in Listing 4 - 44 is bulk safe the unit test should double-check this (and this type of test will catch any future changes that make the trigger bulk sensitive).
188
Salesforce Handbook
Knowing these two potential design flaws you can add the following points to your testing best practices list: •
Each unit test should be portable between environments i.e. they can be deployed without alteration - to DE, sandboxes or production Orgs and still execute successfully. They should therefore not rely on record Ids, data, or other environment information (such as URLs).
•
As far as possible unit tests should operate in bulk
Listing 4 - 46 shows the improved unit test. Listing 4 - 46 @isTest private class AddTasksTriggerTest { static testMethod void testAddTasks( ) { // List of accounts that will be created List accounts = new List( ); // Populate the accounts list with dummy data for(Integer i = 0; i< 200; i++){ Account a = new Account(name = ‘Test’+i, Industry = ‘Software Development’); accounts.add(a); } // DML operation insert accounts; // We’ll need this set to find at the child tasks Set accountIds = new Set( ); // Add the account Ids and add some info for the update for(Account a: accounts){ accountIds.add(a.id); a.Description = ‘Cloud Service Provider’; } Jeff Douglas & Wes Nolte
189
// Use e the start tTest metho od as a precaution Test.s startTest( ); // Thi is should fire f your trigger t update e accounts; ; Test.s stopTest( ); ) // Fin nd the asso ociated tas sks for(Ta ask
t
:
[SELECT
a accountId,
ion descripti
FROM
task
WHERE E tId IN :acc countIds]){ { what // C Check that the task is i the one e you’ve cr reated Syst tem.assertE Equals(t.de escription n, ‘Convert t to Cloud. .’); } } }
We W are assertin ng the same reequirement in this unit test, but instead off relying on exxisting data we w have setup our own reco ords initially. We’ve W had to insert the reco ords first, andd then perforrm an update aas we are testin ng an after update u triggeer. We’ve also used 200 reco ords in this test to ensure th hat the triggerr is bulk safe. It I is not necesssary to write another a test fo or the case of o a single DM ML record ass bulk safe co ode should w work for any number n of reecords (includ ding zero). D Data created within w the co ontext of a un nit test is onlly available fo or the llifetime of thaat test. It is alsso only availab ble to that speecific test. Yo ou can eeven delete non-test data within the co ontext of a tesst without affe fecting tthat same data outside of thee test i.e. it is n not really deleteed. It I is often the ccase that a num mber of unit tests t share the same setup daata, and it therrefore makess sense to movve the data iniitialization intto it’s own meethod(s). For example e in thee unit test ab bove we migh ht have createed methods to o “initialize” account recorrds as is show wn in Listingg 4 - 47. Listing L 4 - 47 public p stat tic List ini itAccounts(Integer num){ n // List of account ts that wil ll be creat ted count> acco ounts = new w List( ); List Dev veloper -> Apex Class ses.
Figure 4 - 7. Apex Schedu uler 1
using-scheduled-ap pex Jeff Douuglas & Wes Nollte
193
You’ll be presented with a simple interface that let’s you choose a class and a restricted execution schedule i.e. the most often a class can be set to run is once a day. While this might be sufficient some of the time you’ll often need more flexibility than present here. The second option requires some development but is well documented and quite easy to use. For this approach you will typically need 3 classes or pieces of code: •
A class that implements the Schedulable interface. In doing this you will have to implement the execute method; this allows you to schedule the running of said class
•
A method or piece of code that is invoked from within the execute method above. This will perform the scheduled work
•
A call to the System.schedule method; this will dictate the execution schedule as well as the code that should be invoked. You can even make this call once off in an anonymous block
Listing 4 - 48 is a simple example that demonstrates all 3 of the above. You can get more detailed examples from the Force.com blog or in the Force.com Apex Code Developer’s Guide. Listing 4 - 48 global class ScheduledDataSync implements Schedulable { // Implementing an interface means we have to implement // any method signatures it contains. global void execute(SchedulableContext sc){ // The CustomerPortal class is not listed here. // This simply illustrates a call to another // classes member method CustomerPortal.sync( ); } } global class Scheduler { public static String invoke(String description, String schedule, Schedulable s){ // This call will schedule the job, returning the jobId return System.schedule(description, schedule, s); } public static void stop(String jobId){ 194
Salesforce Handbook
// This will l terminate e the sched duled uestion // job in qu ystem.abort tJob(jobId); Sy } } em.schedule method acccepts three paarameters. Thee first parameeter is the The Syste name or descrip ption of the job b you’re sched duling. The seccond is a Str ring value rep presenting thee schedule tim ming and uses th he following fo ormat: Seconds Minutes op ptional_yea ar
Hours
Day_of_mo onth
Mon nth
Day_o of_week
The third p parameter is th he class you’d like to executte. Figure 4 - 8 shows how tto use the combination of tthe two classess above to schedule an Apexx job.
Figure 4 - 8. Executing E a Sch hedule
The syntaxx used in the schedule parameter p takees some time to get used tto so you 1 N that w we have wrap pped the calll to the should bookmaark the docuumentation . Note Sy ystem.sched dule method in our own sttatic method m making it acceessible from V Visualforce pages too. The stop method ab bove simply stops the job wiith the passed job j Id. To see the status of a sch heduled job yo ou’ll need to lo og into your Orrg and click Se etup -> Mo onitoring -> Schedule ed Jobs. Fro om here you caan also alter th he schedule or delete the job b. A few thinggs to be aware of when workking with the A Apex Scheduleer are:
1
ap pex-scheduler Jeff Douuglas & Wes Nollte
195
•
Be wary of scheduling jobs from triggers. Only 10 classes can be scheduled at a time; if your trigger performs any bulk operations that result in a violation of this constraint you will receive an error
•
Jobs are added to a queue but the actual execution time varies depending on available resources
•
The users time zone will be used as the schedule basis
•
Callouts made from scheduled jobs must use the @future annotation
•
Do as much of the processing as possible before calling the execute method
Batch Apex Governor Limits are a good way of keeping all tenants on the Force.com platform in check, but sometimes you’ll have to work with massive sets of data e.g. data cleansing activities or archiving. Salesforce.com has created Batch Apex exactly for this purpose1. Similarly to Scheduled Apex you need to implement a specific interface in order to use the feature. The interface in question is Database.Batchable and requires that the following 3 methods be implemented: •
start
•
execute
•
finish
Listing 4 - 49 is an example implementation of the required interface and methods. Listing 4 - 49 global class UpdateSObjectField implements Database.Batchable{ global final String query; global final String fieldName; global final String fieldValue; global UpdateSObjectField(String query, String fieldName, String fieldValue){ this.query = query; this.fieldName = fieldName; this.fieldValue = fieldValue; }
1
batch-apex-intro
196
Salesforce Handbook
global Database.QueryLocator start( Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List scope){ // Loop through all objects in the scope // updating the field value for(Sobject s : scope){ s.put(fieldName,fieldValue); } // Update the batch update scope; } global void finish(Database.BatchableContext BC){ // Setup post-processing success email Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage( ); mail.setToAddresses( new List {‘
[email protected]’}); mail.setSenderDisplayName(‘Force.com Batch Processing’); mail.setSubject(‘Process Completed’); mail.setPlainTextBody(‘Congrats!’); // Send the email Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } }
The start method is called first and gathers all the records you’d like to work with. Notice that the method can return either of the following: Jeff Douglas & Wes Nolte
197
•
Databas se.QueryLoc cator referen nce. Use this w when the scopee of your batcch is a
simple SO OQL query. Note that your Governor G Lim mit here is 50 million m records •
An Iter rable. Used if the scope off your job is ccomplex, or if you want to d define your own n process of itterating througgh the list item ms. Normal Governor G Limiits are enforced in this case
The T start method, as well as a the oth her two, each acceptts a Datab base.Batcha ableContext t object as an n argument; it iis this object that t is used to track
the pro ogress of the b batch processin ng. The T execute method does the processin ng for each battch that it is passed. p It accep pts as it’s parrameters the D Database.Ba atchable context object aas mentioned previously p andd a list of sObjects o or parameterrized types. If you h have chosen to work with Datab base.QueryL Locator then n the list returrned by the staart method sho ould be used aas this second d parameter. The T finish meth hod, as its nam me implies, willl be used for aany post proceessing activitiess such as send ding emails. T To allow callouts from yourr batch class yyou’ll also need d to implemen nt the D Database.Al llowsCallou uts interface. If you’d likee to maintain state iinformation across batcches you’ll need to implement the D Database.St tateful interface. Once O you’ve crreated your claass you need a way to executte the batch an nd for that you’d use the Da atabase.exe ecuteBatch method. Listin ng 4 - 50 show ws such an exam mple. Listing L 4 - 50 // / Query to o fetch app propriate records r String S quer ry = ‘SELEC CT id, name e, industry FROM Acc count WHERE in ndustry = \’Informati \ ion Technol logy\’’; // / Instanti iate your batchable b c class UpdateSObje U ectField up pdateField = new Upd dateSObject tField( query, ‘ ‘industry’, , ‘IT’); // / Invoke t the batchin ng process Database.ex D xecuteBatch h(updateFie eld);
Some S importan nt consideratio ons are: •
198
Each batcch is discrete in its executio on i.e. if the ddata you subm mit is broken iinto 2 batches aand execution fails during baatch 2, all chan nges made in batch 1 will still be persisted. Salesforce Handbbook
•
As with Scheduled Apex it’s important to be cautious when invoking Batch Apex from triggers. Only 5 batches can be queued or running at any one time.
•
Calling the Database.executeBatch method adds the process to the queue but actual execution will only begin when system resources become available
•
Batch processes run asynchronously so you’ll need to use the Test.startTest and Test.stopTest methods in unit tests to ensure that the test batches complete before asserting the results
•
You can only invoke the execute method once within a unit test. You need to limit the scope of the batched records so that you do not violate this limit
•
You can only implement one callout in each start, execute and finish method.
•
Methods that are declared as future cannot be called from a class that implements the Database.Batchable interface. Nor can future methods be called from batch Apex methods.
•
The Database.executeBatch method cannot be called from any batch Apex method.
•
For every batch that runs a record is created in the AsyncApexJob object. Querying this object will give you information about the job’s status, number of errors, progress and submitter
•
All methods must be declared using the global access modifier.
•
You can also schedule batches to run using Scheduled Apex.
Have a look through the official documentation1 for more examples and a comprehensive syntax description. Governor Limits Although we’ve mentioned Governor Limits and best practices in avoiding some of them it’s time to step back and go into a bit more detail about why they exist and how they work. We’ve explored some of the detail regarding why such limits exist noting that in a shared environment it’s key that each community member doesn’t hog memory, processor or database resources2. This also goes a long way towards ensuring the scalability of the platform, as the resource consumption is defined and therefore predictable. Determining how a limit is calculated is up to 3 factors:
1 2
•
The Apex entry point
•
The number of data rows responsible for the invocation
batch-apex governor-limits-intro Jeff Douglas & Wes Nolte
199
•
The type off Governor Liimit
Apex Entry Points The T Apex entrry point can be b described ass the application area wheree the code was first invokeed. For examp ple if a web serrvices method is called and tthis in turn cauuses a trigger tto fire the Ap pex entry pointt is the web service context. Apex can be in nvoked in the following wayys: •
Apex Triggger
•
Apex standdalone class
•
Apex web sservice
•
Anonymouus block
•
Visualforcee page controlller (or extensio on)
•
Unit Tests
The T official documentation describes d the lim mits based on entry point in n detail1. As A an examplee consider a class that is callled from a triggger as well ass a Visualforcee page contro oller. When invvoked by the controller c the class can issuee up to 100 SO OQL queries. IIf it is called from a trigger however it can n only issue 200. It’s I essential to o know that any a other codee or triggers th hat run based on the entry point invocaation will contrribute to total consumer ressources i.e. if a web service is i called and in n turn fires a trigger as welll as calling a method m in a utillity class, all co ode and data acccessed througgh the triggerr and utility claass will contribute towards th he Governor L Limit. Data Volume V Some S Governor Limits scale with the am mount of dataa being proceessed. For exaample the lim mit on DML rows when th he entry poin nt is a trigger is 100. If youu were to passs the triggerr batches of 110 rows the limit becomes 1000; if yourr batches are 100 1 records in n size the lim mit is 10,000. Effectively th his limit is thee batch size m multiplied by th he listed Govvernor Limit. W When reworking very large datasets - durring paginatingg for example - you ccan often achieeve much faster results by uusing client-sid de languages suuch as F Flash or JavaSScript2 to perrform any maanipulations. This T has the aadded aadvantage of skkipping any co oncerned Goveernor Limit im mpositions. Goverrnor Limit Tyype Different D limit types have diffferent values but b the differen nce between th he types isn’t aalways obviouus to beginnerrs. For examplle, the limit fo or “Total numb ber of SOQL queries issuedd” for 1 2
govern nor-limits client--side-data-manipuulation
200
Salesforce Handbbook
triggers is 20, but the limit for “Total number of records retrieved by SOQL queries” is 1000 (and this scales with batch size). The difference here is that the first limit concerns how many times the executing code calls a “SELECT value FROM Object” statement, whereas the second limit governs how many records all of the statements collaboratively fetch. Executing Code Asynchronously Previously we have mentioned that it is advantageous to use the future annotation to split off an asynchronous execution from the current users context to improve performance. We’ve also lightly discussed how this can be used to step around certain Governor Limits. Exploring this in a bit more detail, you’d typically invoke code asynchronously when there is a large amount of processing to undertake and you don’t want to force the users to wait for it to complete. This approach is also popular when avoiding certain Governor Limits1. When invoking such code it forks from the executing context (which is synchronous) and moves into a transaction of it’s own. By doing this you save the user time, and that thread starts it’s Governor Limits afresh; the limits applied are those specific to Visualforce controller or web service entry point limits. Testing As mentioned in the section on unit testing, it is key that you test your code with sufficiently large datasets. Always test triggers, for example, with at least 200 records to test the appropriate limits. Debugging Apex Earlier in the chapter we detailed Anonymous Blocks, the System Log Console2 and the Debug Logs3. Each of these can be used to test your application, from small sections of code to fully features application areas. It can often take time to understand4 the output of the logs, but you can set filters5 on each of these tools to tailor the verbosity of their output. What we haven’t covered yet is how to populate these logs with data that you think is important when debugging. Although we’ve discussed the Force.com System class before we have not detailed how to use it when bug hunting. System.Debug is an overloaded method that accepts 1 String parameter (the message to output), 1 enumerated parameter (a logging level), or two parameters (the message to output as well as the enumerated logging level). The syntax for each is shown in Listing 4 - 51. Listing 4 - 51 // Set filters
the
logging
level.
Similar
to
using
the
debug
log
too-many-dml-rows system-log-console 3 howto-view-debug-logs 4 understanding-debug-logs 5 debug-log-filters 1 2
Jeff Douglas & Wes Nolte
201
System.debu S ug(LoggingL Level.FINES ST); // / Sample d data initia alization List accoun nts = [SEL LECT id, n name FROM Account LIMIT 10]; Map accou untMap = ne ew Map( [SELECT id, name FROM F Accoun nt LIMIT 10 0]); // / Output a at DEBUG le evel System.debu S ug(‘List of f accounts: : ‘ + accounts); // / Output a at INFO lev vel System.debu S ug(Loggingl level.INFO , ‘Map of accounts and Ids: ‘ + accountM Map);
The T method w with a single parrameter impliccitly sets the lo ogging level to debug. Noticee how the loggging levels aree correlated to o the filter optiions when deb bugging? Usingg logging levels, you contro ol what outpuut is seen when a certain log filter is aapplied. Logging levels obeey the follow wing hierarchy ((from lowest to highest): •
ERROR
•
WARN
•
INFO
•
DEBUG
•
FINE
•
FINER
•
FINEST
That T is, any deb bug messages set with a leveel of ERROR will always app pear in the loggs, but messagges set with a lo ogging level off FINEST are only o output if tthe debug filterr is set to “Finest”. W While calls to System.deb S bug are not co ounted for unitt test code covverage tthey do each count as a liine against thee Scripted Staatements Govvernor L Limit.
The View V With W the Moddel and Contrroller parts off MVC out o f the way it’s time to detaail the View. The View on n the Force.co om platform can be createed in one of two t ways; the page layoutts seen in ch hapter 2 or highly h custom mizable Visuaalforce pages. Visualforcee is a 202
Salesforce Handbbook
component-bas ed frameworkk for the Forrce.com platfo orm1. It is usses an XML ttag-based lan nguage to buuild dynamic components and pages that are rendered as HT TML and JavvaScript at run ntime. The languaage includes a large, l well-doccumented com mponent libraryy as well as thee ability to creeate your ow wn components. Standard and custom components include a nuumber of convenient funcctions familiaar in most front-end fr langguages, as weell as baked-iin AJAX fun nctionality. Addditionally youu can include any a amount of HTML and JaavaScript in V Visualforce pages allowing ffor the creation of sophisticcated, modern user interfacees. These interrfaces can alsso be context aaware in that they t render diifferently when n viewed on different devicees such as slaate computers or mobile deviices. Th he System Arcchitecture Figure 4 - 9 shows the Visualforce V systtem architectuure for develop pers while Figuure 4 - 10 demonstrates thee same system for users.
Fig gure 4 - 9. Visuaalforce system arrchitecture as exxperienced by a developer
When deveeloping Visualforce pages th he source codee is sent to the application sserver for compilation (on every save by default). Heree it is checked for errors, and if none existt it passes he metadata sttore as well ass to the page renderer. Thee renderer thee compiled paage code to th parses the Visuallforce code ouutputting the reesulting HTML L page.
1
in ntro-visualforce Jeff Douuglas & Wes Nollte
203
Figure 4 - 10. Visualforce system architecture as experrienced by an en nd user
End E users woulld skip the com mpilation step necessary n with developers. In nstead a page reequest is issueed to an applicaation server, wh hich is passed along a to the meetadata store. From F here the sstored page definition d is passed to the pagee renderer, whicch outputs the resultant HTM ML page. As A mentioned previously thee components of an MVC fframework aree decoupled in n their interdeependence butt it is necessarry to bind them m together to achieve the desired function nality. The tie between view w and model here is achievved through th he controller, which w also pro ovides the corre application logic. These co ontrollers takee a number of fforms namely: •
The standaard object conttrollers (these are a automaticaally generated)
•
Apex contrroller extension ns with object standard conttrollers
•
Custom controllers writteen in the Apexx programmingg language
Knowing K when n to use each is largely based d on experience but the follo owing rules go some way to owards assistingg in the decisio on-making:
204
•
Standard controllers on n objects functtionality such as data views,, data creation n, data modificattion and data deletion. Since they are auttomatically gen nerated you ddo not need to w write any Apeex code, creatte any unit tests or undertaake any of the risk associatedd with writing your own cod de. Use this co ontroller type when w your inteention is to displlay and edit infformation speccific to an objeect and any of its related objeects
•
Use contrroller extensio ons when yourr pages need to o be object-sp pecific but there are additionall features requuired that could dn’t be exposeed with standarrd controllers aalone. Controlleer extensions require a consttructor that acccepts as a paraameter the stan ndard controllerr that it is exten nding. Salesforce Handbbook
•
Custom controllers will be required on pages that aren’t tightly associated with an object, or if the page requires technically complex functionality. They are also useful when creating mashups by integrating with third-party technologies such as Twitter or Google Docs.
MVC: Bringing it all Together You are finally in a position to understand how Apex, Objects and Visualforce all come together to form a system based on the MVC design pattern1. Although Visualforce syntax will be discussed later it’s prudent to analyze the code in listing 4 - 52 to gain an understanding of how these components synergize. The code listed here is a complete Visualforce page that uses a standard controller. Listing 4 - 52
Visiting this page in a browser would render an HTML document as shown in Figure 4 - 11.
1
mvc-visualforce Jeff Douglas & Wes Nolte
205
Figu ure 4 - 11. MVC Working Togetther
Notice N how thee model, view and a controller come c together to create a pagge that allows yyou to manipuulate persisted information. From F the codee listing, the Acccount object’ss standard con ntroller fulfills the “controllerr” role. The ab bility to fetch object o field valuues as well as th he save action all fall into th he controllers domain. The Acccount object ittself, along with h the data it holds is the “moddel” in this case, and the Visuualforce markuup (including co omponents) forrms the “view””. W When startingg out with Visualforce ddevelopment it will be h highly aadvantageous if i you use the Developmentt Mode Footerr mentioned eearlier. IIn using this environment e a of your too all ols (including reference r mateerials) aare in the sam me convenient location, and you’ll have acccess to Visualforce ccode completio on as well as helpful h functionality e.g. it will w provide a hotlink tto create a con ntroller extensiion if you refeerence one thatt does not yet exist. A Additionally evvery time youu save the results of your coding effortts are p present in the same s window giving you instant results. When n would you u use Visualforcce? Standard S pagess are good forr creating, displaying and editing data sto ored in standaard or custom m objects. Youu can quickly manipulate m thee field layouts with the layo out editor, but there will bee times when yyou need an ad dditional field on the page tthat doesn’t neeed to be associated
206
Salesforce Handbbook
with an object. Or perhaps you’d like to include, for instance, visually complex dashboards in your standard pages. These situations call for the use of Visualforce pages, although it isn’t necessarily obvious up front. The following list will aid you when making such decisions: •
Upon clicking a button on a standard page, such as save or new, you’d like the user to be redirected to a bespoke page. This page would be Visualforce and you would override the standard functionality on the object in question to redirect to this page. Note that if appropriate, object information such as the Id will be passed to your page as request parameters
•
Customizing the detail tab for an object would require the creation of a Visualforce page which would override the standard tab page
•
In order to create tabs that aren’t directly associated with an object you can create custom Visualforce tabs
•
To embed custom functionality in standard pages you can create Visualforce pages and add them to the standard page detail layouts inline
•
Creating custom components using third party technologies - such as Google Visualizations requires the use of Visualforce
•
Visualforce pages can be used to create wizards for custom processes or workflows
•
You will use Visualforce pages when building public facing Force.com Sites
Advantages of Using Visualforce In addition to Visualforce fitting neatly into the MVC design pattern there are a number of other gains to be made, both by developers and platform users. •
User-friendly development environment. The in-page IDE is an example of developer web applications. It’s intuitive for beginners and works well. When you’re more comfortable with the Force.com platform you’ll naturally start working in Eclipse which itself is superb tool
•
Easy integration with just about any other technology that can be embedded in or work alongside HTML
•
Neat, cross-browser compliant UI components
•
Highly configurable and intelligent component library. For example, instead of defining field types for email address, select lists and dates you can use one intelligent component which will recognized the field type and apply the appropriate display style and functionality
•
Visualforce pages are hosted on the Force.com platform making their performance just as good as that of standard pages, no matter the volume of data
Jeff Douglas & Wes Nolte
207
•
Upgrades are automated and backward compatible. You will never have to change any code, or worry about compatibility issues
Visualforce Controllers Controllers provide business logic for your Force.com application e.g. what data to present in a page or which action to perform when a button is clicked. There are several types of controllers each powerful when used appropriately. Determining when to use each is best taught through demonstration. If we were to rank all controller types in increasing order of complexity and flexibility the list would be: •
Standard Controllers (including list controllers)
•
Controller Extensions
•
Custom Controllers
You can use this - to some degree - to guide you in making the choice of when to use each controller type. Of course it will take some experience with the platform to learn what Force.com defines as complex. Standard Controllers Standard Controllers are automatically generated for each standard and custom object that can be queried using the Force.com API1. They contain the same logic and functionality found in standard pages using the Save method of a standard controller equates to the same as clicking Save in a standard page. Any page that uses a standard controller will automatically inherit that objects standard page styles. To help you understand some of the upcoming topics please consider Listing 4 - 53. Listing 4 - 53 1
standard-controllers
208
Salesforce Handbook
BlockSectio on> BlockButton ns>
standardController=“Account”
Jeff Douglas & Wes Nolte
211
->
The code is commented appropriately but notice how we have declared a recordSetVar in the page element and used this later in a pageBlockTable element to
iterate over each item in the list. Here you can see that it’s not only possible to access each list item but you can also filter what is seen by using a combination of the {!filterId} and {!listviewoptions} particular to Standard List Controllers. By combining all of these list controller features we’ve very quickly created a page that is easily customizable and serves as a filterable view and mass update screen. We have named this page AccountListPage and access it by typing https://[salesforce_domain]/apex/AccountListPage into our browser. The rendered page is displayed in Figure 4 - 12.
212
Salesforce Handbook
Figure 4 - 12. The Renderred Standard Lisst Controller Page
In addition n to the two methods abo ove, there aree other action ns available to o specific 1 components wh hen using Staandard List Controllers C tthat control save-behavior and list navvigation. Another notable n component in thiss page is pa ageMessages s. If any standard or o validation errrors occur on n the page theey will automaatically be displayed in i the position n of this tag. This compon nent is availab ble for all controller types. t s but youu’ll often wan nt to navigate to such a Creating lisst pages is obvviously quite simple page from one o of the standard d object pages2. In this case aall you’ll need to do is speciffy that the custom button th hat is added to o your standarrd page have a Display Ty ype of List Button, and on your list p page use the {!selected} expression to o access the reccord collection n. The follow wing considerattions are imporrtant when wo orking with Staandard Set Con ntrollers: •
Only 10,000 records can be return ned by a list co ontroller
•
If no filter is specifiied then the lasst used filter fo or the object iss used
•
Recorrds sort on thee first column of o data
•
You can traverse relationships r in n the same w way and to the same degree as with Standdard Controllerrs
•
Tabs can be overrid dden with Stan ndard List Con ntroller pages in i the same waay as with Standdard Controllerrs
Co ontroller Exteensions There is a lot of overlap p in the detail of Controller Extensions and Custom Controllers altthough the forrmer serve as a neat introduuction to the laater. Each are implemented using the Ap pex programm ming language and have all of the languuage features available a to th hem. The 1 2
sttandard-list-contrroller-actions cuustom-list-button ns Jeff Douuglas & Wes Nollte
213
dividin ng line betweeen the two is in i the way eacch is “initialized” and the situations that make each appropriate to uuse. Controller C Exttensions are used u to augmeent the functiionality provid ded by Standaard or Custom m Controllers.. Standard Con ntrollers have a number of vvaluable featurres so if your aaim is to add d a few small actions (such as a web servvice call) to an n otherwise siimple page you can create a Controller Extension and add it to th he page. You might consideer creating Cuustom Contro oller extension ns when you have h functionallity that you neeed to reuse in n a number off areas and th hat functionalitty can be neatlyy packaged intto an extension n. IIt is of the utm most importan nce that you remember that Custom C Contrrollers aand Controllerr Extensions operate o in system mode i.e. they ignore prrofileb based permission and field--level security.. To force ad dherence to a users p permissions an nd security witthin these classses you must declare them using tthe with sha aring keyworrds. Strictly S speakin ng, a Controlleer Extension iss any class thatt has at least one o constructo or that acceptts a singlee argument of either ApexPages s.Standard dController r or Custo omControlle erClass wh here CustomC ControllerClass is a class that yyou’ve defined as a page con ntroller. D Do not define Controller Exxtension metho ods with the saame name as aany of tthe Standard Controller acttions e.g. savee. The page will w not be ab ble to ddetermine whicch controller method m you wiish to call (would you?). As o of the ccurrent version n it will favor the t Standard C Controller meth hod. Listing L 4 - 55 shows the conttroller extensio on and Visualfo orce page codee. Listing L 4 - 55 public p with h sharing class c Contr rollerExtension { private Contact co ontact; /* ontroller extension is instant tiated usi ing a variable The co type ‘St Apex object of tandardCont troller’. This encaps sulates th he Contact t record used in the Standard Contro oller */ public C ControllerE Extension( ApexPa ages.Standa ardControll ler stdCont troller) { // get tRecord( ) returns an n sObject s so you need d to cast // the e object ap ppropriatel ly 214
Salesforce Handbbook
contact = (Co ontact)stdC Controller. .getRecord( ( ); } /* ‘get’ and ‘set’ ‘ parts s of gette ers and set tters are i ignored The ‘ in ca alls from Visualforce V e pages. */ publi ic String getHelloWor g rld( ) { ret turn ‘Hello o ‘ + conta act.firstna ame; } } age standar rdControlle er=“Contact t” {!he elloWorld}< BlockSectio on> < > ield value= =“{!account t.name}”/>
orm > Jeff Douuglas & Wes Nollte
285
title=“Master
Categories”
286
Salesforce Handbook
Listing 6 - 18. Corresponding Controller Extension public class with sharing MultiSelectController { // reference for the standard controller private ApexPages.StandardController controller {get; set;} // the record that is being edited private Opportunity opp; // the values of the selected items public string selectedLevel1 {get; set;} public string selectedLevel2 {get; set;} public string selectedLevel3 {get; set;} public List level1Items { get { List options = new List( ); options.add(new SelectOption(‘‘,’-Choose a Category-’)); for (Cat1__c cat : [select Id, Name from Cat1__c Order By Name]) options.add(new SelectOption(cat.Id,cat.Name)); return options; } set; } public List level2Items { get { List options = new List( ); if (selectedLevel1 != NULL) {
Jeff Douglas & Wes Nolte
287
options.add(new
SelectOption(‘‘,’-Choose
a
Category-
’)); for (Cat2__c cat : [select Id, Name from Cat2__c Where Cat1__c = :selectedLevel1 Order By Name]) options.add(new SelectOption(cat.Id,cat.Name)); } return options; } set; } public List level3Items { get { List options = new List( ); if (selectedLevel2 != NULL) { options.add(new
’));
SelectOption(‘‘,’-Choose
a
Category-
for (Cat3__c cat : [select Id, Name from Cat3__c Where Cat2__c = :selectedLevel2 Order By Name]) options.add(new SelectOption(cat.Id,cat.Name)); } return options; } set; } public MultiSelectController(ApexPages.StandardController controller) { //initialize the stanrdard controller this.controller = controller; // load the record this.opp = (Opportunity)controller.getRecord( ); // preselect the current values for the record selectedLevel1 = opp.Cat1__c; selectedLevel2 = opp.Cat2__c; 288
Salesforce Handbook
selec ctedLevel3 = opp.Cat3 3__c; } public P PageReferen nce save( ) { // se et the sele ected value es to the r record befo ore saving opp.C Cat1__c = selectedLev s vel1; opp.C Cat2__c = selectedLev s vel2; opp.C Cat3__c = selectedLev s vel3; try { sert(opp); ups } cat tch(System.DMLExcepti ion e) { Ape exPages.add dMessages(e e); ret turn null; } rn (new Ape exPages.Sta andardContr roller(opp) )).view( ); ; retur } }
Up ploading a Document using Visu ualforce The salesfo orce.com docuumentation fo or the inputF File Visualfo orce componen nt has an exaample of uplo oading a docum ment using the Standard Co ontroller. Heree is a quick exxample of usiing a Custom m Controller in n case you want w to make the upload prrocess part off a larger traansaction.
Figuree 6 - 10. Visualforce Form for Up ploading a File
Jeff Douuglas & Wes Nollte
289
Make sure you take a look at the finally-block in the controller below. The finally-block always executes when the try block exits regardless if an error occurs or not. You need to ensure you clear out document’s body (document.body = null) so that the blob is not automatically included in the serialized image of the controller. If you do not clear out the body, you’ll get the following view state error: Maximum view state size limit (128K) exceeded. Actual viewstate size for this page was…
Listing 6 - 19. File Upload Visualforce Page 290
Salesforce Handbook
Listing 6 - 20. Custom Controller to Perform Server-Side Upload public with sharing class FileUploadController { public Document document { get { if (document == null) document = new Document( ); return document; } set; } public PageReference upload( ) { document.AuthorId = UserInfo.getUserId( ); // put it in running user’s folder document.FolderId = UserInfo.getUserId( ); try { insert document; } catch (DMLException e) { ApexPages.addMessage(new ApexPages.message( ApexPages.severity.ERROR,’Error uploading file’)); return null; Jeff Douglas & Wes Nolte
291
} finally { dy = null; -- clears the viewst tate document.bod n Documen nt( ); document = new } Message(new w ApexPages s.message( ApexPages.addM everity.INF FO,’File up ploaded suc ccessfully’ ’)); ApexPages.se return null; } }
Uploading an Attachment using u Visuaalforce This T demo buuilds upon th he previous one, o showingg an example for uploadin ng an attachm ment for a co ontact. The Visualforce V paage and Contrroller is very similar with a few excepttions.
Fig gure 6 - 11. Visuaalforce Form forr Uploading a co ontact Attachmeent
Attachments A aare different than t Documeents and are only availablee for the follo owing objects:
292
•
Account
•
Asset
•
Campaign
•
Case
•
Contact Salesforce Handbbook
•
Contract
•
Custom objects
•
EmailMessage
•
EmailTemplate
•
Event
•
Lead
•
Opportunity
•
Product2
•
Solution
•
Task
Salesforce.com restricts an attachment size to a maximum size of 5 MB. For a file attached to a Solution, the limit is 1.5MB. The maximum email attachment size is 3 MB. You can contact salesforce.com support and possibly have them increase these limits. They should be able to increase the document and attachment size to 25MB. They cannot increase the limits for emails. Listing 6 - 21. Visualforce Code for Upload an Attachment
value=“{!attachment.name}”
Jeff Douglas & Wes Nolte
293
value=“Description”
Listing 6 - 22. Corresponding Controller for Uploading Attachments public with sharing class AttachmentUploadController { public Attachment attachment { get { if (attachment == null) attachment = new Attachment( ); return attachment; } set; } public PageReference upload( ) { attachment.OwnerId = UserInfo.getUserId( ); // the record the file is attached to attachment.ParentId = ‘0037000000lFxcw’; attachment.IsPrivate = true; 294
Salesforce Handbook
try { insert attachment; } catch (DMLException e) { ApexPages.addMessage(new ApexPages.message( ApexPages.severity.ERROR,’Error attachment’));
uploading
return null; } finally { attachment = new Attachment( ); } ApexPages.addMessage(new ApexPages.message( ApexPages.severity.INFO,’Attachment uploaded successfully’)); return null; } }
Visualforce and CSS When you start working on the Force.com platform, CSS is an area that can seem fraught with clunky hurdles. Overriding the salesforce.com CSS is a nightmare and we would recommend you either use the styles as salesforce.com has created them or start from scratch. Whether using the standard stylesheets or starting from scratch, the incorporation of CSS into your page can be very time consuming, especially if you are using images within your CSS. The typical process of developing CSS within Visualforce might be: 1.
Create a stylesheet with however many styles. At this point (unless you’ve used an external editor) you have no way of quick-viewing the result.
2.
Include said stylesheet and all referenced images in a zip file. Take care to preserve the directory structure so that you can reference all stylesheet and image files correctly.
3.
Upload the zip file as a static resource.
4.
Create references to the stylesheet in appropriate pages.
5.
View page.
If at this point you need to adjust your coded CSS you’ll need to go through the process from steps 1 to 5 once again. Luckily there are a few neat solutions to this problem.
Jeff Douglas & Wes Nolte
295
Visuallforce Pages aas Stylesheet Documents The T Visualforcce page com mponent has an n attribute caalled content tType. Settingg this attribuute to text/c css will instru uct the page to o render as a C CSS documentt. You can theen use the st tylesheet co omponent to in nclude this “C CSS page” in th he pages you wish w to style. Pros •
Quick pro ototyping of sttylesheets as th hey can be editted in the Forcce.com IDEs
•
Can include calls to controller method ds and global vaariables so valuues can be dynaamic
•
Can incluude static resouurces as imagess
Cons •
Not efficien nt as can’t be minified m or com mpressed
•
You lose th he neat organizzation of the trraditional arran ngement of filees and folders
Plainttext Static Resources as Styylesheet Documents Here H you’ll neeed to upload an a empty text file or an exissting stylesheett - in their plaaintext form - as a static resource. Next yo ou’ll need to suubscribe to thee metadata forr that static ressource in an Eclipse E projectt. Double clickking on the filee in the IDE w will open it in plaintext p in it’ss own tab and d (voila!) you’lll be able to ed dit the contentss directly. To T include th he styleshe eet in a pagge all you’ll n need is the standard styleesheet compo onent, and then n refer to the static s resourcee by name. Pros •
Quick pro ototyping of sttylesheets as th hey can be editted in the Forcce.com IDEs
Cons •
Can’t refeerence any reso ource outside of o the file
•
Not efficiient as they’re not minified or o compressed
•
You lose the neat orgaanization of th he traditional arrangement of o files and fo olders, and will p probably end up u with a prolifferation of CSSS static resourcce files
In I reality we teend to use one of the abovee approaches until our CSS reaches a relaatively compllete state with regards to ouur project goaals. Once we aare done we bundle b the CSS and imagess into a well-o organized folder structure which w we then compress and d upload as a static resourrce. Of course then you’ll neeed to update an ny pages that rreferenced the old static reso ource. C Can you guesss how to miinimize risk h here? What ab bout wrappin ng the rreference to th he stylesheet in n a componentt and using thaat in all your p pages? O Or perhaps ussing a Visualfo orce page as a site template and only inclluding sstylesheets therre? Either wayy you only needd to make chan nge in one placce. 296
Salesforce Handbbook
Redirecting Users to Different Visualforce Pages If your Org has a large number of records types, page layouts and Visualforce pages you’ll eventually be required to route users to various pages depending on roles and/or profiles. Unfortunately, you cannot assign Visualforce pages by record type so you have to implement a hack around it. What you need to do is create a “dispatcher” Visualforce page and accompanying controller extension, and then override the appropriate button/link action (view, edit or new) with this new dispatcher Visualforce page. The code is slightly different depending on whether you are doing view, edit or new so we’ll be showing them all. When a user clicks the view button/link for appropriate object, it loads the new Visualforce page. The Visualforce page loads the controller extension and performs some logic to determine if the user should be dispatched to your new view page (Contact_View_1) or the standard salesforce.com view page. You’ll need to override each link and button to call the specific Visualforce page as described in Chapter #2. Listing 6 - 23. Dispatcher Page for Viewing contacts
Listing 6 - 24. Controller Extension for the “View” Dispatcher Page public class with sharing DispatcherContactViewController { public DispatcherContactViewController( ApexPages.StandardController controller) { this.controller = controller; } public PageReference getRedir( ) { Contact c = [Select id, recordtypeid From Contact Where Id = :ApexPages.currentPage( ).getParameters( ).get(‘id’)]; PageReference newPage; if (c.recordtypeid == ‘111111111111’) { newPage = Page.Contact_View_1; } else { Jeff Douglas & Wes Nolte
297
newPage = new PageReference(‘/’ + c.id); newPage.getParameters( ).put(‘nooverride’, ‘1’); } newPage.getParameters( ).put(‘id’, c.id); return newPage.setRedirect(true); } private final ApexPages.StandardController controller; }
The code is somewhat similar for the edit and new use cases but does have some notable differences. Listing 6 - 25. Dispatcher Page for Editing contacts
Listing 6 - 26. Controller Extension for “Edit” Dispatcher Page public class with sharing DispatcherContactEditController { public DispatcherContactEditController( ApexPages.StandardController controller) { this.controller = controller; } public PageReference getRedir( ) { Id =
Contact c = [Select id, recordtypeid From Contact Where :ApexPages.currentPage( ).getParameters( ).get(‘id’)]; PageReference newPage; if (c.recordtypeid == ‘111111111111’) { newPage = Page.Contact_Edit_1;
298
Salesforce Handbook
} else { newPage = new PageReference(‘/’ + c.id + ‘/e’); newPage.getParameters( ).put(‘nooverride’, ‘1’); } newPage.getParameters( ).put(‘id’, c.id); return newPage.setRedirect(true); } private final ApexPages.StandardController controller; }
Listing 6 - 27. Dispatcher Page for Creating contacts
Listing 6 - 28. Controller Extension for “New” Dispatcher Page public class with sharing DispatcherContactNewController { public DispatcherContactNewController( ApexPages.StandardController controller) { this.controller = controller; } public PageReference getRedir( ) { PageReference newPage; if (ApexPages.currentPage( ).get(‘RecordType’)
).getParameters(
== ‘111111111111’) { newPage = Page.Contact_New_1; return newPage.setRedirect(true); } else { return null; } Jeff Douglas & Wes Nolte
299
} private final ApexPages.StandardController controller; }
RESTful Web Service Callouts using POST The addition of asynchronous Web service callouts to external services is a feature that developers have been requesting for quite awhile in salesforce.com. Using the new @future annotation, your methods execute the callout when salesforce.com has resources available. One of the great benefits is that it allows you to perform callouts during trigger executions. One method of performing callouts is to import your WSDL and let Apex do all of the heavy lifting (WSDL2Apex). The major problem that we found is that Apex does not support RPC/encoded services at this time. Apex does support HTTP service classes which will allow you to create RESTful services as an alternative. The HttpResponse class provides a simple GET example but it was hard to find any examples using POST. Listing 6 - 29. Apex Class to Perform HTTP POST public class with sharing WebServiceCallout { @future (callout=true) public static void sendNotification(String name, String city) { HttpRequest req = new HttpRequest( ); HttpResponse res = new HttpResponse( ); Http http = new Http( ); req.setEndpoint(‘http://my-end-point.com/newCustomer’); req.setMethod(‘POST’); req.setBody(‘name=‘+EncodingUtil.urlEncode(name, ‘UTF-8’)+’&city=‘+EncodingUtil.urlEncode(city,
‘UTF-
8’)); req.setCompressed(true); // otherwise we hit a limit of 32000 try { res = http.send(req); } catch(System.CalloutException e) { System.debug(‘Callout error: ‘+ e); System.debug(res.toString( )); 300
Salesforce Handbook
} } // Anonymou
test
-
run
WebServiceCallout.testMe(
);
from
Execute
public static testMethod void testMe( ) { WebServiceCallout.sendNotification(‘My Test Customer’, ‘My City’); } }
You can execute your callout in a trigger as in Listing 6 - 30. Listing 6 - 30. Example Usage of HTTP Method Call from a Trigger trigger AccountCallout on Account (after insert) { for (Account a : Trigger.new) { // make the asynchronous web service callout WebServiceCallout.sendNotification(a.Name, a.BillingCity); } }
A couple of things to remember when using the future annotation: •
No more than 10 method calls per Apex invocation
•
No more than 200 method calls per salesforce.com license per 24 hours
•
The parameters specified must be primitive data types, arrays of primitive data types, or collections of primitive data types.
•
Methods with the future annotation cannot take sObjects or objects as arguments.
•
Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
Force.com & Case-Sensitivity The Force.com platform is mostly case-insensitive. It’s difficult to find information on which areas are case-sensitive so we’ve compiled this list of what we’ve discovered thus far. Visualforce Templates The name attribute of the define component when referring to an insert component name. A suitable example might be that your application uses a Visualforce page as a template Jeff Douglas & Wes Nolte
301
and this template has an insert component, which allows you to merge other page content with the template. The code for the two pages is shown in Listings 5 - 31 and 5 - 32. Listing 6 - 31. A Visualforce Template Page
Listing 6 - 32. A Visualforce Content Page that Implements the Template Page
Note the name of the insert component is “Content”. Were you to change the name of the define component to “cOTenT”, the define component would be ignored. This behavior isn’t obvious, nor is it consistent since the string value used by the template attribute of composition component is case-insensitive. Apex Sets and Maps Listing 6 - 33 shows that Set values are case-sensitive; the uppercase and lowercase “A” are considered to be two separate values. Listing 6 - 33. A Set with Two Values static testMethod void setTest( ){ Set mySet = new Set {‘a’, ‘A’}; System.assert(mySet.size( )==2,’Set size: ‘+mySet.size( )); }
From this you can deduce that the range of key-values in a Map is also case-sensitive (they are contained in a Set).
302
Salesforce Handbook
Co omponent Idss & ReRendeer Visualforcee component Ids I are case-seensitive when used in a reRender attrib bute. Our guuess is that thiis area is case--sensitive becaause JavaScrip pt (a case-sensiitive language)) is being useed behind the scenes. Saalesforce.com 15 character Ids 15 characteer IDs are casee-sensitive, buut 18-characterr IDs are case--insensitive. Th here is an alggorithm for changing betweeen the two, butt the easiest waays to do this are a •
Use thee FIXID( ) formula f in the Excel Connecctor
•
Use Jefff Douglas’ Force.com Utilityy Belt for salessforce.com
•
Assign an Id containeed String-valuee variable to an n Id-value variable in Apex
Most String meethods This area o of case-sensitivvity is quite lo ogical since theese methods are a tasked with h working specifically on teext. More info ormation on String S methodss can be found d in the salesfforce.com Do ocumentation.
Caalling a REST Web Serrvice (XML L) This is an eexample of callling a REST web w service wiith Apex. You enter your adddress and thee Apex code ffetches the geo o coordinates from f Yahoo! M Maps. The serrvice returns th he data as XM ML. If you wantt to run this deemo in your ow wn Org, you w will need to do the following:: •
Add a “Remote Sitee” (Setup -> - Security y Controls s -> Remot te Site Setting) with the URL: U http:// /local.yahooapis.com m You can run this sam mple at https://jeffdouglas-deveeloper-edition.na55.force.com/ examples/R RestDemo
The Visuallforce page in n Listing 6 - 34 3 presents th he user with address a fields that they sub bmit to the ccontroller. Thee controller caalls the REST T web service and then dissplays the ressulting geo coo ordinates to th he user. Listing 6 - 34. Visualforrce Address Search S Using Yahoo! Mapss Jeff Douuglas & Wes Nollte
303
This example calls Yahoo! Map geocoding REST service with the address you provide below. Address City State
304
Salesforce Handbook
The submit method in Listing 6 - 35 is invoked from the Visualforce page when the user clicks the submit button. It passes the address info to the getMap( ) method which does the GET call to the REST service. We’ve used the XmlDom class to parse through the results and construct a GeoResult object (from the inner class) and then present the info as a String to the user on the Visualforce page. Listing 6 - 35. Controller used to make RESTful Call to Yahoo! Maps API public class with sharing RestDemoController { public String geoAddress {get;set;} public String address {get;set;} public String city {get;set;} public String state {get;set;} // set the Yahoo Application Id private String appId {get;set { appId = ‘[SOME-ID]’; } } // method called by the Visualforce page’s submit button public PageReference submit( ) { List results = getMap(address,city,state); geoAddress = results[0].toDisplayString( ); return null; } // call the REST service with the address info public List getMap(String street, String city, String state) { HttpRequest req = new HttpRequest( ); Http http = new Http( ); List results = new List( ); // set the request method req.setMethod(‘GET’); // set the yahoo maps url with address Jeff Douglas & Wes Nolte
305
String url = ‘http://local.yahooapis.com/MapsService/V1/geocode?appi
d=‘
+ appId + ‘&street=‘ + EncodingUtil.urlEncode(street,’UTF-8’) + ‘&city=‘ + EncodingUtil.urlEncode(city,’UTF-8’) + ‘&state=‘ + EncodingUtil.urlEncode(state,’UTF-8’); // add the endpoint to the request req.setEndpoint(url); // create the response object HTTPResponse resp = http.send(req); operation
//
create
the
doc-contains
the
results
of
the
REST
XmlDom doc = new XmlDom(resp.getBody( )); // process the results XmlDom.Element[] elements = doc.getElementsByTagName(‘Result’); if (elements != null) { for (XmlDom.Element element : elements) results.add(toGeoResult(element)); } return results; } // utility method to convert the xml element to the inner class private GeoResult toGeoResult(XmlDom.Element element) { GeoResult geo = new GeoResult( ); geo.latitude = element.getValue(‘Latitude’); geo.longitude = element.getValue(‘Longitude’); geo.address = element.getValue(‘Address’); geo.city = element.getValue(‘City’); geo.state = element.getValue(‘State’); 306
Salesforce Handbook
geo.zip = eleme ent.getValu ue(‘Zip’); return geo; } r class // inner private class GeoR Result { public String latitude; l public String longitude; l a public String address; c public String city; s public String state; z public String zip; t tring( ) { public String toDisplaySt ess + ‘, ‘ return addre + city + ‘, ‘ + state + ‘, ‘ + zip + ‘ [‘ + latitude + ‘, ‘ + longitude + ‘]’; } } }
Caalling a REST Web Serrvice (JSON N) Using JSON N RESTful Web W Services with w salesforce.ccom opens up p your Org to a number of third-party in ntegration oppo ortunities (Go oogle, Yahoo!, Flickr, bespokke, etc.). JSON N support isn n’t baked into the Force.com m platform butt Ron Hess at salesforce.com m has ported tthe JSON parser that will ddo the heavy liffting for you. We’ve put together a smaall demo wheree you enter your address and d the Apex codde fetches thee address and coordinates from f the Googgle Maps. Thee service returrns the data ass a JSON ob bject. You can run this sam mple at https://jeffdouglas-deveeloper-edition.na55.force.com/ examples/R RestDemoJson
Jeff Douuglas & Wes Nollte
307
To get started, you’ll need to download the JSONObject class and install it into a Developer Org or Sandbox. Unfortunately there is no documentation for the parser so you have to extrapolate from the json.org website. You’ll also need to sign up for a Google Maps API key in order to use their geocoding service. We would also recommend that you take a look at the docs for Google Maps geocoding service. Listing 6 - 36 is the Controller for the demo. The interesting stuff is in the getAddress( ) and toGeoResult( ) methods. In getAddress( ) the user-entered address is used to construct the URL for the GET call to the geocoding service. Make sure you properly encode the address or you may receive undesirable results returned from Google. One thing to point out is line #58. Google is returning a line feed in their JSON response that causes the JSON parser to choke. We simply replace all like feeds with spaces and that did the trick. Ron was going to look into making this change to the JSONObject class in the near future. We were also having some problems with the geocoding service so we hard-coded the returned JSON object for testing. We checked around and it seems to be a common problem that the Google Maps API randomly returns 620 errors when overloaded. You might want to take a look at the JSON response returned for the hard-coded address. We will give you a little insight for the parsing process. The toGeoResult( ) method parses the returned JSON response and populates the GeoResult object with the appropriate data. We chose this Google Maps example because it shows how to parse simple values, nested JSON objects and arrays. The coordinates for the address can either be returned as integers or doubles so we’ve had to check each one.
308
Salesforce Handbook
Listing 6 - 36. Controller to Make RESTful Calls using JSON public class with sharing RestDemoJsonController { public String geoAddress {get;set;} public String address {get;set;} public String city {get;set;} public String state {get;set;} public Boolean useGoogle {get;set;} // google api key private String apiKey {get;set { apiKey = ‘[SOME-ID]’; } } // method called by the Visualforce page’s submit button public PageReference submit( ) { if (address.length( ) == 0) { ApexPages.addMessage(new ApexPages.message( ApexPages.severity.ERROR,’Address cannot be blank’)); if (city.length( ) == 0) ApexPages.addMessage(new ApexPages.message( ApexPages.severity.ERROR,’City cannot be blank’)); if (state.length( ) == 0) ApexPages.addMessage(new ApexPages.message( ApexPages.severity.ERROR,’State cannot be blank’)); if (!ApexPages.hasMessages( )) geoAddress = getAddress(address,city,state); return null; } // call the geocoding service private String getAddress(String street, String city, String state) { String json; // hard-coded returned JSON response from Google Jeff Douglas & Wes Nolte
309
if (useGoogle) { json = ‘{ “name”: “1600 Amphitheatre Parkway, Mountain View, CA”, “Status”: { “code”: 200, “request”: “geocode” }, “Placemark”: [ { “id”: “p1”, “address”: “1600 Amphitheatre Pkwy, Mountain View, CA 94043, USA”, “AddressDetails”: { “Accuracy” : 8, “Country” : { “AdministrativeArea” : { “AdministrativeAreaName” : “CA”, “SubAdministrativeArea” : { “Locality” : { “LocalityName” : “Mountain View”, “PostalCode” : { “PostalCodeNumber” : “94043” }, “Thoroughfare” : { “ThoroughfareName” : “1600 Amphitheatre Pkwy” } }, ‘+ ‘ “SubAdministrativeAreaName” : “Santa Clara” } }, “CountryName” : “USA”, “CountryNameCode” : “US” }}, “ExtendedData”: { “LatLonBox”: { “north”: 37.4251466, “south”: 37.4188514, “east”: -122.0811574, “west”: -122.0874526 } }, “Point”: { “coordinates”: [ -122.0843700, 37.4217590, 0 ] } } ]} ‘; // call the geocoding service live } else { HttpRequest req = new HttpRequest( ); Http http = new Http( ); // set the method req.setMethod(‘GET’); // generate the url for the request String url = ‘http://maps.google.com/maps/geo?q=‘+ EncodingUtil.urlEncode(street,’UTF-8’)+’,+’ + EncodingUtil.urlEncode(city,’UTF-8’)+’,+’ + EncodingUtil.urlEncode(state,’UTF-8’) +’&output=json&sensor=false&key=‘+apiKey; // add the endpoint to the request req.setEndpoint(url); // create the response object HTTPResponse resp = http.send(req); // geocoding service is returns a line feed so parse it out json = resp.getBody( ).replace(‘\n’, ‘‘); } 310
Salesforce Handbook
try { JSONObject j = new JSONObject( json ); return toGeoResult(j).toDisplayString( ); } catch (JSONObject.JSONException e) { return ‘Error parsing JSON response from Google: ‘+e; } } class
// utility method to convert the JSON object to the inner private GeoResult toGeoResult(JSONObject resp) { GeoResult geo = new GeoResult( ); try { geo.address = resp.getValue(‘Placemark’).values[0].obj. getValue(‘address’).str; geo.keys = resp.keys( ); geo.name = resp.getString(‘name’); geo.statusCode = resp.getValue(‘Status’).obj. getValue(‘code’).num; // set the coordinates - may either be integers or doubles
geo.coordinate1 = resp.getValue(‘Placemark’).values[0].obj.getValue(‘Point’).obj.getV alue(‘coordinates’).values[0].num != NULL ? resp.getValue(‘Placemark’).values[0].obj.getValue(‘Point’).obj.getV alue(‘coordinates’).values[0].num.format( ) : resp.getValue(‘Placemark’).values[0].obj.getValue(‘Point’).obj.getV alue(‘coordinates’).values[0].dnum.format( ); geo.coordinate2 = resp.getValue(‘Placemark’).values[0].obj.getValue(‘Point’).obj.getV alue(‘coordinates’).values[1].num != NULL ? resp.getValue(‘Placemark’).values[0].obj.getValue(‘Point’).obj.getV alue(‘coordinates’).values[1].num.format( ) : resp.getValue(‘Placemark’).values[0].obj.getValue(‘Point’).obj.getV alue(‘coordinates’).values[1].dnum.format( ); geo.coordinate3 = resp.getValue(‘Placemark’).values[0].obj.getValue(‘Point’).obj.getV alue(‘coordinates’).values[2].num != NULL ? Jeff Douglas & Wes Nolte
311
resp.getValue(‘Placemark’).values[0].obj.getValue(‘Point’).obj.getV alue(‘coordinates’).values[2].num.format( ) : resp.getValue(‘Placemark’).values[0].obj.getValue(‘Point’).obj.getV alue(‘coordinates’).values[2].dnum.format( ); } catch (Exception e) { // #fail } return geo; } // inner class private class GeoResult { public Set keys; public Integer statusCode; public String name; public String coordinate1; public String coordinate2; public String coordinate3; public String address; public String toDisplayString( ) { return address + ‘ [‘ + coordinate1 + ‘, ‘ + coordinate2 + ‘, ‘ + coordinate3 + ‘] - Status: ‘ + statusCode; } } }
The Visualforce page is fairly simple and presents the user with a form to enter their address. If the geocoding services is experiencing issues, the user can check “Use hard-coded Google JSON response?” and the Controller with use the hard-coded JSON response instead of making the GET call to the geocoding service. Once submitted, the address is processed and the outputPanel is refreshed with the resulting address and coordinates. Listing 6 - 37. Visualforce Page used to Geocode Address Information 312
Salesforce Handbook
This example calls the Google Map geocoding REST service (JSON) with the address provide below. Sometimes the geocoding services stops responding due to service availability. If you are receiving errors with the returned JSON object, you can check the “Use hard-coded JSON response” to use a returned JSON response hard-coded into the controller from the Google address. Address City Jeff Douglas & Wes Nolte
313
State Use hard-coded Google JSON response?
id=“useGoogle”
Locking sObject Records Salesforce.com has the ability to lock sObject records while they are being updated to prevent threading problems and race conditions. To lock records, simply use the FOR UPDATE keywords in your SOQL statements. You do not have to manually commit the records so if your Apex script finishes successfully the changes are automatically committed to the database and the locks are released. If your Apex script fails, any database changes are rolled back and the locks are also released. Listing 6 - 38. Locking Records During Updates for (List ops : [select id from Opportunity where stagename = ‘Closed Lost’ for update]) { // process the records and issue DML } 314
Salesforce Handbook
The Apex runtime engine locks not only the parent sObject record but all child records as well. So if you lock an opportunity sObject all of its opportunity Line Items will be locked as well. Other users will be able to read these records but not make changes to them while the lock is in place. If your record is locked and another thread tries to commit changes, the platform will retry for roughly 5 -10 seconds before failing with a “Resource Unavailable” error. For end users, we believe if they try to save a locked record from the salesforce.com UI, they will receive an error message stating that the record has been changed and that they should reload the page. We can’t confirm but we’ve seen this in the past.
Automating Approval Processes with Triggers This question came up on LinkedIn asking how to automatically fire off an approval process when an opportunity reaches 30% probability. The trigger fires when an opportunity is updated and is submitted for approval if the opportunity’s probability has moved from less than 30% to greater than or equal to 30%. For the trigger to work you need to have an approval process with matching criteria. Mine is fairly simple and is where the opportunity owner is the current user (there is only one user in a DE Org). The trigger makes no attempt to trap for errors if an approval process doesn’t exist. Listing 6 - 39. Trigger to Fire Off Approval Process trigger OpportunitySubmitForApproval on Opportunity (after update) { for (Integer i = 0; i < Trigger.new.size( ); i++) { if (Trigger.old[i].Probability < 30 && Trigger.new[i].Probability >= 30) { // create the new approval request to submit Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest( ); req.setComments(‘Submitted approve.’);
for
approval.
Please
req.setObjectId(Trigger.new[i].Id); // submit the approval request for processing Approval.ProcessResult result = Approval.process(req); // display if the reqeust was successful System.debug(‘Submitted for approval successfully: ‘+result.isSuccess( )); } Jeff Douglas & Wes Nolte
315
} }
Here is the test class but you might want to enhance it to handle bulk operations and opportunities that are not submitted for approval because their probability is not greater than 30%. Listing 6 - 40. Test Class for Approval Trigger @isTest private class TestOpportunitySubmitForApproval { static testMethod void testApprovalSuccess( ) { Opportunity opp = new Opportunity( ); opp.Name = ‘Test Opp’; opp.Amount = 100; opp.CloseDate = Date.today( ); opp.Probability = 10; opp.StageName = ‘Prospecting’; // insert the new opp insert opp; // change the probability of the opp so the trigger // submits it for approval opp.Probability = 40; // update the opp which should submit it for approval update opp; // ensure that the opp was submitted for approval List processInstances = [select Id, Status from ProcessInstance where TargetObjectId = :opp.id]; System.assertEquals(processInstances.size( ),1); } }
Enhancing the Lead Conversion Process During the salesforce.com lead conversion process you can create an account, contact and opportunity for the lead that is being converted. The process is pretty straightforward and salesforce.com provides some tools for customizing it: 316
Salesforce Handbook
•
Salesforce.com allows you to automatically map standard and custom lead fields to account, contact, and opportunity fields.
•
Apex triggers are fired and universally required custom fields and validation rules are enforced only if validation and triggers for lead convert are enabled in your Org.
However, there may be some instances when a use case requires more complex processing. For instance: •
Whenever a new contact is created from a lead, a custom object is created that is associated to the contact.
•
Whenever a new account is created, a callout is made to an external web service.
•
Whenever a new opportunity is created, a number of standard products are added to the opportunity.
Listing 6 - 41 is a sample trigger that, for simplicity, does not operate for bulk inserts but gives you a good head start. Check the salesforce.com documentation on the conversion process. Listing 6 - 41. Trigger to Enhance the Conversion Process trigger LeadConvert on Lead (after update) { // no bulk processing; will only run from the UI if (Trigger.new.size( ) == 1) { if (Trigger.old[0].isConverted == false && Trigger.new[0].isConverted == true) { // if a new account was created if (Trigger.new[0].ConvertedAccountId != null) { // update the converted account with text from the lead Account a = [Select a.Id, a.Description From Account a Where a.Id = :Trigger.new[0].ConvertedAccountId]; a.Description = Trigger.new[0].Name; update a; } // if a new contact was created if (Trigger.new[0].ConvertedContactId != null) { // update the converted contact with text from the lead Contact c = [Select c.Id, c.Description, c.Name From Contact c Where c.Id = Jeff Douglas & Wes Nolte
317
:Trigger.new[0].ConvertedContactId]; c.Description = Trigger.new[0].Name; update c; // insert a custom object associated with the contact MyObject obj = new MyObject( ); obj.Name = c.Name; obj.contact__c = Trigger.new[0].ConvertedContactId; insert obj; } // if a new opportunity was created if (Trigger.new[0].ConvertedOpportunityId != null) { // update the converted opportunity with text from lead Opportunity opp = [Select o.Id, o.Description from Opportunity o Where o.Id = :Trigger.new[0].ConvertedOpportunityId]; opp.Description = Trigger.new[0].Name; update opp; // add an opportunity line item OpportunityLineItem oli = new OpportunityLineItem( ); oli.OpportunityId = opp.Id; oli.Quantity = 1; oli.TotalPrice = 100.00; oli.PricebookEntryId = [Select p.Id From PricebookEntry p Where CurrencyIsoCode = ‘USD’ And IsActive = true limit 1].Id; insert oli; } } } }
318
Salesforce Handbook
Using Email Templates with Apex There are often a number of new questions in the forums asking how to use email templates from Apex classes. The documentation on the topic is spread over many articles so we’ve collated those and other findings here. To start with note that there are a number of email template types: •
Text
•
HTML
•
Custom
•
Visualforce
Each has its own application and you can easily make them professional. Salesforce.com stores these as records in the EmailTempate object allowing you to query for them by name. As shown in Listing 6 - 42 you’ll then need to assign this template to the mail you’re sending. Listing 6 - 42. Assigning an Email Template to an Email Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage( ); 1];
Contact recipient = [SELECT id, firstname FROM Contact LIMIT EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName = ‘MyTemplate’]; mail.setSenderDisplayName(‘Your Loving Administrator’); // Specify who the email should be sent to. mail.setTargetObjectId(recipient.id); mail.setTemplateId(et.id); Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
Notice how there’s no need to specify the to-addresses, the subject, or the email body; they’re all pulled from the template. Some important considerations are: •
When querying for an email template always use the developerName field. If a power user decides to change the name of the template they’re less likely to change the unique name too, this way you have a (small) safety net. Of course you should always wrap this query in an exception handler.
•
Visualforce templates can’t be used in bulk emails.
Jeff Douglas & Wes Nolte
319
•
After you’ve created a template you need to make sure that you set it as Available to Use (an option on the template detail page), or emails using the template won’t be dispatched.
Writing an Inbound Email Service Creating an inbound email service for salesforce.com is a relatively straightforward process but there are a few tips that can make your life easier. The email service is an Apex class that implements the Messaging.InboundEmailHandler interface which allows you to process the email contents, headers and attachments. Using the information in the email you could for instance create a new contact if one does not exists with that email address, receive job applications and attached the person’s resume to their record, or have an integration process that emails data files for processing. You access email services from Setup -> Develop -> Email Services. This page contains the basic code you will always use to start your Apex class. Simply copy this code and create your new class with it. Click the New Email Service button to get started and fill out the form. There are a number of options so make sure you read carefully and check out the docs. One handy option is the Enable Error Routing, which will send the inbound email to an alternative email address when the processing fails. You can also specify email address(es) to accept mail from. This works great if you have some sort of internal process that emails results or files for import into salesforce.com. Just like Workflow, make sure that you mark it as Active or it will not work. After you save the new email service, you will need to scroll down to the bottom of the page and create a new email address for the service. An email service can have multiple email addresses and therefore process the same message differently for each address. When you create a new email service address you specify the “Context User” and “Accept Email From”. The email service uses the permissions of the Context User when processing the inbound message. So you could, for example, have the same email service that accepts email from US accounts and processes them with a US context user and another address that accepts email from EMEA accounts and processes them with an EMEA context user. After you submit the form the Force.com Platform will create a unique email address like the following:
[email protected] e.com
This is the address you send your email to for processing. Now that the email service is configured you can get down to writing the Apex code. Listing 6 - 43 is a simple class the creates a new contact and attaches any documents to the record. Listing 6 - 43. Inbound Email Handler Class global class ProcessJobApplicantEmail implements Messaging.InboundEmailHandler { global Messaging.InboundEmailResult handleInboundEmail( 320
Salesforce Handbook
Messaging.InboundEmail email, Messaging.InboundEnvelope envelope) { Messaging.InboundEmailResult result = new Messaging.InboundEmailresult( ); Contact contact = new Contact( ); contact.FirstName = email.fromname.substring( 0,email.fromname.indexOf(‘ ‘)); contact.LastName = email.fromname.substring( email.fromname.indexOf(‘ ‘)); contact.Email = envelope.fromAddress; insert contact; if (email.binaryAttachments != null && email.binaryAttachments.size( ) > 0) { for (integer i = 0; i < email.binaryAttachments.size( ); i++) { Attachment attachment = new Attachment( ); // attach to the newly created contact record attachment.ParentId = contact.Id; attachment.Name email.binaryAttachments[i].filename;
=
attachment.Body = email.binaryAttachments[i].body; insert attachment; } } return result; } }
One of the difficult things about email service is debugging them. You can either create a test class for this or simply send the email and check the debug logs. Any debug statements you add to your class will show in the debug logs. Go to Setup -> Administration Setup -> Monitoring -> Debug Logs and add the Context User for the email service to the debug logs. Send an email to the address and check the debug log for that user. One thing we wanted to see was the actual text and headers that are coming through in the service. Figure 6 - 12 shows virtually all fields and headers in a sample email. Jeff Douglas & Wes Nolte
321
Figure 6 - 12. 1 Email Detaill from an Inboun nd Service
The T code in Listing 6 - 44 willl give virtuallyy 100% code coverage for th he previous class. Listing L 6 - 44. Unit Test for Inbound Em mail Handlerr static s test tMethod voi id testMe( ) { // create a new em mail and en nvelope obj ject ng.InboundE Email email l = new Me essaging.In nboundEmail l( ) Messagin ; Messagin ng.InboundE Envelope en nv = new Me essaging.In nboundEnvel lope( ); // setup p the data for the em mail email.su ubject = ‘T Test Job Ap pplicant’; email.fr romname = ‘FirstName ‘ ; LastName’; env.from mAddress = ‘someaddre
[email protected] com’; // add a an attachme ent Messagin ng.InboundE Email.Binar ryAttachmen nt attachm ment = new Me essaging.In nboundEmail l.BinaryAtt tachment( ); 322
Salesforce Handbbook
attachment.body = blob.valueOf(‘my attachment text’); attachment.fileName = ‘textfile.txt’; attachment.mimeTypeSubType = ‘text/plain’; email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment
};
// call the email service class and test it with the ProcessJobApplicantEmail emailProcess = new ProcessJobApplicantEmail( ); emailProcess.handleInboundEmail(email, env); // query for the contact the email service created Contact contact = [select id, firstName, lastName, email from contact where firstName = ‘FirstName’ and lastName = ‘LastName’]; System.assertEquals(contact.firstName,’FirstName’); System.assertEquals(contact.lastName,’LastName’); System.assertEquals(contact.email,’
[email protected]’); // find the attachment Attachment a = [select name from attachment where parentId = :contact.id]; System.assertEquals(a.name,’textfile.txt’); }
Unit Tests & Code Coverage The most common question with regards to unit testing seems to be, “Why can’t I get code coverage for my entire class?” The trick here is to think like a runtime engine, and consider how you might journey through all possible testing paths. In this article we’ll touch on some of the more common test-situations. If-Else Statements This situation comes about when we have a piece of code something like that in Listing 6 - 45. Listing 6 - 45. Class with If-Else Branches Jeff Douglas & Wes Nolte
323
public class MyClass{ public Integer var{get;set;} public void aMethod( ){ if(var==1){ // Operations for this value } else if (var==2){ // Different operations for this value } else { // And more operations for all other values } } }
Assume that a field on a Visualforce page sets the variable var during normal operation. Your test methods have to mimic this behavior and set the value programmatically. Not only this, but your need to set the variable var to each of the values required to step through each branch of the if-else statement. Further to this, we would suggest a test method for each of the values that var can assume. This requires a lot of work but it makes for test code that is easier to understand and maintain. The test code for this class is shown in Listing 6 - 46. Listing 6 - 46. Test Class for If-Else Branches public static void testMethod testAMethod1( ){ MyClass mc = new MyClass( ); // Mimic that variable being set by the page mc.var = 1; mc.aMethod( ); // Assert that the operations in the first branch worked System.assert(...); } public static void testMethod testAMethod2( ){ MyClass mc = new MyClass( ); // Mimic that variable being set by the page mc.var = 2; mc.aMethod( ); // Assert that the operations in the second branch worked 324
Salesforce Handbook
System.assert(...); } public static void testMethod testAMethod3( ){ MyClass mc = new MyClass( ); // Mimic that variable being set by the page mc.var = 9; mc.aMethod( ); // Assert that the operations in the last branch worked System.assert(...); }
For-Loops A contrived for-loop example is detailed in Listing 6 - 47.s Listing 6 - 47. Class Using a For-Loop public class with sharing MyClass{ public List accounts{get;set;} public void aMethod( ){ // Debug should System.debug(‘accounts:’+accounts);
go
here:
for(Account a: accounts){ // Insert logic here } } public void anotherMethod( ){ for(Account a: [SELECT id FROM Account WHERE condition = true]){ // Insert logic here } } }
If you’re not getting code coverage in methods similar to aMethod( ) and anotherMethod( ) you probably have an empty or null list i.e. the list accounts is Jeff Douglas & Wes Nolte
325
empty, or the SELECT id FROM Account WHERE condition = true query is not returning any values. A few well-placed System.debug( ) messages will tell you where you’re going wrong. Exceptions The last – and trickiest – case we’ll cover is exception handlers. The reason they’re more complex is that you need to test expected input and situations as well as erroneous input or unexpected situations. Listing 6 - 48 shows the class to test. Listing 6 - 48. Apex Code That Throws Exceptions public class with sharing MyClass{ public String accountName{get;set;} public void aMethod( ){ try{ Account a = [SELECT id FROM Account WHERE name = :accountName]; } catch (System.queryException e){ // Deal with exception in logical and superfun way } } }
We would suggest writing a single test method to cover the try-part, and a separate test method to cover the catch-part as shown in Listing 6 - 49. Listing 6 - 49. Test Code for Exception Handlers public static void init( ){ // This is an aside. I recommend setting up your own test // data so that any unit tests are independent of the Org // that you have them in. Account a = new Account(name=‘A name that I know doesn\’t exist in my real dataset’); // The data inserted will only exist (and be available) for // the lifetime of the test method that executes it. insert a; }
326
Salesforce Handbook
/** Positive Test **/ public static void testMethod testAMethod1( ){ init( ); MyClass mc = new MyClass( ); real
mc.accountName = ‘A name that I know doesn\’t exist in my dataset’; mc.aMethod( ); List a = [SELECT id FROM Account WHERE name = ‘A name that I know doesn\’t exist in my real dataset’]; System.assert(a.size( )>0);
} /** Negative Test **/ public static void testMethod testAMethod1( ){ // No call to init( ) since we want an exception to be thrown MyClass mc = new MyClass( ); mc.accountName = ‘A name that I know doesn’t exist in my real dataset’; mc.aMethod( ); List a = [SELECT id FROM Account WHERE name = ‘A name that I know doesn\’t exist in my real dataset’]; System.assert(a.size( )==0); }
Testing exceptions can be further complicated where you need to catch more than one type of exception as in Listing 6 - 50. Listing 6 - 50. Try-Catch Block with Multiple Exception Handlers public void aMethod( ){ try{ Account a = [SELECT id FROM Account WHERE name = :accountName]; a.name = ‘A new name’; update a; Jeff Douglas & Wes Nolte
327
} catch (System.QueryException e){ // Deal with exception in logical and superfun way } catch (System.DmlException e){ // Deal with this exception differently } }
Here we’d suggest we have a test case for the try-part, as well as one for each of the catchstatements. Some other helpful tips when unit testing are: •
Always run your tests from the Force.com IDE
•
There are different schools of thought on this but we’d recommend only testing your public methods
•
Read through the Force.com IDE code coverage report. It will tell you which lines of code haven’t yet been tested
•
Split out your test methods into separate classes from those they are testing. This allows you to use the @isTest annotation so that test code isn’t counted against your Org. It also makes maintenance (especially in teams) much easier
These samples are relatively simple, but you’ll notice that even your most complex code is a mixed bag of these situations. One feature of good software development is being able to break a complex problem down into smaller parts and analyze those independently.
Programmatically Creating Sharing Rules Listing 6 - 51 is a small Apex Trigger that demonstrates how to programmatically create sharing rules for objects with a private sharing model. The example scenario is that the object has a private sharing model (contacts in this case) so that only the record owner and users higher in the role hierarchy have access to it. We’ve added a checkbox to the contact object called “Make Public” that when set to TRUE, creates a sharing record for a specific group (e.g., All Internal Users). When set to FALSE, it deletes all manual-sharing rules for the record. You can modify this to add multiple groups or even make it operate on the reverse (public by default and then remove the sharing rules). Listing 6 - 51. Trigger to Create Sharing Rules trigger ContactMakePublicTrigger on Contact (after insert, after update) { // get the id for the group for everyone in the org ID groupId = [select id from Group where Type = ‘Organization’].id; 328
Salesforce Handbook
// inserting new records if (Trigger.isInsert) { List List( );
sharesToCreate
=
new
for (Contact contact : Trigger.new) { if (contact.Make_Public__c == true) { // create the new share for group ContactShare cs = new ContactShare( ); cs.ContactAccessLevel = ‘Edit’; cs.ContactId = contact.Id; cs.UserOrGroupId = groupId; sharesToCreate.add(cs); } } // do the DML to create shares if (!sharesToCreate.isEmpty( )) insert sharesToCreate; // updating existing records} else if (Trigger.isUpdate) { List sharesToCreate = new List( ); List shareIdsToDelete = new List( ); for (Contact contact : Trigger.new) { // if the record was public but is now private – delete the existing share if (Trigger.oldMap.get(contact.id).Make_Public__c == true && contact.Make_Public__c == false) { shareIdsToDelete.add(contact.id); // if the record was private but now is public – create the new share for the group } else if (Trigger.oldMap.get(contact.id).Make_Public__c == Jeff Douglas & Wes Nolte
329
false && contact.Make_Public__c == true) { // create the new share with read/write access ContactShare cs = new ContactShare( ); cs.ContactAccessLevel = ‘Edit’; cs.ContactId = contact.Id; cs.UserOrGroupId = groupId; sharesToCreate.add(cs); } } // do the DML to delete shares if (!shareIdsToDelete.isEmpty( )) delete [select id from ContactShare where ContactId IN :shareIdsToDelete and RowCause = ‘Manual’]; // do the DML to create shares if (!sharesToCreate.isEmpty( )) insert sharesToCreate; } }
Listing 6 - 52. Test Code for the Previous Trigger @isTest private class TestContactMakePublicTrigger { // test that newly inserted records marked as pubic= true have corresponding shares created static testMethod void testAddShares( ) { Set ids = new Set( ); List contacts = new List( ); for (Integer i=0;i Customize -> Accounts. You can configure person account page layout like you would any other type of page layout. You’ll need to go and assign the new record type to each of the profiles that need access to it.
Jeff Douglas & Wes Nolte
335
Figuree 6 - 13. Person account Menu IItems
Once O you’ve ddone they youu will be able to create acco ounts for Bussiness and Perrsonal record d types. When you click the New N Account button b you’ll rreceive a pickliist asking you w which type to o create.
336
Salesforce Handbbook
Figu ure 6 - 14. Creatiing person acco ount records
So what h happens when n you create a new person n account? A person acco ount is a combination of both an accouunt and contaact record. Wh hen person acccounts are enaabled, the folllowing fields aare added to th he account objject: 1. FirstN Name 2. LastN Name 3. IsPessonAccount 4. Langguages_pc 5. Leveel_pc 6. Perso onAssistantNaame 7. Perso onAssistantPh hone 8. Perso onBirthdate 9. Perso onContactId 10. Perso onDepartmentt Jeff Douuglas & Wes Nollte
337
11. PersonEmail 12. PersonEmailBouncedDate 13. PersonEmailBouncedReason 14. PersonHomePhone 15. PersonLastCURequestDate 16. PersonLastCUUpdateDate 17. PersonLeadSource 18. PersonMailingCity 19. PersonMailingCountry 20. PersonMailingPostalCode 21. PersonMailingState 22. PersonMailingStreet 23. PersonMobilePhone 24. PersonOtherCity 25. PersonOtherCountry 26. PersonOtherPhone 27. PersonOtherPostalCode 28. PersonOtherState 29. PersonOtherStreet 30. PersonTitle 31. RecordTypeId 32. Salutation The following fields are not available for person accounts: 1. Parent Account 2. View Hierarchy 3. Reports To You can go to the person account page layout and add these fields to the page layout. However, you cannot add the contacts related list to the page layout. The Partner related list is available though so you can relate person accounts to one another.
338
Salesforce Handbook
Figure 6 - 15. A person accoun nt page
When you create new person account records, r salesfforce.com creaates not only an n account reccord but also a contact reccord in the baackground. Yo ou cannot access the accouunt record dirrectly (it alwayys relocates yo ou back to thee person acco ount record) but b it is needeed for the fun nctionality thaat requires a contact c (emailss, customer po ortal, etc.). Figgure 6 - 16 an nd 6 - 17 show what the reecords look likke from SOQL L.
Figure 6 - 16. The accou unt record for a person accountt
Jeff Douuglas & Wes Nollte
339
R for a persson account Figure 6 - 177. The contact Record
Some S other thiings to take intto consideratio on for person aaccounts includ de:
340
•
Person acccounts can bee associated with w activities uusing either th he Name or Related To fields.
•
Person acccounts can bee invited to gro oup events andd requested meeetings.
•
Person acccounts can bee added to Caampaigns and have a Campaaign History related list.
•
For casess, person acco ounts can be entered e in the account Nam me field, the co ontact Name fielld, or both.
•
You can add person acccounts to thee contact Rolees related list on o cases, conttracts, and oppo ortunities.
•
Custom o objects with relationships to o either accouunts or contaccts can be addded as related lists on person accounts. a
•
Person acccounts can bee enabled as users for your Customer and Self-service S porrtals.
•
Person aaccounts are currently c supp ported in Connect Offlinee and Connecct for Outlook version 3.2 an nd later. Theyy are not currrently supportted in Connecct for Lotus No otes.
•
You can ssend individuaal emails and mass m emails to p person accoun nts.
•
For field history, acco ount fields fo or person acco ounts can be tracked usin ng the account ffield history seettings, but con ntact fields for person accounts are confiigured on the contact field histtory settings paage.
•
Person aaccounts havee a unique im mport wizard so make suure you checkk the salesforcee.com Help forr more info.
•
Leads witth a blank Co ompany field are a converted to person acccounts. The ddefault person acccount record type t for your profile p is applieed to the new person accoun nt.
•
You cann not add a contaact formula fieeld that referen nces the accouunt object to p person accounts page layouts.
Salesforce Handbbook
•
Contact sharing is not available if you have enabled person accounts. The Org-wide defaults for contact is set to Controlled by Parent and is not editable.
•
If your company has customized your contact sharing settings and you want to enable person accounts, change your Org-wide default for contact to Controlled by Parent, which removes all your contact sharing rules and manually shared Contacts.
•
Person accounts count against both account and contact storage because the API considers each person account to consist of one account as well as one contact.
•
Creating or editing a person account triggers account workflow rules.
Jeff Douglas & Wes Nolte
341
Summary
W
e had a great time writing this book. We really enjoy working on the Force.com platform and hope this book makes this apparent. We wanted to expose you to a large number of features rather than dive too deeply into any one area. We hope we’ve armed you with a broad understanding of the possibilities of salesforce.com and the Force.com platform, and we look forward to seeing your innovative applications come to life.