Вы находитесь на странице: 1из 360

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


Salesforce Handbook

Salesforce Handbook
A newcomers 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 cant 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.............................................................................................................................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

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

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 Thats 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

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

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

Working with Person Accounts .................................................................................. 335 Summary ......................................................................................................................... 343



ouve just picked up a book on Salesforce and the Force.com platformwelcome to the ground floor in our industrys 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 deliverythe 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 infrastructurethe idea that developers could consume raw computing and storage capabilities as a service, without any physical infrastructure to deploy or maintain. Now were seeing a revolution in application platformsgiving 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. Heres 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 youve 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 elses 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 dont know that they dont 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 platformI 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

About the Authors A

Je Douglas is a highly sought-after and award eff y d-winning te echnologist wi more than 15 years of leadership e ith n f experience cr rafting techno ology solution for compa ns anies of all s sizes. His te echnology skill were honed during the fas and furious dot com ls st er ra, when he provided SAP developmen services for Fortune P nt r 50 companies including C 00 s Coca-Cola, An nheuser-Busch Disney h, Im magineering, M Moen, and Er ricsson. After years of being a lowly g Ja developer, in 2006 he ascended into cloud compu ava , o uting. He pe eriodically wri ites for develo oper.force.com and actively tries to m y work the word automagical into functional document w tation. He speaks at indus stry conferenc ces, developer meetups and enthusiastica blogs abo cloud d ally out computing (espe ecially Force.co at http://b om) blog.jeffdouglas.com m. Jeff works for Appirio a cloud so s o, olution provid that offer both prod der rs ducts and pro ofessional serv vices to help en nterprises acce elerate their ad doption of the cloud. With o over 2,500 customers, Appi has a prov track reco of implem irio ven ord menting missio on-critical solu utions and dev veloping inno ovative produc on cloud platforms suc as salesfor cts ch rce.com, Goog Apps, gle Workday and Am mazon Web Se ervices. From offices in the U and Japan Appirio serv a wide U.S. n, ves ran nge of comp panies including Thompso Reuters, Japan Post Network, Lt Brady on td, Co orporation, BM RehabCare Starbucks an Qualcomm Appirio was founded in 20 is the MC, e, nd m. 006, fas stest growing partner of salesforce.com a Google, an is backed by Sequoia Ca and nd b apital and GG Capital. GV Jeff resides in Sarasota, FL, with his w Cathy and four children Scott, Tyler, Brittany, s F wife d n , and Kira (adopte He and hi wife have be medical fo ed). is een oster parents for over 12 yea caring f ars, for more than 75 children. r 5 Wes Nolte has a long histo of love for all things tec W ory r chnologybased, with experience spanning the entire Inf b e formation Technology spe T ectrum across two continent A relative n ts. newcomer to the cloud-c o computing sce he has no ene onetheless wo several on in nternational a accolades inc cluding the auspicious F Force.com Developer Her award; he a holds the much covete title of D ro also e ed Force.com Dev F veloper Challen Winner. nge A prevalent member in a num r mber of dev velopment communities, his highly acclaimed input on cloud computing c t matters is often sought across the US, Euro Asia and A m n ope, Africa. Wes is seen as a champio of salesforce n on e.com and the Force.com Pl latform, and hi blog on is the subject is re e egarded as on of the mos influential in the world. From this soapbox he ne st n ins spires the com mmunity by im mplementing a combining groundbreak and g king technolog in all gies

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 theyre accessible in the mainstream allowing him to dabble to his hearts 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.

Salesforce Handbook


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 couldnt do it alone and would like to thank some of the key people that made this book possible. First and foremost, wed 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. Shes a keeper. And thanks to Wes fiance 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, wed 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. Its 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. Wed 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 were 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 wed 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 wouldnt 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


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; lets 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, Lets 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, its 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.

Sales sforce.com i the Final Word is

Throughout th book well provide featu T he ures explanatio ons, code sam mples, tips from the m trench and links to resources for more in hes s nformation. O One of the great things about g salesfo orce.com is tha they release new features a updates th times per year. The bad thing at and hree about salesforce.com is that they release new f m features and up pdates three times per year. This t . makes it hard to be right 100% of the time reg o garding how th platform c he currently wor If rks. you fin a contradic nd ction in this bo its probably due to a recent release or update. The best ook o e source of informatio is http://developer.force.com a salesforce.com Help and documentatio so e on and d on, always check there fo the final wo s for ord.

Next Steps t
After you are f A finished readin this book c ng cover to cover what are you next steps? Since r, ur we on provide a c nly cursory overview of most to opics we invite you to drill into aspects o the of platfor rm that int terest you. The first website that you shou t uld bookmar rk is http:// /developer.force.co This site contains the latest inform om. mation regardi ing the Force e.com platfor There are many hidden gems at develo rm. oper.force.com so make sur you really ex m re xplore the site e. For advanced developers that need a deep-dive into the platform, A t Apex, Vis sualforce and strategies for working with governors an limits, pick up a h nd k cop of Developm with the For py ment rce.com Platform: Building Busin Applications in the : ness s Clo by Jason Ouellette. The book covers a surprisingl large numb of oud O e s ly ber dev velopment topics and is a great refe erence for bo oth salesforce e.com adm ministrators an developers Its a logic extension to this book as it nd s. cal exp pands on topic that we cove at a high lev cs er vel.

Conv ventions Used in this Book B

Termi inology Conv ventions Org An instance in which the sale A esforce.com an Force.com applications ar developed, t nd re tested and us sed. Salesf force.com Not only the a N actual compan salesforce.c ny, com, but also collectively th software an its he nd user in nterface. Typog graphic Conv ventions Italic URLs, email ad U ddress


Salesforce Handb book

Co onstant Wid dth

Used for program listings, as well as w within paragrap to refer to program elem phs metns such as variable or me ethod names, data types, key d ywords and stat tements.
Co onstant Wid dth Bold

Shows com mmands or oth directives su as clicking a button. her uch g Ico onic Convent tions An icon to indicate a Tip from t trenches or some othe type of n the er importa note or side ant ebar. An icon to indicate a Common Pitfall or issue that we ha come n ave across in the past. n An icon to indicate an important lin to a websit with a demo or more n n nk te o informa ation. There is so much grea salesforce.co content on the web that we didnt s at om n want to leave it out. T Therefore wev set up a del ve licious.com ac ccount for quick ac ccess to all of t links that w the weve either re eferenced or ha found ave useful with more in w nformation. W Weve categor rized these li inks with deliciou tags that you can find in th footnotes of each section. us u he f You can ac ccess the delicious bookmark at: http://ww ks ww.delicious.com/ /salesforcehandbo ook

Jeff Do ouglas & Wes No olte


In ntroducti to Sal ion lesforce.c com

Sa alesforce.co Overview om w
Salesfo orce.com is so oftware as a s service (SaaS), meaning that there is t simply no software to install or ser rvers to mainta You simpl sign up ain. ly for an account and sa alesforce.com spins up an in nstance of their software r that yo can use to r your busin right away Salesforce.co offers ou run ness y. om a 30-da trial and sin there is no contract, you can cancel at any time ay nce o u t and wa away if its not a fit fo your busin alk or ness. Again th here is no software to inst tall; everything is accessible from your b g e browser so its easy for use to get s ers sta arted. Even th hough salesforc ce.com is a pr re-configured system you ar not locked into their re pro ocesses. You can tweak sale esforce.com p your comp per panys specifica ations, develop custom fun nctionality and even install fr and low co applications from the App d ree ost s pExchange. Founded in 1999 by Ma Benioff (O n arc Oracle), Parker Harris (Left Coast Softwa r are), Dave Mo oellenhoff, an Frank Dom nd minguez (both from Clarif salesforce.com started out as a h fy), Cu ustomer Relatio onship Manag gement (CRM) product but o over the years has evolved in much, nto mu more. Fro a high lev salesforce.c uch om vel, com consists o several pro of oducts: Sales, S Service & Su upport, Partner Relationship Management, Marketing, C r Content, Ideas, Analytics, and Chatter. d De evelopers can extend the sy ystem by writi application on the For ing ns rce.com platfo orm using sal lesforce.coms proprietary lan nguages Apex and Visualfor rce. Salesforce.c com provides these services in the clou ud. By now, youve probably heard about cloud com mputing. Its go from a for one rward-looking concept, initia adopted b smaller, g ally by nim compani to a serious requirement for a growing number of la mble ies s g arger businesse Before es. we dive into sale e esforce.com le take a step back and talk about Cloud Computing, a concept ets p k d tha salesforce.co is champio at om oning.

Sa alesforce.co IS Cloud Computin om d ng

A number of vendors are making cla a aims to offer cloud solut tions. Howeve simply er, mo oving your ser rver to anothe companys data center do not make it a cloud solution. In er oes mo developme communities and the ent ost ent terprise compu uting space in general, salesfo g force.com, Go oogle and Am mazon.com are leading th march tow a he wards enterpri adoption of cloud ise computing servic 1. The three commonly ac ces e ccepted levels of cloud comp puting offering include gs Infrastructure as a Service (Iaa Platform a a Service (Pa s aS), as aaS), and Softw as a Servi (Saas). ware ice Ea has its own unique, but sometimes ov ach n verlapping plac in the cloud computing sp ce d pace with the own uniqu features an benefits. H eir ue nd However they do share som common attributes me inh herent to the space itself.

cl loud-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 clients 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 doesnt 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, its 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 its 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 doesnt 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 vendor la C andscape (Source: Appirio CIO blog)

Take a look at where the major players sit in relation to the types of cloud offerin weve k s n o ngs dis scussed so far as well as in comparison t each other. You can quic see that t major r to ckly the off ferings seem to build on eac other. Amaz Web Servi o ch zon ices, in the bot ttom-left sectio offers on, the least custom e mization. It sim mply removes your need to build out a physical infra o astructure, lea aving all the m management and support to y your IT staff. S Shifting to the right, you see that App En ngine offers just slightly mor abstraction, now covering the platform and infrastruct re a ture while sal lesforce.com a abstracts the ap pplication, plat tform and infra astructure layers. Its import tant to note that the place t ement of the offerings on this diagram does not ind dicate preferen or correla with value in any way. E nce ate Each of these offerings has its own e un nique value and place in the market and w d weve used a co ombination of them to build the best f d sol lution for our customers. Ea offering do provide companies with the following b ach oes benefits. Sa Money an Time ave nd Consider a basic Java ap pplication runn ning on WebS Sphere and assume that it m meets the req quirements fo an applicat or tion that coul be run in the cloud. With Amazon Elastic ld W ns Co omputing Clou (EC2) you can quickly b ud build the Linux stack with a preconfigured Apache x d ser rver and your choice of Ja application server and database. You have to sup r ava n u pport the op perating system the datab m, base, the app plication serve the securi er, ity, and all t the same components you be support ud ting in an on-p premise enviro onment, excep the physical machine. pt Th no doubt, s his, saves time and money. But, IaaS offerings still need prov d visioning and l long-term sup pport at mor layers than the applicat re n tion. Now, on the flip sid consider t n de, this same application runn on Force.c ning com. You don need hardw provisione or software installed, nt ware ed e need an applic cation server o a database. All these are wrapped into the core or o and you dont n atform offering from salesforce.com. g pla

Jeff Do ouglas & Wes No olte


Innov vate Quicker Take a look at Figure 1-2, which shows tw diagrams c T t w wo comparing the scope of act e tivities and th budget and effort of a tra he aditional IT de epartment with those of ano h other IT depart tment that is leveraging a P PaaS offering for its business applications. T fo Take special notice of the am mount of ma aintenance on the hardware middleware, and applicat e, , tion layers for the tradition IT r nal depart tment. Its app parent that all that lost time is intruding on the time, budget, and effo left t n ort over fo innovation. Now, in comp or parison, consid the IT dep der partment levera aging PaaS offe ferings for the hardware a middlewar layers. Rem eir and re moving the mai intenance requ uired to keep those layers in house, the department is free to spend that extra tim innovating on its core business me o applica ations. You mi ight notice tha vendor management is a n time-allotm category when at new ment youre using PaaS so olutions. How wever, thats a small effort in comparison to managing these n n solutio internally. ons If youre curr I rently entrenched in a trad ditional softw ware-development structure or a traditio IT depart onal tment, one of these previous illustrations probably look very familiar The ks r. ineffic ciency of tradi itional IT is one of the main reasons so many comp o o panies are ado opting Force.com for their development platform. p

Figure 1 - 2. Tradional IT versus IT lever T raging PaaS (So ource: Appirio CIO blog) C

What is Salesfor t rce.com?

From its humb start as a sales force aut F ble s tomation (SFA tool, salesfo A) orce.com has g grown into a platform for developing and running mission critic enterprise applications. Most r cal, compa anies get starte on salesforc ed ce.com as a wa to track the customers and prospects more ay eir a efficien Salesforce CRM is a se of business processes and integrated ap ntly. et d pplications that help t compa anies manage customer inf formation, act tivities, and c conversations in one centr ralized locatio By combin on. ning business processes, peo p ople, and techn nology, compa anies can drive sales e and ke customers satisfied after the sale. eep For sales mana F agers, CRM allows them to forecast sale more accurately with real a o es l-time visibili into their teams activiti For sales reps, CRM s ity ies. streamlines customer interac ctions
16 Salesforce Handb book

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 whats 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 glanceincluding 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 Theres 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.

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 wont 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 todays 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.


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 customers 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 customers 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 its 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.

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.coms 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 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. 2. 3. 4. 5. Delivers faster time to value Requires no up-front capital expenses Minimizes operational costs Requires fewer technical resources 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 only can y develop internal applicat N you tions for your c company but you can also d y design, build and host pu ublic-facing websites on th Force.com platform us w he m sing standard Web techno ologies such as HTML, Flash Flex and Jav s h, vaScript. Custo Applicatio Developme om on ent The majority o salesforce.co customizati T of om ions are done with the decla arative, point-n n-click interfa However, in certain case you may nee to create en ace. es ed ntirely new pro ocesses or inte erfaces that ar beyond the scope of the current declar re rative capabiliti In these cases, salesforce ies. e.com offers proprietary lan nguages, Apex and Visualforc which allow you to write custom code o the ce, w on Force.com platform1. Apex is a strongly-typed, object-oriente programmi language t s , ed ing that is compil led and exec cuted on the Force.com m multitenant in nfrastructure. If you have some I develo opment experie ence, Apex sho be fairly easy to pick up. The language looks and fee like ould . e els Java and has similar variable and expression sy a r d yntax, block a conditiona statement sy and al yntax, loopin constructs, o ng object and array notation, pas by reference and other feat y ss e tures that you might expect in high level language. Whe Apex shine is its built-in support for database opera t ere es n d ations. Apex supports DML statements fo inserting, up s L or pdating, upsert and deleti of records along ting ing with a powerful inlin query (SOQL and search ( ne L) (SOSL) syntax for locating re ecords. To build applic T cations or custo omize the sales sforce.com UI, developers us Visualforce, a tag, se based markup langua similar to HTML, in conju m age H unctions with A Apex code. Visu ualforce tags pr rovide develo opers with the ability to bui AJAX-y ap ild pplications wit surprisingly few lines of code. th Visualf force pages ca consist of standard or custom compone an s ents interspers with snippets of sed HTML CSS or JavaS L, Script. Well be diving into Ap and Visualfo in-depth later on in the b pex force book.

F Figure 1 - 3. Cus stom developme on the Force ent e.com platform.


apex-intro Salesforce Handb book


VM Mforce Salesforce.c com recently accounted a pa a artnership with VMware to develop a new product h w cal lled VMforce that allows Ja developers to write nati apps in the cloud that s ava s ive seamlessly 1 ho into the Force.com platf ook form . Java de evelopers can use the Spring Eclipse-based IDE to g wr standard P rite POJOs, JSPs and Servlets t a that deploy ef ffortlessly to VMforce serve in the V ers sal lesforce.com d datacenters. Th native hooks into the Fo he orce.com platf form (e.g., JPA REST) A, allo developers to write app ow plications that may normall exist outsid the platform due to t ly de m go overnor limits or other cons straints. Comp panies can lev verage existing development skills to g t mo legacy Jav apps to th cloud, dev ove va he velop new Jav apps that run in a mu va ulti-tenant en nvironment or reuse existing Java libraries t are not ava J that ailable on the Force.com pla F atform.

Se ecurity
Security is baked into all aspects of Force.com in a ncluding user, session, netw , work and pla atform restric ctions2. The platform featu p ures a robust and flexible security arc t e chitecture, pro oviding granul control ove users, netwo access, and data not onl from a prog lar er ork d ly grammatic asp but from system config pect guration as wel These securi protocols are intended to not only ll. ity a o pro otect data and logic from unauthorized ex d xternal access, but also from unauthorized internal , m d acc cess as well. W When you acc cess the appli ication using a salesforce.co om-supported browser, Secure Socket Layer (SSL) technology protects you informatio using bot server ur on th authentication an data encryp nd ption, ensuring that your dat is safe, secur and availab only to g ta re, ble reg gistered users i your compa in any. We highly encourage you to visit the http://trust.sale lesforce.com/secur site for the latest in rity e sec curity educatio This is where salesfor on. w rce.com customers can lear about secu rn urity best pra actices, learn h to spot su how uspicious email and attend se ls ecurity webina ars. Us Security a Authentic ser and cation When a new salesforce.co instance is provisioned, a unique Org ID is genera w om s g ated. You wil need this Or ID anytime that you cont salesforce. ll rg tact .com for suppo billing or activation ort, of features. This Org ID is us for both se s sed ecurity and data access. To find your Org ID, click f g
Se etup -> A Administrat tive In nformation. . Setup p -> Com mpany Prof file -> C Company

Figure 1 - 4. The Org ID displayed in the Builder e g

1 2

vm mforce se ecurity Jeff Do ouglas & Wes No olte 23

Your product tion Org ID w always rem the same but a new Or ID will main rg will be genera ated each time your refresh a sandbox. This may affec any e h T ct third-party too that are lice ols ensed by Org I ID. Salesforce.com requires that users login in the platfo S nto orm with a un nique username and passwo This deter ord. rmines the inst tance and Org ID for the use and ties thes identifiers to their er se o session Each request to the platform utilizes this s n. t m session and the associated Org ID to segmen and e g nt compa artmentalize dat protecting yo companys data from user outside your Org. ta our rs Salesforce.com usernames must be un m nique across all production and a n sandbox envi ironments. Fo instance, tw production Orgs cannot have or wo t the same use ername myusern name@mydomai in.com, but it can exist in b c both a production an a sandbox O nd Org. Companies tha utilize single sign-on to sim C at e mplify and stan ndardize their user authentic cation 1 can im mplement either delegated or federated auth hentication wit salesforce.co . th om Using delegated authenticatio Force.com does not val U on, m lidate passwor but instead uses rds d an exte ernal Web serv to validate user credenti When a us attempts to login, the pla vice e ials. ser o atform checks the users pro to see if th are enabled for SSO. If s it makes a Web services c to s ofile hey so, W call the en ndpoint specified for the Org asking it to validate the username and password. The Web g, p e service checks the cr e redentials again an identity store (e.g., LD nst y DAP, OpenID and either re D) eturns true or false. If true, the user is granted acce to the appl ess lication and pr roceeds norma If ally. false, the user is info t ormed that thei credentials a invalid. ir are Federated auth F hentication, th preferred an default of the two meth he nd hods, uses Se ecurity Assert tion Markup L Language (SAM to send a ML) authentication and authoriz n zation data bet tween affiliat and unrela ted ated Web serv vices. Federate authenticat ed tion does not validate the users actual password on t Force.com platform. Instead, the platfo receives a SAML asserti in the m form ion an HT POST req TTP quest. The SA AML assertion has a limited v validity period contains a u d, unique identif and is digi fier, itally signed. If the assertion is still within its validity period, has an iden f ntifier that ha not been u as used before, an has a valid signature from a trusted id nd m dentity provide the er, user is granted acces to the applic s ss cation. If the a assertion fails v validation for any reason, the user a e is informed that thei credentials are invalid. ir With the Wint 11 release salesforce.com now suppo OAuth2 for authorizing web W ter m orts f g applica ations. This no only allows you to extend the reach of your external applications b to ot d f but do so in a more sec cure manner as you are no lo s onger required to store user credentials in your d r n client applications. A number of authentication flows for OA a n Auth 2.0 are su upported, incl luding the we server flow, user-agent flo and SAML assertion flow eb ow w. Sessio Security on When logging in, salesforce.com issue a session cookie to record encr W g es n rypted authen ntication inform mation for the duration of a the session. Session security is used to limit . o

sso Salesforce Handb book


exp posure to you network wh a user leav their comp ur hen ves puter unattended while still l logged in. Th session time he eout is config gurable for all users within t Org. When a users sess the n sion times ou (by default i two hours they are pr ut its s), rompted with a popup that asks them to continue wo orking or log o If they do not respond to the dialog at all, they are au out. o t utomatically lo ogged out. Yo can edit the setting by clicking Setup -> Administ ou ese p tration Setup -> Security Co ontrols -> Session Settings. Ne etwork-based Security d To help p prevent hacke and other unauthorized users from accessing your data, ers r d m sal lesforce.com p provides the ab bility to define the hours tha users can log plus the ra at gin ange of IP addresses that lo ogins can origi inate from. If a user attempt to login from an IP not d ts defined in the network list, they will send a challenge e e d email asking th to confirm their attempt to login. hem m t Yo can also wh ou hitelist IP addr resses from w which users can always login without a cha n allenge by clicking Setup -> Adminis stration Se etup -> Se ecurity Con ntrols -> N Network
Ac ccess.

Se ecurity Token ns Force.com has an additio layer of acc for extern and client applications. I you are on cess nal If run nning a deve elopment tool (e.g., Data Loader, Forc l ce.com IDE) or developin a web ng application that uses the Web services API, you will need to append a special security token to s y the end of your p e password if th IP address is outside of the trusted IP ra he s e ange. To receiv or reset ve your security token click Setup -> Personal Setup -> My Pe > l ersonal In nformation -> Reset Security T Token. This w create a new token and send an will n d em to the ema address cont mail ail tained in the u users account. E Each time you reset your pa assword a new security toke will be auto w en omatically em mailed to you. Be careful w . when resetting an administra password as it may ator af ffect running applications a lock users out. For ext and s ternal applicat tions you m want to create a new API-only u may c user and set its password to never i ex xpire. Da Security ata access to data is one of t most cha a the allenging and complex pro ocesses in Securing a sal lesforce.com1. Locking down access is don by a combin n ne nation of profil and role and involves le d configuring obje level secu ect urity, field lev security an record level security. If you are vel nd f im mplementing se ecurity and sha aring rules for your Org yo will want to research this topic in r ou o s depth and test y your design in a sandbox to i insure that use dont have access to una ers authorized fie and record elds ds. Security is configured by both user p y profile and rol Profiles are typically defi le. e fined by a use job function and are a collection of settings and pe ers c ermissions that determine wh a user t hat can do in the ap n pplication. Cur rrently, a user can only be a assigned to on profile. A u ne users role

se ecurity-data Jeff Do ouglas & Wes No olte 25

defines which actual records they have access to Object level security is used to control C l h o. CRUD access to objects by profile. For ea profile you can determin whether or not a user can view, ach u ne n create, edit, or delete any instance of a particular type of object , e t.

Figure 1 - 5. Configuring C 5 CRUD access fo a profile. or

Once you have locked down access to obje by profile, you can limit access to indiv O e ects , vidual fields with field-leve security. Fiel w el ld-level securit determines whether a use based upon their ty er, n profile can see, edit and delete th value for a p e, t, he particular field on an object. This allows y to d . you protec sensitive fie ct elds (e.g., payr informatio social secu roll on, urity numbers) without havi to ing hide th entire object from specif profiles. Th he fic hese restriction are also en ns nforced throug the gh variou salesforce.co APIs. us om

Fi igure 1 - 6. Conf figuring account field level secu t urity for a profile e.

Record-level se R ecurity grants users access to the individ dual records in your Org a is i and config gured with a co ombination of Org-wide defa aults, the role h hierarchy and sharing rules. s Configuring re C ecord-level sec curity begins b setting up the Org-wide defaults for each by e r object. These setting specify the default level of access to reco in the Org For most ob gs d f ords g. bjects, Org-w sharing se wide ettings can be set to Private, Public Read O s Only, or Public Read/Write. With c these setting in place you basically lock down a s y access to the m restrictive level and the use most e en the rol hierarchy an sharing rules to open up a le nd access to users. .


Salesforce Handb book

Figure 1 - 7. Org-wide default setting fo sharing model or l.

You can sh hare access to records by a users position in the role hierarchy. You define a n h u rol by its positio in the role hierarchy, which is similar to an org chart. A user has access to all le on h o rec cords owned b roles beneat them in the role hierarchy This ensures, for example, that sales by th y. ma anagers have a access to the sa data as th sales reps. You can also use a territory hierarchy ame heir u to share records based upon cr riteria such as z code, indu zip ustry or a custo field. om You can al manually and programm lso matically share records with sharing rules Sharing e h s. rul let you make automatic exceptions to Org-wide defa les e aults for partic cular sets of (s somewhat sta users to gi them acces to records th do not own or cannot no atic) ive ss hey n ormally see. Pr rofiles determine what a use can see an do with different types o objects er nd of w while roles determine which r records a user h access to has o.

In nfrastructure e
Infrastructu is one of th ure hose things tha you sometim take for gr at mes ranted in a Saa or PaaS aS env vironment1. D Development in the cloud inh n herently remove the necessity to be concern about es y ned inf frastructure an allows us to focus m nd more resources on business processes. However, s s inf frastructure is one of the se ecret ingredien of salesfor nts rce.com. Over 77,000 comp panies and commercial vend trust the platform to deli robust, reli dors p iver iable, Internet-scale applicatio ons. Salesforce.c com has five main data cente and is curre m ers ently building out two new ones in the o US Equinix ow these facili S. wns ities and salesf force.com co-l locates their se ervers there. T ensure To ava ailability and re edundancy, sale esforce.com us multiple ne ses etwork vendors at these locati s ions. Location San Jose, CA A Reston, VA Singapore Japan San Francisco, CA

Function Main Production D Center n Data Prod duction & Back k-up Data Cen nter Prod duction Data C Center Prod duction Data C Center R&D Lab and Tap Archive D pe

in nfrastructure Jeff Do ouglas & Wes No olte 27

Sale esforce.com re ecently announ nced plans to b build a new dat center in Lo ta ondon by 2 2012. Each user tha logs into salesforce.com is mapped to what is called an Or E at s m c rg, a compl instance of the salesf lete force.com sof ftware stack. S Salesforce.com has roughly 3000 m Dell servers (50% are idle, staged for d % disaster recovery) configu ured in a pod infrast tructure. Thes pods are clu se ustered pools of RedHat Li inux boxes ru unning open source Resin app servers, O Oracle RAC database instan d nces, Java app servers, Luce full-text s p ene search servers, load balanc cing servers and a SAN d a disk array. Requests to the app server are ese rs statele providing for a high degree of scalability an allowing for long run ess g h nd nning transactions to utili multiple boxes. The salesforce.com n ize network archi itecture is designed for ma assive failover Virtually eve transaction from the pr r. ery n rimary data cen nters are repli icated in real l-time to the R Reston, VA ba ack-up data ce enter. To ensure th users hav a secure browser con T hat ve nnection to the salesforce e.com enviro onment, all con nnections are via SSL 3.0/T 1.0, using global step-u certificates from TLS g up Verisig In respons to phishing attacks, salesf gn. se g force.com has significantly stepped up se s ecurity and us education. For an extra layer of securit all data is tr ser ty, ransmitted across encrypted links, they have implemen h nted an extra token-based e t external access protocol and you can configure d networ access by IP and time fram rk P me. When you sign up for an ac W n ccount, your O is provisio Org oned on an in nstance based upon your lo ocation: Re egion No America orth Jap pan AP PAC EM MEA SSL L Pods na1, na2 na3, na4, na5 na6, na7 2, 5, ap0 ap1 eu0 na0

You can determ Y mine what ins stance your Or is running on by looking at the URL i the rg g in addres bar. ss

Fig gure 1 - 8. The in nstance for the O based upon the browser UR Org RL.

Sandbox Orgs run on their own instances as well (cs0-cs5 and tapp0 for older Orgs and S o f s) are on different main n ntenance and upgrade schedu u ules. Knowing which instance you Org runs on is very impo K ur n ortant as salesf force.com sche edules mainte enance, updates and upgrades per instan nce. Addition nally, when th here are outag or ges
28 Salesforce Handb book

dis sruption they typically do not affect all i n instances. You can visit http u p://trust.salesfor rce.com for rea al-time and his storical inform mation on syste performance, planned maintenance and security em m thr reats and best practices.

Fi igure 1 - 9. Trust.salesforce.com displaying serv performanc history. m vice ce

Sc cheduled relea ases Salesforce.c com schedule three majo seasonal re es or eleases per ye ear: Spring (F February), Su ummer (June) a Winter (O and October). These releases typically contain changes to a w range c wide of salesforce.com products and services including the user interfac desktop in a ce, ntegration pro oducts, develo opment IDE, tools and AP These rel PIs. leases are roll out to users at no led additional charg and are ava ge ailable to ever ryone on the platform. Som features th greatly me hat im mpact the user experience are required to b enabled by t Orgs adm e be the ministrator. For example, r the is a new fe ere eature in Winte 11 that allo a user to c er ows click on a record in table or chart in a rep and be ta port aken to the re ecord detail pa instead of another summ age mary level. Th feature his mu be enabled by the Org ad ust dministrator. Salesforce.c com works very hard to ensure compatibi of existing code and fun ility g nctionality and weve seen v few instances where up very pgrades break existing functi ionality. Salesf force.com act tively strives to implement new functiona n ality that users request. User submit new ideas for rs fun nctionality at the IdeaExc change allowin other users to vote th idea up o down. ng he or Sal lesforce.com t takes these po opular ideas in account wi each releas and decides whether nto ith se s the are rolled in the next release. Each rel ey nto lease typically contains a num mber of ideas s submitted by the salesforce y e.com commun nity. A couple o months befo the upcom release, sa of ore ming alesforce.com makes availabl a list of m le use submitted id that are under consider er deas u ration by Prod Managers for the next re duct elease. As the release date gets closer, sa e alesforce.com s starts commun nicating some of the new fe eatures on var rious blogs a and webinars They also make pre-re s. elease trial Orgs available so that O administrators an developer can test out t impact of the new funct nd the tionality. As th release he
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.coms 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.coms 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 platforms engine can use to generate the virtual application components at runtime. When someone wants to modify or customize an aspect of the application, all thats required is a simple non-blocking update to the corresponding metadata. Because metadata is a key ingredient of Force.com applications, the platforms 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 platforms engine then materializes virtual table data at runtime by considering corresponding metadata1. To optimize access to data in the systems large tables, Force.coms engine relies on a set of specialized pivot tables that maintain denormalized data for various purposes such as indexing, uniqueness, relationships, etc. Force.coms 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 services 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

database 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: 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 objects 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 Are (Rich) - Fo representing rich text (HT ea or g TML) up to 32, ,000 characters with s formatted text, images and links with an embedded WYSIWYG editor. d a e URL - A Allows the user to enter a we r ebsite address that open the URL in a sep e parate browser w window when clicked on.

Relati ionship Fields The Force.com database sim T m mplifies that w that developers work with related rec way w cords. Relatio onal databases enforce data integrity wit primary and foreign key relationships. The s a th y Force.com data abs stracts and sim mplifies these requirements by creating simply relation s nships betwee objects. A relationship field stores th ID of the parent recor in a pre-de en he e rd efined relationship, providi a user interface represen ing ntations in both the parent and child recor as h a rds well as structured wa to query the chain of relat objects. s ay e ted For each relations you can sp r ship pecify up to 5 levels in your queries. This a allows you to build som powerful an useful queri that let you reach up or down u me nd ies u the relationship ch to fetch d hain data. Looku Relationsh up hip This relationsh creates a simple (foreig key) relationship that li T hip gn inks one obje to ect anothe These can be used to create one-t er. n to-one and one-to-many re elationships. W When display records in the salesforc ying n ce.com UI, the platform gen e nerates a link to the related r o record allowin you to navig from reco to related r ng gate ord record. Maste er-Detail Rela ationship A master-detail relationship creates a speci type of relat l c ial tionship betwe two object the een ts, parent or master object and its child, or det t, tail object. De objects ca etail annot live with hout a master object and o r once created, th relationship cannot be c his change. Detail objects also in nherit the sec curity from th master obje and deletes cascade from the master to the detail ob he ect s m o bjects. An ex xample of a m master-detail re elationship wo ould be a Sale Order (mas object) an the es ster nd individ Sales Ord Line Items (detail objects associated w it. The line items cannot exist dual der s) with e t withou the order he ut eader and are deleted when th order heade is deleted. d he er A few caveats exist with this type of relati s ionship. An ob bject cannot be the master in one n relationship and a detail in anothe An object c be the ma er. can aster in multipl relationship but le ps, these relationships cannot be used to implement multiple level of detail. r t ls This may seem backwards, but you create a master-detail relationsh by e hip add ding a field to the child obje instead of t parent. Ho ect the owever, you cannot crea a master-de relationsh for an obje that curren contains da A ate etail hip ect ntly ata. wor rkaround is to create a looku relationship to the maste add a value to all up p er, chil records for the relationshi and then c ld ip, convert the loo okup relationsh to hip am master-detail rel lationship.


Salesforce Handb book

The maste object in a master-detail relationship c also conta a special f er can ain field type cal lled a rollup s summary field. These fields store values a aggregated fro the child r om records in the relationship. For example, in our Sales Order exampl you could create an Ord Total e . , le der rol llup summary field that aut y tomatically sum the amoun of all line items. Rollup summary ms nt i fie can either count records or sum, min and max specific fields bas upon all records or elds n sed rec cords meeting certain crit g teria (e.g., ma atching record type, create date before today, d ed Bo oolean value). Many-to-Many Relationship y p There are development scenarios where you will n need to imple ement a many y-to-many rel lationship whe a record on one side of a relationship can be associa ere n ated with man records ny on the other side In this case salesforce.com uses an intermediate object which they r n e. m t, refer to as a junction objec (aka mappin table or piv table). To implement a junction objec simply j ct ng vot ct, cre a custom object and ad two master eate dd r-detail relation nships to the objects on eac side of o ch the relationship. e An issue with junction objects invo n olves usability When you add the y. junction ob bject as a related list on a pa layout, the user may have to make age e an extra series of clicks to create ne records or navigate bac to the s ew r ck original rec cord. This can be somewhat confusing from a UI perspective. m Sy ystem Fields Its no surp prise that the Force.com da atabase contai a number read-only syst ins tem fields automatically as ssociated with each object For each r h t. record in the database, F e Force.com automatically ass signs an identit field (called ID) and mana the identit data. The ID is a case ty ages ty D sen nsitive 15 cha aracter string that is used to uniquely identify the record throug r ghout the pla atform. To view a record in the salesforce.com UI, simply ap m ppend the reco ID to ord your sale esforce.com domain. Fo or instance, when yo ou enter https://na1.salesforce.com/0 0014000000Hg g6pL, Force.co will fetch th record om he from the database, along with its associ d iated metadata and display t record a, the using the automatically g a generated UI ba ased upon you security setti ur ings. Each recor is also requ rd uired to have a special nam field. This can either be an autome e nu umber field or a human-read dable identifier for the record to distinguis one record from one r d sh another. When F Force.com gen nerates a user interface, youl see that the value for the n ll v name field is always displaye as a link to the detail page of the record itself. Other read-only, syst fields a ed e d tem inc clude: Creat tedDate the date and time when the reco was create e ord ed Creat tedById the ID of the Use that created the record e er d
Jeff Do ouglas & Wes No olte 33

LastMod difiedById - th ID of the U that last m he User modified the re ecord LastMod difiedDate the date and tim when the r t me record was last modified by a User SystemM ModStamp the date and tim when the o me object was last modified by a User or system process (e.g., trigger, web se m ervice) S System fields are read-only. However, this can pose a pr a s roblem when trying t import data You may w to a. want to import created dates or created b for t by t these new reco ords. You can c contact salesfo orce.com support and ask them to e enable Create Audit Fields This will allo you to imp some read e . ow port d-only f fields for most standard and all custom obj t jects using the Data Loader.

In addition to traditional dat I tabase function nality, the Forc ce.com databa has a numb of ase ber service baked-in. es Apex Triggers Similar to othe database trig S er ggers, Apex T Triggers can be programmat e tically configur to red fire be efore or after a record is cre eated, updated, deleted or un , ndeleted1. Trig ggers have acce to ess virtual all Apex fun lly nctionality with a few excepti h ions (e.g., no c callouts). Valida ation Rules These rules help enforce data integrity from both th salesforce.c T d he com UI and API2. Valida ation rules fire each time a record is saved and perform the validatio against a c r d ms on certain field based upon a f b formula expression. If the e expression eva aluates to true the save is ab borted and an error message is displayed (or sent back t n ( through the AP For instan you can cr PI). nce, reate a validat tion rule statin that a field always contain a value or t ng ns that a number entered into a field falls within a certain range. w Formu ulas These dynamic T cally generated fields are the real workhors of Force.co A formula field d ses om. a behave much like a spreadsheet formula in th it reflects some calculati based on other es hat ion fields and operation based upon those fields3. For instance, for an opp ns n portunity you could at d ounted field: { {!Amount} ({!Amount * t} create a formula tha contains a discounted amo {!Pct t_Discount} . This amo }) ount would di isplay on any page layout, could be use for ed reporti and would look like a reg ing d gular field to q queries. Field History You can confi Y igure each obj ject to track c changes to field values (up to 20 fields). Field history can be displa y ayed on the page layout sho owing the befo and after value, who cha ore v anged the field and the date and time it was changed. e w
intro-t triggers validat tion-rule-example es 3 intro-t to-formulas
1 2


Salesforce Handb book

You can contact salesf force.com Sup pport and ha them increase the ave number of fields that can be tracked for your Org We have seen them f d g. increased this number 40 for most requ 0 uests.

Pl latform Lim mits

Every programming en nvironment im mposes its ow sets of co wn onstructs, feat tures and constraints. The Force.com platform is no different. All programs, se e p l ervices and ap pplications run nning on the p platform run in a multi-tenan environment where their resources (e.g., memory, n nt r , network, database connection are being s ns) shared with ev very other pro ogram on the platform. Th herefore its ex xtremely impor rtant that the p platform preve rouge, run ents naway applicati ions from sat turating system resources an degrading t performan of other ap m nd the nce pplications also running o on the platform Force.com im n m. mplements a number of go overnors and limits to ensur that all l re applications pla nicely with each other. O of the main tasks for new developers i learning ay h One n w is ho to write app ow plications that run within the boundaries. ese s They often for us to take a step back an analyze rce nd Governors are not evil. T our code to ensure that we are using best practices and system resources t g efficiently. Salesforce.com engineering is actively wo m orking to stream mline and make gove ernors and lim easier to work with. The Winter 1 release mits T 11 simplifies some of the lim surroundin test method s mits ng ds. Limits com in many flav and may o not be in re me vors or elation to the edition you are running1. Fo instance, the is a limit to the number of application you can cre or ere t r ns eate, the numb of tab ber for an Org and the number of custom fiel an object may have. Wh developin custom r o lds hen ng applications, you have to activ take into c u vely consideration A Apex governor and limits. T Apex rs The run ntime engine s strictly enforces limits and i issues a runtim exception if, for instance a script me i e, exceeds a limit. Limits differ based upon th entry point of your code For instance when a he t e. e, Tr rigger is called from a Visual lforce Control the Apex r ller runtime engine uses the limi for the e its Visualforce Cont troller, not the limits for the Trigger. e Governor exceptions cann be caught a handled lik most other ex e not and ke xceptions. However, you can test for limits program y r mmatically usin the Limits cla which ng ass, returns the amount of reso ources available in the current context. e t its tweaked by salesforce.com using their internal m r Some limi can be t provisionin feature or ng black tab. F instance, the API limits are 5000 For t calls per us per 24 hou However, salesforce.com Support can increase ser urs. m n this limit on a case by cas basis. se

go overnor-limits-int tro Jeff Do ouglas & Wes No olte 35

Sales sforce.com E Editions

Salesforce.com offers a number of bundles of its produc and service called editi S m s cts es, ions, that pr rovide the sam look and feel but differ by price, features and functio me onality1. Within each n edition companies can purchase different lice n enses, which allows them to access diff fferent feature on the platf es form. These ed ditions and licenses become very importan when devel nt loping applica ations as you have to ta u ake your pot tential users edition and license types into consid deration before offering func e ctionality. You may develop a great manage package tha fails ed at when a customer ins stalls it due to restriction (edi r ition and/or li icenses) in thei Org. ir W cant stress how importa it is to kno the features and restrictio of We s ant ow s ons e each Edition. Applications that you dev velop on one Edition may not e y f function on another Editio due to a f a on feature not en nabled or a s of set g governor limits s. Sales and Service C Cloud Edition ns Conta Manager E act Edition Contact Manag (CME) is a starting point for many sma business and provides acc to C ger t all d cess key CRM features such as accou unts, contacts activities, ca s, alendars, notes, attachments and reports. CME is cus stomizable to a point and i designed to whet a users appetite for more is s functio onality. Contac managemen supports up to 5 users and is priced at $5 ct nt d 5/user/month h. Store and m manage unlimited contacts Track custo omer interactio via reporti ons ing Stay on top of your day with tasks and reminders p w Works with any email app h plication Integrated w Google Apps with A Share docu uments using th content libr he rary Mobile access

Restrictions inc R clude no acces to Apex, Vis ss sualforce, API sharing rules scheduled reports, I, s, workfl low, approval processes, ass signments, cus stom labels, an nalytic snapsh hots, marketing user g license (thus no cam e mpaigns), prod ducts or priceb books, opportu unities, leads, forecasting, account f or sale teams, multi currencies, custom profil and develo es iple , les opment sandbo oxes. Group Edition p Group Edition (GE) is tar G n rgeted toward small busin ds nesses and tea ams of up to five o provid sales and support functi ding ionality and is priced at $25/ /user/month. In addition to what o

edition ns Salesforce Handb book


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 cant 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:

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.coms infrastructure even if its 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.coms 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 20MB of data and 600M of file stora mits, d MB age/user Up to 25 F Force.com Sites with up to 50 s 00,000 page vie per month ews h 1 Develope sandbox er API access for integration with third-pa application n arty ns Fully customizable mobil capabilities f an addition fee le for nal

Force.com Unlimit ted The Force.com Unlimited Edition (FUE) offers virtuall unlimited cl T m E ly loud computin for ng your entire company for $75/user/ y /month. 24x7 Premi Support ier Complete c cloud platform m Secure and reliable cloud infrastructure e Unlimited n number of use ers Up to 2000 custom objec 0 cts Access to a accounts and contacts c Unlimited a apps per user Storage lim 120MB of data and 600M of file stor mits, f MB rage/user Up to 25 F Force.com Sites with up to 1,000,000 page v s views per mon nth Multiple sa andboxes devel lopment, testin and training ng g API access for integration with third-pa application n arty ns Fully customizable mobil capabilities le

Devel loper Edition The Developer Edition (DE environmen is where yo develop yo application for T r E) nt ou our ns free . You can have a many DE Orgs as you need for any type of purpose. You can sign u for Y as O Y up a new DE Org on th home page of http://devel he e loper.force.com an be up and running in a m nd matter of min nutes. If you ar testing conf change imp re fig pact, developin new Apex co or develop a ng ode ping packag application for distribut ged n tion, most of y your time will probably be spent in a DE Org. s E Additi ionally, all man naged packages (applications) must be deve s ) eloped in a DE Org. E

Y cannot de You eploy code to p production or sandbox envir ronments from a m D Org using Change Sets. Y will need to use the For DE You rce.com IDE, c create an unma anaged packag or move the code manually ge y.

develo oper-edition Salesforce Handb book


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 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

DE Orgs also have special limits based upon the nature of the edition:

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

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 dashboards 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 users 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

the are involved access custo objects bas upon their profile and re ey d, om sed eceive the Por Super rtal Us permission ser n. Cu ustomer Porta Manager Custom al C An extensio of the Custom Portal Ma on anager Standar license, this license also a rd s allows the use to run rep er ports based their profile s t settings plus r receive the Delegated Po ortal User Ad dministrator p permission. Partner po ortal users can also have th following two user lice n he enses entitling them to additional features: Silver Partner - This license en r T ntitles the user to access Sa r alesforce CRM Content M (based up feature license and p d profile), 2 MB of data stor B rage and acce to the ess docum ments tab, app provals and My Account Prof y file. Gold Partner - Th license ent his titles the user to access Salesforce CRM Content r M (based up feature li d icense and pro ofile), 5 MB of data storage and access to accounts, f leads, opportunities, cases, cust tom objects, documents ta approvals and My ab, Accou Profile. unt

Hi Volume C igh Customer Por User rtal This license is designed for contacts wh need access to customer support information in e f ho your Org. These users dont have roles, don appear in th role hierarc and can on access e h nt he chy nly specific records based upon specific criteri These user can access accounts, asse cases, ia. rs ets, contacts, custom objects, docu m uments, ideas, a questions depending on their profile settings. and Ch hatter Only Salesforce.c com recently announced a C a Chatter license for users who typically do n access o not Sal lesforce CRM but need to collaborate with other users via Chatter. The l M t e C license is $15/user/month and allows th user to acce profiles, st h he ess tatus updates, people directo ories, realtim feeds, file sharing/cont me tent, groups, ideas, contact accounts, dashboards, r ts, reports, 1 custom app and up to 10 custo objects. om Be careful when purchas sing salesforce e.com licenses on a budget. You may be tempted to save mon by choosin a cheaper license but down the d ney ng road you may discover that your users do not have access to required h o features.

St tandard Sale esforce.com Applicatio m ons

In addition to core CRM functionality salesforce.co has develo n M y, om oped a large n number of sta andard applicat tions that you can utilize bas upon your license. sed

Jeff Do ouglas & Wes No olte


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 users 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


Salesforce Handbook

Sa alesforce Idea as This comm munity applicat tion allows use to post idea and vote an comments o them1. ers as nd on Ide can be org eas ganized into categories (e.g., New Produc Developmen Peripherals Gloves) ct nt, s, and sub-groups allowing users to filter and drill into wha interests them. You can use Ideas s d at int ternally within your Org or make it availabl externally vi the custome portal. m le ia er Salesforce.com uses Idea to develop new ideas for future releas Users as r ses. can vote id up or dow to let Produ Managers know which fe deas wn uct k eatures are important to them. Salesforce.com a actively uses these new ide when t eas determinin new features to include in future releases ng s s. Sa alesforce Answ wers Answers in another com n mmunity appl lication that a allows membe help one another2. ers Sim milar to a mes ssage board, users ask questions, commu u unity experts (o other commun users nity and customer se ervice agents) provide answe the comm ers, munity votes on the best ans n swers and the best knowledge in the com e mmunity bubb up to the top. Compan can sharp reduce bles e nies ply sup pport costs by tapping into the power of t y their commun nities resulting in faster answers, fewer inb bound calls and happier cust tomers. Sa alesforce Mob bile Salesforce M Mobile is a feature that enables users to a access their sa alesforce.com d from data the iPhone, Bla eir ackberry, Palm Treo and Win m ndows mobile devices. The Salesforce Mobile client S application exchanges data wit salesforce.co over wirele carrier netw th om ess works, and stor a local res copy of the user data in its own database o the mobile device. Users can edit local copies of rs o on the salesforce.c eir com records when a wirele connection is unavailab and transm those w ess n ble, mit changes when th connection becomes ava he n ailable. Admin nistrators can create multipl mobile le configurations d determining the types of data that can be ac e a ccessed. A sep parate Salesforc Mobile ce license is require for each use running the client. For P ed ers e Professional, Enterprise, Unli imited, or De eveloper Editi users with ion hout mobile li icenses, salesfo force.com offe Mobile Lit a free, ers te, res stricted version of Salesforce Mobile. n e Cu ustomer Porta al The Custom Portal allo you to deli a personal mer ows iver lized, service application to y a your most 3 im mportant custom . The Cu mers ustomer Portal consists of fu l functionality si imilar to salesf force.com and is one of th most use and custom heir ed mizable offerin Many oth application use the ngs. her ns customer portal in the backgro ound for authe entication (e.g Force.com Sites, Ideas) so dont be g., S o sur rprised if you see it poppin up from tim to time. F ng me Functionality of the Custom Portal o mer inc cludes but is not limited to th following: he

id deas an nswers 3 cu ustomer-portal

1 2

Jeff Do ouglas & Wes No olte


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: 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 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 others objects and fields for virtually any type of record (e.g., lead, accounts, opportunities, custom objects) in one anothers 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 youd 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 companys
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. Youll 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 youll 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 thats 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.


Salesforce Handbook

Contacts th are not lin hat nked to an account are alway private, rega ys ardless of your Org sharing m gs model. Only the owner of the con ntact and administrat can view i Sharing rule and workflo rules do no apply to tors it. es ow ot private con ntacts. Le ead Leads are s simply prospec ctive customers that you are trying to sell to. Leads can b entered be ma anually, impor rted or capture from a Web ed b-to-Lead form on your com m mpanys websi Leads ite. are very generic in nature and contain both c e company and c contact inform mation. When n leads new are created you can automatic e cally assign th hem to sales p people with le assignment rules or ead t pla them in a queue to manage distributi ace ion. Your sale team will work these leads and at es w som point in the sales proc me cess convert them by cr reating a new account, con ntact and, op ptionally, an op pportunity. Ad dministrators can configure f field mappings which determ mines how the data from th lead is used to create the n account, c e he new contact and op pportunity. All open and clo osed activities f from the lead are attached to the account, contact, and opportunity. o o Once leads are converted t a they can no lon be viewed directly but d appear nger d do in lead reports. The lead obj contains IsConverted, C ject ConvertedDate ConvertedA e, AccountId, ConvertedCo ontactId and C ConvertedOpp portunityId fie elds. You can query for converted re ecords and det termine what accounts, con ntacts and opp portunities were created during the con nversion proce ess. Ca ampaign Campaigns are outboun marketing p s nd projects (e.g., direct mail program, semin print p nar, adv vertisement, e email) that you want to pla manage, an track within salesforce.co Both u an, nd om. lea and contac can be adde to campaign You can or ads cts ed ns. rganize campai igns into hiera archies for eas analysis of r sy related market tactics. Al campaigns ar executed ou ting ll re utside of salesf force.com bu you can track their respons and analyze their influence on new busin ut k se ness. Opportu unities can be configured to either manu o ually or autom matically associate multiple in nfluential cam mpaigns to determine what m marketing effo impacted s orts sales. Op pportunity Opportunit are past or pending sal for an account that you want to wor and/or ties o les u rk tra By using o ack. opportunities you are, in a s y sense, building your pipelin and enablin you to g ne ng perform sales f forecasting. Opportunities are one of the most wid O dely used and heavily d customized obje on the pla ects atform. Oppor rtunities allow you to track the individual products (op pportunity line items) that you are selling on the deal, m e y multiple quotes any partners involved s, s and competitor a their products that you a competing against. and are

Jeff Do ouglas & Wes No olte


For team sellin opportunity owners can set up sales te F ng, y eams of users assigned to sp pecific roles (e.g., account e ( executive, pre-sales consultan with specif access privi nt) fic ileges. You can also n split op pportunities to give credit to multiple mem o o mbers of the te eam. Forecasting is a way to estim quarterly revenue from your opportu F mate unities. The forecast amoun is based up your pipel nt pon line and is the total amoun of all Com e nt mmit opportu unities divided by the total a d amount of all Best Case opportunities. F a more gra For anular view, yo can ou setup customizable forecasting to reflect ho your com ow mpany forecas its sales. With sts custom mizable forecasting, you can forecast on a monthly or q quarterly basis, use different dates , when applying amou to forecas forecast ba unts sts, ased on revenu or quantity or both, and d ue define additio quotas based on produc families. onal ct Quote e A quote is a fo ormal proposal for products and services t you are of l that ffering for a sp pecific opport tunity. Oppor rtunities can contain multi iple quotes an quotes are created from an nd e opport tunity and its p products. Whe a quote and an opportun are synced, any change t line en d nity to items on the opport tunity will syn with produc on the quo and vice versa. You can also nc cts ote, v n create templates that allow you to email complet quotes as P t ted PDFs to prospects. Produ and Price Book uct Products are th actual items that you sell on your oppor P he s rtunities and quotes. Produc are q cts associa ated to one o more price books to cre or eate price boo entries. Pro ok oducts can ex in xist multip price book with many different pr ple ks y rices. For exa ample, you may have a N m North Ameri ican price boo with one se of prices fo your produc and a Sou American price ok et or cts uth book with a differe set of pri ent ices. You can also create default revenu and/or qu n ue uantity schedu for produ ules ucts or oppor rtunity line ite ems to determ mine how defa unit price are ault es handle ed. You can use th standard price book tha comes with salesforce.com or create cu Y he p at m ustom price books. The sta b andard price book is automatically genera b ated to contain a master list of all n produc and standa prices reg cts ard gardless of the custom pric books that also contain them. e ce When you add produ to your op ucts pportunities or quotes, you f have to se r first elect the price b book. W When importin products yo must also i ng ou import price book entries. I you b If a using cust are tom price bo ooks, you must also add the product to the t o s standard price book in additi to the cust ion tom price book k. Case Cases are the f C foundation of the Service Cl loud and are u used to track customer issue and c es inquiri Cases are t ies. typically used to track and m manage custom feedback, issues or ques mer stions. Cases can be create by support representative from web forms on you website (we ed es, ur eb-tocase), by customers themselves from the Custo fr omer Portal o directly from emails (ema or m ail-tocase). New cases ca be assigned directly to su an upport agents, case teams or case queues using r assignm ment rules. Cases allow you to interact w customer easily by sen u with r nding and rece eiving
50 Salesforce Handb book

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 Orgs reports, dashboards, price books, products, apps, and customizations under Setup, but exclude all of your Orgs standard and custom object records, documents, and attachments. Its 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.


Salesforce Handbook

Where Should You Develop?

Developer Sandbox Type Configuration-only sandbox intended for development by a single developer. Best used for developing extension app. Daily refresh. Unit and Apex Config-Only Sandbox Essentially a copy of your production Org without data. Best used for general dev with sample data. Daily refresh. Feature and regression testing with sample data Applicable if using subset of production data. Special case testing with sample or subset of data. Full Copy Sandbox 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. Developer Edition Free, separate development instance. Best used for standalone app dev. Small scale, ad-hoc application testing.




Not well suited

Not well suited

Integration Testing

Not well suited

Not well suited

Jeff Douglas & Wes Nolte


Getting St G tarted wit Salesfo th orce.com m

ow that yo have a good understandin of what sale ou d ng esforce.com is and what the platform s e consists of lets really dig into it. In this chapter well discuss the major fea f, d atures and benefits of using the Force.co platform a well as som of the majo design consi g om as me or iderations tha must take pl in a multit at lace tenant environ nment.

Managing Us M sers
Every user that has acce to the plat r ess tform is identi ified by a user rname, passwo and a ord sin ngle profile. Y You can acce the list of all users in your Org by clicking Se ess f etup -> Ad dministrati ion Setup -> Manage Users -> Users. The user record maintains e no only persona information such as phon number and manager but platform sett ot al n ne d t tings such as time zone, em encoding, approval sett mail , tings and mob configurat bile tions1. Users c cannot be deleted once the are created but can be de ey eactivated. You can change a users userna u ame once cre eated as long a it remains un as nique. Salesforce.com usernam must be unique acros all produc mes ss ction and sandboxes environments For instance two produc s. e, ction Orgs can nnot have the same username myu username@mydomain.com, but it can exist i both a in production and a sandbo Org. n ox Users can grant login permission fo administrators so that they can for impersonat users and tr te roubleshoot ap pplication issue security set es, ttings and record acce easier. Use must go to Setup -> Personal Se ess ers P etup -> My Perso onal Information -> Grant Logi Access and enter in an expiratio date to gran login access on nt s. Pr rofiles Profiles typ pically model a users job fun nction (e.g., sa manager, marketing assis ales m stant) and 2 use can only b assigned to a single prof . A profile defines the objects that a user can ers be o file e acc as well as the settings and permission for various functions on the platform. You can cess s a ns s . acc profiles b clicking Set cess by tup -> Admi inistration Setup -> Manage Us > sers ->
Pr rofiles.

Each profi is assigned a specific license that prov ile vides access to specific fea t atures and fun nctionality. M Many of the more granular settings for th platform (e.g., Schedule Reports, m he ( Im mport Leads, V View Setup an Configurat nd tion) and con nfigured at the profile level Profiles e l. determine:
1 2

users pr rofiles

CRUD pe ermissions per object determ r mining the user ability to cr rs reate, read, edi and it, delete rec cords Which sta andard apps, custom apps an tabs the use can view nd er The speci page layout the user sees per object ific The field d-level security settings that determine th users abilit to view and edit y he ty d specific fi ields for each object o Record ty ypes available per object to th user p he Login res strictions such as specific login hours and from which IP addresses a user d can login from Admin an general user permissions f managing t Org and ap within it nd r for the pps The Apex classes that a user is author x rized to execut te The Visua alforce pages a user is allowe to access ed S Salesforce.com includes a nu m umber of stand profiles in every Org. As only dard n c certain settings can be chang on standard profiles, it is highly recom s ged s mmend t you clone standard profi before usin them. that files ng

Roles Used in combi U ination with yo sharing se our ettings, roles co ontrol the actu records tha can ual at be view by users1. Users at any given role level can view, edit and report on all data own by wed g l t, o ned or shar with users below them in the hierarchy unless your Orgs sharing model for an o red n y, object specifi otherwise. For example, if your role hi ies ierarchy conta a VP Sale North America ains es, and a VP Sales, E Europe role with additional roles undern w l neath (e.g., Ch hannel Sales, D Direct Sales, Government) then all record owned by u ds users under the VP Sales roles will be acce e essible to the users assigned to the VP Sales roles. Ho d S owever, users w not be abl to access re will le ecords d rs erarchy. This e ensures that bo osses have access to owned by other user above them in the role hie all reco owned by their subordi ords y inates and som that are priv to them. All users that re me vate A equire visibili to the entire Org should belong to the h ity e b highest level in the hierarchy n y. The role hierar T rchy is not nec cessarily your org chart but it may be simi You can a ilar. access your Orgs roles by clicking Setup -> Admin O nistration Setup -> Manage User M rs > Rol les. It is not necessary to create individ t dual roles for e each title at yo company, r our rather each role in the hier rarchy should represent a lev of data acc that a use or group of users vel cess er f needs. A role is option but it is a b practice to assign each user one. Every user nal best o u y s should be assi igned to a role or their dat will not disp in oppor e, ta play rtunity r reports, forecast roll-ups, and other display based on rol d ys les.

roles Salesforce Handb book


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 users 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 users 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 users 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, youll need to determine your Orgs 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 ca then use ro hierarchies, sharing rules, and manual s an ole , , sharing to ope up the recor to en rds other users who need to access. u Org-wide defau specify th default level of access to records and ca be set sepa O ults he l an arately for mo standard an all custom objects. Organization-wide sharing setting can be set t the ost nd gs to follow wing: Public R Read/Write - All users can v A view, edit, and r report on all re ecords. Public R Read Only - Only the owner and users abo them in th role hierarch can O r ove he hy edit recor All other users can only v rds. u view and repo on records. ort Private - Only the own and users a ner above them in the role hiera n archy can view edit w, and repor on records. rt Controlle by Parent - A user can o view, edit and report on a detail reco ed only t ords if they have access to the associated pa e e arent record. F example, a user can only view For y Activities for a Contact if they access to that Contac record. ct Public R Read/Write/T Transfer - App plicable for Le eads and Cases only. All user can s rs view, edit transfer own t, nership, and rep on all reco port ords. Full Acc cess - Applica able for camp paigns only. U Users can view edit, delete and w, e, transfer o ownership of records. Users can share rec r cords with oth users but cannot her grant them Full Access. m . A Administrators and users w the View All Data or Modify All s with w a D Data profile permissions c checked have full access to all records o the o of s selected object type, regardle of the shari settings for the object. t ess ing r

Figure 2 - 1. Org-wide d defaults decision model. n

After you have defined the Org-wide defaults, you can s A e O specify whethe users have a er access to dat owned by or shared wit their subor ta th rdinates in th hierarchy. Similar to, bu not he S ut necess sarily an Org ch hart, a role hie erarchy represe the level o data access that a user or g ents of t group of use have. The role hierarc ers e chy ensures t that a supervi isor always has access to their h subord dinates record regardless of the Org-wide default settin In addition to role hierar ds f e ngs. n rchies,
58 Salesforce Handb book

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


2 sharing example by object. e Figure 2 - 2. Security and s

Field Accessibility Since access to fields can be a confusing c S o combination o page layouts field-level se of s, ecurity and pr rofile permissions, salesforce e.com has a ha andy little sect tion called Field Accessibilit that ty allows you to view field access by profile or f b field for a par rticular object. You can find this . d section by clicking S n Setup -> Ad dministrat tion Setup -> Securit Controls -> ty s Field Accessib d bility. You can choose a field and v u view its access sibility by diff fferent profile and record t es types. You can also choose profile and vi field accessibility for diff n iew fferent record types. d


Salesforce Handb book

Figure 2 - 3. Account field accessibilit for a particula field, profile, or record type. e f ty ar

You can th click a fiel to modify th accessibility for that field based upon field level hen ld he y d sec curity and/or p page layout.

Jeff Do ouglas & Wes No olte


Figure 2 - 4. Modify the fiel access setting for field-level security and pa layouts. . ld gs age

Recor Types rd Record types a an extreme powerful fe R are ely eature of salesf force.com that allow you to offer t differe business pr ent rocesses, segm ment data and personalize th UI based on user profiles1. By he o default objects do n use record types. Once yo add a recor type for an object, the pla t, not ou rd o atform will ad a new field called RecordT dd TypeId to the object. You c determine which profiles have can s access to individual record types and display d different page layouts to use based upo the ers on record record type. You can also determine the picklist value that are avail ds . e es lable for the picklist fields on the object f a specific record type. o for When a user cr W reates a new re ecord they will be presented with a picklist of available r l t record types for the object and will be required to choose the type of record the are creating The f t r ey g. platfor will automa rm atically display the page layou based upon their profile. ut For example, a use case for record types m be a comp F may pany that repa equipment The airs t. compa repairs two types of equ any o uipment, gasol line and diesel engines, so they create a r l t record type fo each one. W or When employee create a new record they s es w select the type of engine (gasoline e or diesel) and enter data about th engine base upon the r he ed record type. For gasoline en F ngines

record d-types Salesforce Handb book


the may be a fi that allows the user to en the date t engine was last serviced, while this ere field nter the fie does not d eld display for dies engines. Th sel here may also be a field for the user to select the o ori of the equ igin uipment. For gasoline engine the picklist values may be North Ame g es e erica and South America while for die engines th may be North America South Ame esel hey , erica and E Europe (they o sell diesel engines in Eu only l urope). When a use views a piec of equipmen in the UI, t platform will automatical display er ce nt the w lly the correct page layout for the users profile based upon t record type of the record Record e e e the e d. typ are extrem useful in th you can cr pes mely hat reate views, rep ports, workflo or Apex trig ow ggers that seg gment or oper only on specific record ty rate ypes. For users t that typically use only a singl record type you can set a default record type for u le d eac object thu allowing the to skip th record type select proce when crea ch us em he ess ating new rec cords. Again, p profiles can be assigned acce to specific record types, which does not impact e ess sec curity in any w Users can still view rec way. n cords irrespect of record types (based upon the tive sha aring model o course) and even change the record ty to any ava of d ype ailable record t type. The rec cord type limit tation imposed by profiles is only enforced when a record is created. d d d

Au utomate Bu usiness Proc cesses with Workflow

Workflow i one of the most widely used and loved f is m features of sale esforce.com1. W Workflow giv you the abi to automa and enforce key business processes with ves ility ate e hout the need to write a sin line of cod ngle de. ck our equirement ca be met an You should always chec to see if yo business re using work kflow before w writing Apex co ode. All workflo rules are ac ow ccessible by cli icking Setup -> App Se etup -> Cre eate -> Wo orkflow & Approvals -> Workfl low Rules. Workflow ru ules are config gured per ob bject, fire based upon chang to record v d ges values, filter re ecords based upon some typ of rule u pe cri iteria and then performs some sort of action immed s diately or at a point in th future. he Workflow rules c be configu to fire: can ured When a record is cr n reated, or when a record is edited and did not previously meet the n n y rule criteria Only when a record is created d y d edited Every time a record is created or e

Records pr rocessed by wo orkflow rules m also mee a rule criteri must et ion. You can c choose to n a tatus equals R Rejected) or a formula that you write run the rule if a certain criteria is met (i.e., St evaluates to true (i.e., OwnerId <> LastMod d difiedById).

workflow w Jeff Do ouglas & Wes No olte 63

Figure 2 - 5. The name, description, and criteria to trig d gger your workflo rule. ow

One of the m O most agonizing decisions you make when creating a new workflow r u w rule is determ mining when th workflow rule should fir If you want the workflow to fire only when he r re. t w the record is created then choose (obviously) the Only wh e hen a reco ord is created optio on. If you w want a rule to fire each time a record is created and updated (repea e u atedly) regard dless of the ru criteria, then choose Ev ule very time a record is created or d edite . The only caveat with this option is that you cann add timeed t not -dependent ac ctions. Perhap the most w ps widely used op ption is When a record is create n d ed, or whe a en
recor is edit rd ted and di not pre id eviously m meet the rule crite r eria.

Choos this option to include new records and updates to exi se w isting records, unless the rul just le ran an still meets th rule criteria The rule is n re-triggere on edits tha do not affec rule nd he a. not ed at ct criteria For example if setting a leads status to In Progress causes the ru to fire, wit this a. e, l o ule th option the rule wil only fire ag n, ll gain if the lea ads status cha anges, then ch hanges back to In o Progre no mat how many times you edi the record. ess tter y it When workflo rules fire, you want som sort of act W ow y me tion to be per rformed. Wor rkflow actions can be conf figured to hap ppen immediat or at som point in the future. Immediate tely me e workfl actions are self-explanat low e tory but with ti ime-dependen workflow actions you coul for nt ld, examp have salesf ple, force.com auto omatically send an email rem d minder to a sup pport case ow wner if
64 Salesforce Handb book

the case has not been modified in the last tw weeks or cr e d wo reate a task for the VP of Sa to call r ales a customer 5 day before an op c ys pportunity is scheduled to close. Time-depen ndent workflo is not analo ow ogous to a syst scheduler where a proce runs at tem w ess som date in the future to fin records that meet a specif criterion. When a record is saved, me e nd t fic W d the platform che e ecks to see if the record mee the workflo rule criteria If so, it sche t ets ow a. edules the act tion(s) to take place at som point in the future. If th record is ag e me he gain updated and it no lon meets the workflow rule criteria, then all affected ac nger e e n ctions are canc celled. When work kflow rules fire they can auto e omate the follo owing types of actions: f Field Updates - Update the valu of a field on a record. For example, auto d ue n r omatically chang the leads ow ge wner to a queu or another u based upo the value o the lead ue user on of status s. Emai Alerts - Sen an email to one or more r il nd recipients. For example, auto r omatically send a account ma an anager an emai notification w il when a suppor case closes. rt Tasks - Assign a new task to a user, role or record owner. For example, autom matically assign a follow-up task for the a n account manag to call and thank a ger d custom one week after the oppo mer ortunity closes. Outb bound Messag - Send a s ges secure, configu urable API me essage (in XML format) L to a d designated list tener. For exa ample, automa atically notify an external H system a HR when a user updates their home p s phone number.

Developing A Approval Pr rocesses

Approval p processes are an extension o workflow an are often ta a of nd alked about in the same 1 context . An ap pproval proces is an autom ss mated process your compan can use to approve ny o rec cords in salesf force.com. App proval process build upon workflow by allowing you t specify ses n to a sequence of s s steps that are required to a approve a reco The proc ord. cess specifies the steps necessary for a r record to be ap pproved, who must approve it at each ste and the acti e ep ions to be tak when a re ken ecord is submi itted for appro oval, approved rejected or recalled. You can build d, r complex approv processes th dynamicall evaluate and route approv based upon specific val hat ly d vals iteria. For insta ance, you coul build an app ld proval process for purchase requests that r routes the cri approval to an em mployees man nager for reque under $10 while reque over $1000 are sent ests 000 ests to the purchasing manager. g You can al enable approval via emai This allows users to simpl reply to lso il. ly an email by typing appro y ove, appro oved, yes, reject, re ejected, or no in th first line of t email body and adding comments in th second he the y c he line.

ap pproval-processes Jeff Do ouglas & Wes No olte 65

re cess. Figur 2 - 6. A sample approval proc

Setting up an a S approval process involves m many steps and quite a bit of planning to do it d o correctly. You may w want to visual design your process with all stakeholde to ensure t lly r h ers that it nts. h ate s ndard Setup W Wizard meets all requiremen This will help you transla the process using the Stan mp d. e ed p p or Jum Start Wizard Some of the steps involve in setting up an approval process include: Determin records th should be processed f approval - Your proces can ne hat e for ss either inc clude all recor for a part rds ticular object or you can fi ilter them by entry criteria. T criterion can either be a combination of field values (i.e., Lead Sta = This c s atus Negotiat tion/Review) or a formula that evaluates to true (i.e., Amount > 10,00 00). Specify w which users are allowed to submit re ecords for ap pproval - You can u configure the process so that only the record owne or creator, members in a p e e er m public group or users in a spec role can su cific ubmit records for approval. Specify the sender of approval requests - By default, approval re l equest ons er cify notificatio are sent from the use submitting the request. You can spec a different from addres if required b your busines processes. ss by ss
Salesforce Handb book


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 submitters manager, a user or queue that the submitter chooses, a queue specified by the administrator, a user listed in the submitters 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 users 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 users Home tab layout.

Jeff Douglas & Wes Nolte


Figure 2 - 7. It tems to approve displayed on th Home tab. e he

Y can also write Apex t You triggers to aut tomate approv processes based val u upon some va alue on the record. For inst tances, you may want to sta an art a approval proce when an op ess pportunity reac 30% proba ch ability. See chap 6 pter f a detailed example. for e

Form mulas
Formulas are a prevalent fea F ature in the declarative development area of salesforce a e.com. The re eason for thei popularity is because they are a simple way for non ir e n-technical use to ers transla business req ate quirements int application l to logic. Dependi on their co ing ontext, formula can as be use to present dynamically calculated field values, deter ed c d rmine default field values, e ensure 1 data in ntegrity or det termine execution criteria . Although its important to discuss the va arious contex its worthw xts, while introducin the commo ng onalities such a syntax. as A youll see la As ater, the declara ative developm areas that use formulas dont ment t r require any Ap code or u testing. T pex unit This often ma akes them easier to m maintain or change, and very quick to impl y lement. It is fo these reason that or ns i highly advised that you c its consider using these features as an alternat to tive p programmatic development w where possible e. Syntax x Formulas are e F essentially equ uations that ar executed at runtime e.g. when a page loads. re w Key to know at this point is that these equation arent just m o t ns mathematical, but can also in b nvolve the ev valuation of lo ogic. Although it is beyond the scope of this book to detail the topics of h mathem matics and the languages of logic, consider the following simple examp e r g ple: Your business requirement is that you need a field that w display a discounted valu for Y s d will d ue a purchased item if y your customer spends more than X dollars s. The first step required to tr T ranslate this re equirement int application logic is to word it to using something call pseudo co Essentially you need to break your pr led ode. y roblem into ph hrases separa ated by logica operators and (if requ al uired) mathem matical expres ssions. The a above require ement might b phrased as: be
IF custome I er A spend ds GREATER THAN X dollars TH R HEN they will recei ive a Y% di iscount ELS they dont receiv a discou SE ve unt.

intro-t to-formulas Salesforce Handb book


Here the w words in capita are the log als gical operators. The phrase between the IF and the . b F TH HEN is the ex xpression to evaluate, and t two logic-b e the branches will deliver the ap ppropriate res sults (a discoun or no discou nt unt). Once your business requ r uirement is ph hrased in this way then its simple to tran nslate this pseudo code into formula code The above e o e. example can be written as in Listing 2 - 1. e Listing 2 - 1. Sim mple Conditi ional Formula a
IF( Sale e_Amount__c > 2000, c Sales_Amount__c * 0.9, c Sales_Amount)

The details of formula sy s yntax is extensively docume ented in the re eference docum mentation bu its valuable to understan the categori that the gr ut e nd ies roups that syn ntactic compo onents fall int to: rences to obj ject fields - U Used to includ the value of other field in your de ds Refer formu Note that you can refe ula. t erence related object record fields very e d easily too! More on this later. Oper rators - As mentioned befo these can be either log m ore gical operators (used to determ mine the truth of a stateme or mathem h ent) matical operato (used to c ors calculate a value) ) Litera - These are values that yo hard-code, such as pieces of text or num als e ou mbers Func ctions - The platform offe a number of built-in functions for common ers f opera ations. Many of these are s o similar to tho offered in Excel and fa into 4 ose all catego ories: Date and Time, Text, L d Logical and M Mathematical Globa Variables - Provide acce to system o other conv al ess or venient inform mation. An examp is the $Org ple ganization.Nam me

Figure 2 - 8. Various F e Formula Syntax Components x Jeff Do ouglas & Wes No olte 69

Cross Object Form mulas Often youll fin that you ne to refer to fields in records that are re O nd eed elated to the cu urrent record that the form is being ap d mula pplied to e.g. th formula mig apply to a Contact record, but he ght in that formula you might want to refer to the related Accou record. Luc t o unt ckily salesforce e.com has ma this very si ade imple and the feature is aptly named Cross Object Form y s mulas. N Note that it is only possible to access the fields in the direction of ch to d hild p parent i.e. you will not be a u able to retriev the data of child records from ve t their parents. The syntax for these referen T r nces is natural and precise. C Consider the situation wher you s re need to create a for t rmula for a Co ontact record, but you need to refer to th related Acco he ounts parent Accounts na t ame. In this ca the syntax would be Acc ase count.Parent.n name i.e. you a access the fie value by u eld using the relate field names (separated by periods) unt you arrive a the ed s y til at object field in quest tion. For custo objects the syntax is slig om e ghtly different e.g. if the formula t applies to a custom object and ne s eeds to interrog the paren objects nam field throug the gate nt me gh Parent t__c relationsh field, the sy hip yntax would be Parent__r.na e ame. This is very p T powerful, espe ecially when y you consider that you can traverse up to 5 n 1 relationships deep (y can mix st (you tandard and cu ustom objects relationship). Where Do I Use Th e hem? Formulas can b used in a number of area within the p F be n as platform as pre eviously menti ioned, and de epending on th context can be used to achieve differen types of resu heir n nt ults. Formu Fields ula These are read T d-only fields with values def w fined by the u underlying form mula. Data in these fields are not persist but is calcu a ted ulated on the f when the f fly field is accessed. Creating formula fields can be done fr c rom the same area as the oth field types. a her At creation tim youll need to select the type that you wish the field to adop e.g. A me d e pt curren date, and t ncy, text. The type you choose af ffects the field display, but also how the fi is d a field seen by any Apex or API interroga b r ations. U Using formula functions yo implicitly h a ou have access to some sub fieldt types including hyperlinks an images. g nd You are free to use any com Y o mbination of fo ormula compo onent in formu fields as lo as ula ong the resultant value i of the pre-determined ty is ype. This way you have a powerful slate upon p which you can use conditional lo to presen a range of d ogic nt dynamic value types to you end e ur users.

cross-object-formulas Salesforce Handb book


Never use a formula fie as an index eld xing or filterin value. If yo need a ng ou field value to be dynamic cally calculated but know tha it will be use to filter d at ed data throug API calls o in the WHE gh or ERE clause of any SOQL s f statement, consider using static fie u elds in combin nation with workflows inst w tead. The reason her is that the calculation o formulas ca be especia taxing re of an ally under the hood to the platform in these conditio and will r e e ons result in a performance loss. De efault values When decla aring most fiel types you h ld have the oppor rtunity to decla a default value. This are can either be as simple as a lite value or al n eral lternatively a fo ormula of any complexity. If no value f is specified for th field when a record is crea then it wi be assigned said default va s he ated ill alue.

Fig gure 2 - 9. Using formulas in def g fault values

Jeff Do ouglas & Wes No olte


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. Youll 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 thats 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.

validation-rule-examples 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
<apex:outputPanel rendered={!NOT(ISNULL($CurrentPage.Parameters.Id)}> $CurrentPage.Parameters.Id </apex:outputPanel>

Although the syntax of formulas here is slightly different (youll have access to number of other functions, operators and global variables) the overlap is so large that youll 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 doesnt abuse the shared pool of resources, it is necessary to impose certain limits on formula field usage. 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 Its common to exceed the length for formula fields and its 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). Its 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 mightve 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 youll 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. 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 youll 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 youre 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 isnt a whopper of a formula but its good to keep your house in order. In this type of situation its 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 youll just have to use a formula that cant 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 youll need to create an object field of the type youd like to present. The Workflow or Trigger would then update this value at creation, update or both of object records. With Workflow youd 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 youd have to translate the required logic into the Apex and write the value to the records field. As seasoned developers, wed highly recommend writing formula code in a text editor with some concept of syntax highlighting and bracket matching. Youll 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 youll 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 many of the and wed recommend p nt ese poring 1 over th as a start, or even as a reference to mo experience formula users . hem ore e s

Valid dating User Input

In addition to workflow and formulas, va I d alidation rules are one of the most widely used y feature on the platf es form. Validatio rules help e on ensure data int tegrity by verif fying that the d a data user en nters meets ce ertain standard Validation r ds. rules fire when never a user attempts to insert or change a record. The rules preve incomplete or junk data from being entered by mi e ese ent e a istake, which in turn causes more issues to creep up dow the road. s wn To get started using valid T d dation rules, click Setup -> Custo omize, selec the ct approp priate object fr rom the menu, and then click Validatio Rules. , k on A validation ru can contain a formula o expression that evaluates the data in o or ule or one more fields and retu urns a value of true or f false. The vali idation rule ca be configur to an red display a custom err message to the user, eith at the top o the page or next to a spe y ror o her of r ecified field. A validation ru will fire an display an e ule nd error message even if the of ffending field is not display on the pag layout. yed ge

Figure 2 - 10 Configurating a validation rul to fire if an em address is not entered. 0. g le mail n


useful-validation-formu formula-cheatsheet ulas, Salesforce Handb book


Validation rules are a pla atform level service and no simply for the UI. Validation rules ot t apply to all new and updated records for an object even w r when processed by one of the APIs or d du uring the data loading process. Administra ators must b aware tha adding new validation rules in be at w production may break ex n xisting process and integrations. Always test in a ses s sandbox en nvirnoment be efore making p production cha anges.

Bu uilding Pub Website blic es

Force.com Sites allows you to exten your salesf nd force.com app plications and data by d cre eating public w websites and ap pplications tha run natively on the platfor 1. Since you sites are at rm ur ho osted on the Fo orce.com serve there are n ers, none of those pesky data int tegration issues allowing s you focus on c creating highly interactive, s y scalable websi ites. Force.com Sites are bu using m uilt Visualforce and Apex, and th can leverag the data, co hus ge ontent and log that reside in your gic es Or You can s up your site to be wid rg. set de-open to the public or re e equire a usern name and password to acc cess it (via Cu ustomer or Partner Portals). Force.com ta . akes care of y your sites inf frastructure he eadaches freein you up to co ng oncentrate on building applic cations such as s: Corpo orate website - create a p e public-facing w website using standard web elements such a CSS, Flash and JavaScript frameworks ( as a t (e.g., jQuery, YUI) Y Empl loyee intrane - set up a c et company intran that uses single sign-on restricts net n, access by IP address and/or time of day s Colle new ideas - host a pub community forum for sharing and v ect s blic voting on Salesf force Ideas reg garding your co ompanys prod ducts and servi ices Micro osites - create microsites to collect feedb e o back or allow people to sig up for w gn webin or marketi informatio nars ing on Expo product information - publish you companys product cata ose i ur alog on a subdo omain of your existing website with detai r iled descriptio current pr ons, ricing and produ images all pulled seamless and in realuct p sly -time from you Org. ur

Setting up a new Force.com Site is r relatively easy. Start by clic . cking Setup -> App Se etup -> Dev velopment -> Sites. C Choose an ava ailable Force.co domain na om ame, enter the name of you site, pick a si administrat and the platform spins up a new site fo you in a e ur ite tor p or ma atter of second You can th create pag templates to give your sit a consistent look and ds. hen ge o te fee that matche your corpor el es rate branding. Your site tem . mplate provides the page la ayout and sty ylesheet for yo site and ov our verrides forma atting inherited from any ass d sociated portal that you l ma use. You can then start ad ay dding standard or Visualforce pages by asso d e ociating them with your site. Apex contro ollers and class provide the logic for your site. ses e

si ites Jeff Do ouglas & Wes No olte 77

Configuring pe C ermissions for your site look relatively fam 1. Visitor to your site use a ks miliar rs Guest user license and a Sites-sp t pecific profile You configu the permis e. ure ssion for this Sitesspecifi profile like y would any other profile in salesforce.com. You can configure tab and ic you y e n b record type access, p d page layout ass signments, field d-level security for standard and custom objects y and ob bject permissio (read, creat edit and del ons te, lete) for each s sites users. It is important to note i o that sa alesforce.com does impose some additio e onal access re estrictions for Sites visitors For s. instanc while visito can read, create, edit and delete custom objects they can only read and ce, ors c d m y create standard obje ects. Some obje such as pr ects roducts and pr books onl offer read a rice ly access. Be sur to check the documentatio before desig re e on gning your For rce.com Site.

Figure 2 - 11. Configuring perm C missions for Stan ndard objects.

Sites impose l S limits based upon edition but they are fairly liberal. For instance, with u , Enterp prise Edition th maximum page views per month is 500 he p r 0.000 and the bandwidth limi (per b it rolling 24-hour perio per site) is 40 GB. You can purchase more page vi g od iews if needed The d. numbe of individua Force.com Sites you can create is deter er al rmined by you edition. Yo can ur ou run yo site off of a Force.com domain name (h our http://acmecorp.force.com/intran or use your own net) r compa branded do any omain set up with a redirect via DNS. w Y can moni Sites users by adding th You itor s hem to the De ebug log. How wever, f public web for bsites this only provides a g y generic view of their actions. You f c also previe a site as an administrator and view de can ew n ebug info by a adding s some tags to th Visualforce footers. he

Going Global
With more an more globa companies adopting sale W nd al esforce.com, it no surprise that ts e interna ationalization an localization is an importan aspect of the platform. Sale nd nt e esforce.com sup pports geogra aphical segment tation, advance multi-currency and translati of the UI in 20+ langua ed ion nto ages.

profile es Salesforce Handb book


Di ivisions Divisions a allows you to segment your data into orga anizational bu uckets provid ding users with a view of data that is relev to their n vant needs1. You can set up divisio any way th makes n ons hat sen to your company such as geographicall line of busin (i.e., com nse s ly, ness mmercial or gov vernment) or any other typ of internal corporate gr pe l rouping. Divis sions do not restrict data a r access but ma akes data easie to manage and find for la er a arger Orgs. Fo instance, a sales manager in South or r Am merican may w want to run reports or for r recast sales on for South American an not be nly nd concerned with E European data a. Contacts salesforce.com Support to enable div m o visions for yo our Org. Divisions are meant for s a segmentation p purposes only and do not en nforce any type of security constrain nts. When divisions are enab bled, a divisio called global is autom on matically create and all ed rec cords are autom matically assign to this div ned vision by defau You can create up to 100 divisions ult. 0 bu you should c ut carefully plan your strategy in advance for h y n handling multi divisions. iple You will als need to set the default div so vision for each user. This is the division th applies h t hat to all newly created accounts, leads, and cust l tom objects fo which divisi or ions are enable (unless ed the user explicitl chooses a division). You can also enab the Affec e ly d ble cted by Div visions permission for p profiles so that users can set t their current working divis sion. Users can set their n w working divisi using a dr ion rop-down list in the left sidebar thus lim miting search results to rec cords in the se elected division Users witho this permis n. out ssion still have a default div e vision, can vie division fie ew elds, change th division for a record and specify a divis he sion while crea ating new rec cords. Howeve these users will always see records in all divisions. The permission a filters er, e l also list views by divi t ision and allow users to run reports for a s ws single or all div visions. Lo ocale A users L Locale setting affects the fo ormatting of n names, numbe date and d ers, date/time fie and calend elds dars. The Locale determines the order that first and last names are dis e t splayed for use leads, ers, and contacts. Fo instance, Mi Smith in th English (U or ike he United States) locale displays as Mike l Sm mith, while the same name in the Chinese (China) locale displays as S i e Smith Mike. times are also displayed per a users Locale. A date in the English (Unit States) e ted Dates and t loc will display as 04/28/20 cale y 000 while it di isplays as 28/0 04/2000 in th German loca Times he ale. in the English (U United States) lo ocale display using a twelve-h hour clock with AM and PM (e.g., 3:00 h PM while in the German locale they display u M), e e, using a twenty-four-hour cloc (e.g., 15:00). ck Dates are stored in the d s database in GM and conver on-the-fly using the MT rted users Loca To import data for a use with EST, use the format 2010-06ale. t er u t 25T18:25:0 00.000-04:00 w the 4 hour time zone of with rs ffset.

in nternationalization n Jeff Do ouglas & Wes No olte 79

Curren ncies The Force.com platform has support for multiple curre T m encies baked in from the gr i round up1. It provides ad dvanced supp port for multi iple currencies for opportu unity manage ement, forecasting and repo orting. With multi-currency enabled each international division can track, m h forecast and report on opportu t unities in loca currencies, while providi al ing enterprise e-wide forecasting and repo orting in a singl common cu le urrency. C Contact salesfo orce.com Supp to enable multiple curre port encies for your Org. r O Once enabled, the link wil visible and you can man ll nage currenci by ies c clicking Setu up -> Ad dministrati ion Setup -> Com p mpany
P Profile -> Manage Cur rrencies.

Once multiple currencies are enabled, youll need to set up a corpora currency w O e ate which reflect the currency used by the corporate he ts y eadquarters. Yo can then create and ma ou c aintain multip currencies in which yo do busines and their c ple ou ss conversion ra ates relative to the o corpor rate currency. Every user must have thei personal c m ir currency conf figured. When new n record are created, the users pers ds sonal currency is automatical used unless another curre lly ency is selecte manually. T personal cu ed The urrency is also used as the u o users default currency for qu c uotas, forecasts, opportuni ities and repor however o rts, other active cu urrencies are also available. Only a active currencies can be used in cu n urrency amoun fields. nt

Figure 2 - 12. Configurin multiple curr ng rencies.

When adminis W strators chang an existing conversion rate, all curr ge g rency amount are ts immed diately updated with the ne rate across the entire Org. This inclu d ew udes all conver rsions within opportunities, forecasts, and other am n a mounts that u the curren conversion rate. use nt n Previo conversion rates are not stored and you cannot track revenue gain or loss based upon ous n k curren fluctuation If currency changes seve ncy ns. y erely impact y your company you may wa to y, ant investi igate using Dat Exchange Rates. ted A opportunit currency c An tys cannot be mo odified once a product has been a added to it wit the default currency. You will need to remove all pr th u roduct r records first be efore you can m modify the opp portunitys cur rrency.

curren ncy-management Salesforce Handb book


Ad dvanced Curr rency Manage ement Advanced currency ma anagement allows you to manage date exchange rates for ed op pportunities. D Dated exchang rates allow you define a conversion rate for a specified ge w n currencys date range. For ex xample, a com mpanys exchan rate in th 3rd quarter and 4th nge he r qu uarters are 1 U USD to .60 EU and 1 USD to .75 EUR respectively All opportun UR D R, y. nities that clo in the 3rd quarter use th 3rd quarter exchange rate (1 = .6) while those that clo in the ose he e ose 4th quarter use the 4th quarte rate (1 = .7 This retain the historical conversion rates and h er 75). ns ten to be very beneficial to most large com nds m mpanies. Dated exch hange rates are used in conjunction with opportunities, opportunity products, e op pportunity prod schedules campaign op duct s, pportunity field and reports related to these objects ds and fields. Static conversion rates, instead of dated exch c hange rates, are used in fo a orecasting, currency fields in other objects and currency fields in other types of repo n s y r orts. When adva anced currency managemen is initially en nt nabled, your existing static exchange e rat automatical become you first set of d tes lly ur dated exchange rates. These rates are valid until you d define another set of exchange rates. Dated exchange rate are defined using a conve e es ersion rate and a start date. Each conversi rate is effective until the day before the next start dat for that ion e te currency or until either the end of time. l d

Figure 2 - 13. Creating a new dated e exchange rate.

When adv vanced currenc managemen is enabled, Visualforce inputField cy nt and output tField compon nents cannot d display currency fields. If yo enable ou advanced currency mana c agement, you cannot create roll-up summ mary fields that calcula currency on the opportun object. ate n nity Enabling multicurrency m have some unintended consequences regarding m may c SOQL que eries and aggre egate functions Be sure to ch s. heck the docum mentation for the imp plications of en nabling multicu urrency.
Jeff Do ouglas & Wes No olte 81

Trans slating the Us Interface ser Salesforce.com allows users to work in th language o choice with a simple lan S m heir of h nguage attribu on the user record. The salesforce.co UI is availa in Danish German, En ute rs e om able h, nglish, Spanis Finnish, F sh, French, Italian Japanese, K n, Korean, Dutc Portuguese (Brazil), Ru ch, e ussian, Swedis Thai, Chin sh, nese (Simplified and Chinese (Traditional). To translate customization that d) e ns youve made to yo Org or to override tr e our t ranslations fro managed packages, use the om Transl lation Workbench to translate virtually eve erything from custom pickli values to cu ist ustom fields into a suppo orted language1. These custo omizations ar also availab for partner and re ble custom portal user mer rs. As an administrator you add translatable languages to y A d your Org and optionally ass sign a user re esponsible for translating cu ustomizations. The admin int terface allows you to transla the ate text fo buttons and link labels, cu or d ustom fields, s standard field h help, record ty ypes, picklist v values, web ta and plus m abs much more.

Figur 2 - 14. Transla re ating picklist va alues in the Tran nslation Workbe ench.

Once enabled, the Translatio Workbench imposes som changes to your salesforce O on h me y e.com Org:

Picklist v values must be edited indiv b vidually and y you can no lo onger mass u update picklist va alues (mass add is still availab d ble) When sor alphabetica picklists are sorted alphab rted ally, e betical by the Orgs default lan O nguage Reports m have a lang may guage drop do for certain filter criteria own n Web-to-L and Web-t Lead to-Case require a language sele e ection before generate the HT g TML

transla ation-workbench-overview Salesforce Handb book


Not everth in salesfor hing rce.com is tran nslatable. You are currently n able to a not translate Visualforce tabs, homepage c V components elements or record type e description ns.

Using Analyt tics

Youve sp pent a lot of time, effort and money putting your important d f r data into sal lesforce.com a you want to be able to vi it, report o it and analyz it in a coher and o iew on ze rent, userfriendly manner One of the advantages of the Force.com platform is that it in r. e m ncludes a complete system for building reports, securing and schedu m r uling them and assembling c d collections of them into user-friendly das shboards. Its not as powerful as say Cry ystal Reports b it also but do oesnt have the steep learning curve and ass g sociated price t tag. While the t topic of analyti is extremely important, a deep-dive is beyond the sco of this ics y b ope bo Reporting is well docum ook. g mented in the u guide and there are num user d merous tutoria to help als get you started1. The best way to learn abo analytics is to simply sta building rep t y out s art ports and ass sembling them into dashboards. Well cove some topics from a high le m er s evel. The Winter 11 release sp r ports a new an greatly improved visual, real-time repor builder. nd r rt Th new report builder allow you to add reorder, and remove col he t ws d, lumns, summa fields, ary for rmulas, and gr roupings with ease. You can even change t report form and display options, e the mat y add a chart and p preview data in real-time. n

Figure 2 - 15. Creating a new Account and Contact report with the real-ti n d t ime report build der.

Choosing t format of the report dr the f rives a numbe of options that are availa er t able when act tually building the report. Th are three t here types of report you can cho ts oose from: Tabu - Tabular re ular eports are analo ogous to spread dsheets and are best for creati lists of e ing record or a list with a single grand total. They co ds h d onsist simply of an ordered se of fields f et in colu umns, with eac matching re ch ecord listed in a row. Tabular reports cant b used to be create groups of data or charts, and cant be used i dashboards unless rows are limited. e a d in e

re eports Jeff Do ouglas & Wes No olte 83

Summary - Summary reports are the most widely u y r used report typ These are similar pe. to tabular reports but also allow use to group r r ers rows of data, view subtotals and s, create cha arts. Matrix - Matrix reports are similar to summary rep s o ports but are much more pow m werful and comp plex. This form allows yo to group an summarize data by both rows mat ou nd and colu umns. This fo ormat is part ticularly usefu for compar ul ring related t totals, especially if you have la amounts o data to sum y arge of mmarize and yo need to com ou mpare values in several differ rent fields, or you want to look at data by division an by nd product, a account rep, or sales region.

When saving a r W report one of the confusing a t aspects is provid access to the report. The are ding t ere a num mber of public r report folders into which you can save you report. How u ur wever, if you w to want restrict access to the report you do not configure this at the repo level. Instea you must cr t ort ad, reate a new report folder a r and grant access to it for specific Publi Groups, Ro and Roles and ic oles Subord dinates. Only th specified users will have access to the fo hese u older and any re eports in it. You can schedule reports to run and have t results automatically ema Y the ailed salesforce e.com users. T informatio a users sees in a report is only the data to which they have The on s y a access. This in ncludes records they own, re s ecords to which they have re or h ead r read/write access, records th have been shared with th hat hem, records o owned b or shared with users in r by w roles below th hem in the hierarchy, and re ecords f which they have Read permissions Therefore, reports may d for y s. r display d differently base upon the us running the report. ed ser e Runni Dynamic Reports ing c Salesforce.com has a little un S m ndocumented a unsupport feature tha allows you t run and ted at to 1 reports dynamically . Typically if you would lik to display t number of widgets sold by a ke the f d specifi account for a practice, yo would have to run the re ic ou e eport and choo these selec ose ctions from the individual p t picklists. To run these re T eports dynami ically you simp add a custo link or butt to the acco ply om ton ounts detail page that pass these varia ses ables to the re eport using me erge fields or other coded v o values. Create the report in the format th you want b leave the v e n hat but values for the criteria blank You k. then append the var a riables to the URL where pv is the first p U v0 parameter, pv1 is the secon and 1 nd so on. The code for the URL for your custom lin or button w y nk would look like e:
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 URL passe to run the report would th look like: T ed r hen https://na2.salesf h sforce.com/000000123AJUY34 4?pv0=0000000456ABCBD& &pv1=EMEA&pv2 =LAPTOP =

report ts-dynamic Salesforce Handb book


Cu ustom Report Types t Salesforce.c com come wit a large set of report types pre-defined. The first step in creating th T n any report is cho oosing a repor type. But wh if you wou like to prov your users with the rt hat uld vide s ability to report on data bas upon you customizations or from different aspects? For t sed ur ins stance, if your Org contain a shipment custom obje you may want users to run and r ns t ect, w o customize repor based on accounts with open oppor rts h rtunities and shipments tha include s at specific fields fro all three ob om bjects. Salesforce.c com enables you to create cu y ustom report t types that allow you to conn up to w nect 1 fou related obje in order to expand the scope of you Orgs repor ur ects t e ur rting ability . O Once you hav defined a cu ve ustom report type, users can create custom reports from it. You can create new t n m m custom report ty ypes by clicking Setup -> App Setup -> Create -> Report Types. g

F Figure 2 - 16. De efining the objec relationship f a custom rep type. ct for port

When creat a new cus ting stom report typ the objects available for you to choose from are pe, s e based on the p primary object relationship to other o ts ps objects. For ex xample, if you choose acc counts as the primary object, then you can only ch e u hoose standar and custom objects rd m ass sociated with a accounts (e.g., contacts, opp portunities). Th also applies to subsequen objects his nt added to the c custom report type. So, if account is s t f selected as th primary ob he bject and op pportunity is se elected as the secondary obje then you c only select objects associ s ect, can t iated with op pportunities as the third object for your cus stom report typ pe. Da ashboards A dashboa is a collect ard tion of compo onents (report Visualforce pages and Sts, -Controls) tha graphically displays a snapshot of k metrics an performan indicators2. Report at key nd nce components can display as ga n auges, tables, horizontal and vertical bar charts, line c d charts, pie
1 2

cu ustom-report-typ pes dashboards Jeff Do ouglas & Wes No olte 85

charts, donut charts and funnel ch , harts. You can select up to 2 different co n 20 omponents for each r dashbo but only s oard summary and matrix report f m formats can be used with the e em. As with report folders con A ts, ntrol user access to the das shboards how wever the Run nning User determines acc cess to the actu data. The r ual running user fo the compon can be: or nent A named user The dashboard run using the se d d ns ecurity settings of a single, n s named user. All users with acc cess to the da ashboard see t same data, regardless of their the , f own pers sonal security settings. Use this approach for sharing th big pictur of he re support c cases across a division, or motivating a sales team by showing peer m g performan within a te nce eam. The curr rent user These dynamic d T dashboards run using the secu urity settings o the of user curre ently viewing the dashboard Each user sees the dashboard accordi to d. ing their own security and access settings. Use this app n proach to shar one commo set re on of dashbo componen to users wi different le oard nts ith evels of access.

Salesforce.com recently intro S m oduced the Da ashboard Build 1, a drag-and der d-drop interfac for ce creatin and modify ng fying dashboar rds. The new builder is a dramatic improvement ove the er previo multi-scree approach an allows you to drag-and-dr componen and datasources; ous en nd rop nts config gure, rename a move com and mponents; edit component ti itles, chart typ and setting and pes gs config dashboard properties. gure d

Figure 2 - 17. Drag-and-d drop Dashboard Builder. d

Y Your Org can have up to three dynam dashboard which mu be n o mic ds ust r refreshed man nually. You can schedule re nt efreshes for dynamic dashb d boards s ensure that you plan accor so rdingly.

dashbo oard-builder Salesforce Handb book


An nalytic Snapsh hots Reporting i a static func is ction by its ver nature. Whe you view a report it repre ry en esents the current state of y your data in sa alesforce.com. If the underlyi report data changes, a m ing a minute or a day after the rep for instanc the existing report does n reflect the changes. By creating y port ce, g not ese y analytic snapshots you can report on trendin and changin data in your Org1. For inst ng ng tance, you ma set up an a ay analytic snapsh to track d hot daily inventory levels in you warehouse a allow y ur and use to report o it. ers on You can cr reate new analy snapshots by clicking Se ytic etup -> Adm minstrative Setup e -> Data Mana > agement -> Analytic Snapshots. To create a new analytic snapshot > you essentially cr reate a new re eport and then pipe the outp of the repo on a schedu basis put ort uled to a custom obje that you de ect efine. Users ca then use the data in this custom object to create an c t rep ports or constr dashboard ruct ds. Triggers an workflows on a target object are not ex nd xecuted as a re esult of an analytic snapshot run. In fact, you are not allowed to use an obje with a n e ect trigger as the target of a snapshot. Add a trigger to a target obje results ding t ect in the snap pshot run failin ng.

Overriding L Link, Tabs and Labels a

Salesforce.c com allows yo to rename ta objects an fields to ma the UI mo closely ou abs, nd ake ore ref flect your co ompanys ter rminology. Fo instance, you can re or ename Accounts to O Organizations if your co ompany opera ates with thi terminolog Click Set is gy. tup -> Cu ustomize -> Tabs and Labels - Rename T > d -> Tabs and Labels to m L make these Or rg-wide change es.

Fig gure 2 - 18. Rena aming standard f field labels.

Salesforce.c also provid a way to ov com des verride the beh havior of standa buttons and links for ard d eac object2. So instead of displaying the sta ch andard details page when you click on a li for an ink op pportunitys det tails, you can ha each oppor ave rtunity display i a customized Visualforce page. in d Overrides a global thro are oughout the sa alesforce.com UI as they co ontrol the actio behind on the each button and link. For example, if y override t View link on opportuni e r you the ities, your rep placement action takes effect wherever tha action is avai t at ilable:
1 2

an nalytic-shapshots ov verriding-links-bu uttons Jeff Do ouglas & Wes No olte 87

The opport tunities tab ho page ome Any opportunities related lists on other objects such as accounts d r Any link re epresenting the record display in the UI e yed Any browser bookmarks for this salesfo force.com page e

To use a Visualforce page ins T stead of the sta andard details page, click the Override b e button for the View link. In the Override Properties se e n ection, select t Visualforce Page radio b the e button to disp the list of available Vis play f sualforce pages for the opportunity objec Only Visua ct. alforce pages that implemen the opportun standard c nt nity controller will be displayed in this list. n

Figure 2 - 19. Overriding the standard view page with a Visualforce page. e d h p

The standard b T buttons and lin section wil now show th your Visua nks ll hat alforce page is being used in nstead of the default salesfo ore.com details page. You ca click the Re s an eset link to r revert back to the default d o details page.

Fi igure 2 - 20. Stan ndard Buttons and Links sectio with the overr a on ridden display Visualforce page V e.


Salesforce Handb book

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 users 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 recipients 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 Organizations 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


page la ayout or field-level security settings while administrators can import in any of the listed s s nto fields regardless of security settings. r Salesforce.com offers a clien application for inserting, updating, upserting, deleting and S m nt extract ting records c called the Data Loader. The Data Loader can move da into and o of a e r ata out virtual any type of object using CSV files. To prevent dupl lly f o licate records from being cr reated during the import p g process, you can use an ID from an ex c D xternal system (referred to as an extern ID) as a unique key. An external ID is a custom field that has the Externa ID nal A D al attribu checked. W ute When you sele the upsert option during the import process, the im ect g p mport wizard and Data L d Loader will detect existing r records in sal lesforce.com that have the same t extern ID and upse the record matching reco instead of creating a new one. nal ert ords f w M Make sure tha the user performing the import has the Modify All at e D Data permissi checked on their profile for the objects being import so ion n s ted t any sharin rule checks a skipped. that ng are You can dow Y wnload the Windows versio of the D W on Data Loader from Setup -> f p Admin nistration Setup -> Data Manag gement -> D Data Loader while the Ma OS r ac X ver rsion, LexiLoa ader, is availab at http://w ble www.pocketsoap.com. Both ver rsions of the Data Loader use the same Web Services API so the on difference is the client in e s nly nterface.

Fig gure 2 - 21. The OS X version of the Data Loade extracting data. O f er


Salesforce Handb book

The Data L Loader can als run unatten so nded from the command lin (aka Comm e ne mand Line Int terpreter) in s scenarios where human interaction is no required. The CLI uses the same ot T en ngine as the G GUI interface thus supports the same operations for inserting, updating, e f up pserting, deletin and exporti data. ng ing The Data Loader has bui in support f the Bulk API providing a fast and L ilt for A efficient way to upload extremely larg sets of data You can als import w ge a. so attachment and documen into salesfo t nts orce.com using the Data Loa g ader. A number of third-party applications a available on the AppExch are n hange (mostly for a fee) for loading, upda r ating, dedupin and cleansin data. Deman ng ng ndTools from CRMfusion is a widely m po opular favorite among admin nistrators. How wever, if price is an issue, you can also b e y build your ow data loadin application using any cl wn ng n lient-side lang guage that is supported by the Web s Services API. For loading extremely large sets of data, salesforce.com offers a RE m EST-based Bu API with m ulk management an monitoring features built into the salesf nd force.com UI.

Deploying Co to Prod ode duction

Salesforce.c com requires you to write your Apex co in a sandb or develo ode box oper Org, pro ovide unit tes to ensure your code performs as in sts ntended and then deploy it to your t t pro oduction Org. Even though it is possibl to make co h le onfiguration ch hanges directly in your y pro oduction Org, the best pract is to do th is a sandbo or develope Org and the test the , tice his ox er en im mpact. There ar a number of ways that y can deploy code and co re o you y onfiguration ch hanges to your production Org. Fo orce.com IDE E The Force.com IDE is a free, salesforc ce.com supported Eclipse plu ug-in that facil litates and sim mplifies develo opment on the Force.com p e platform. The F Force.com ID has a built in wizard DE for deploying co resources and other conf r ode, a figuration chan to produc nges ction. Fo orce.com Mig gration Tool This migrat tion tool is a command line Apache Ant tool for scrip e, t pting deploym ments. The pro ocess of using t Force.com Migration Too is more comp that deplo the ol plex oying with the F Force.com ID and may req DE quire some Java experience. T tool is well suited for repe a This l etitive deploym ments such as testing deploym plans or in ment nstalling code i production Orgs during setup. into n s The Force e.com IDE an the Force.c nd com Migration Tool will be covered n e fully in late chapters. er

Jeff Do ouglas & Wes No olte


Unma anaged Packa ages Unmanaged pa U ackages are th old schoo way to de he ol eploy code an component An nd ts. unman naged package contains comp ponents such a code, object reports, or email template for as ts, es, instanc which can b uploaded to share with ot ce, be o thers privately or publicly. Chang Sets ge Change sets ar the newest method for d C re deploying cod and components and pro de ovides some enhanced fun nctionality1. Ch hanges sets use packages in the backgrou but provid the e und de ability to move code from not onl sandbox to production, b from sandb to sandbo and e ly but box ox produc ction to sandb box. While deploym W ment with the Force.com Mi F igration Tool a the Force. and .com IDE are tasks typical performed by developers, change sets a focused m lly are more for admin nistrators. For larger compa anies this allo ows multiple developers t create cha to ange set that are deploye by t ed administrators who may have more intimat knowledge of their en o te ntire salesforce e.com landscape. Before deployi change set administrato must setup trusted deplo B ing ts ors p oyment connec ctions betwee their Orgs Deployment connections cant be crea en s. t ated between arbitrary Org By gs. default a deploymen connection is created betw t nt ween all Orgs affiliated with a production Org h n (e.g., sandboxes). Co s onnections are created betw e ween each sand dbox and betw ween each san ndbox and pr roduction Org A deployme connection alone doesn enable chan sets to be sent g. ent n nt nge e betwee Orgs. Each Org must be authorized to send and rece change se This added level en h o eive ets. d of secu urity enforces code promotio paths and k on keeps an Orgs metadata from being overw s m written by mis stake.

Figu 2 - 22. Chan Set showing outbound chan ure nge nges to productio on.

When sending changes from your curren Org to another Org, you create an out W g m nt u tbound change set. The proc to create and deploy a c e cess a change set is re elatively straigh htforward. You first u create a new change set and then walk through a series of screens adding the componen that e t nt

change e-sets Salesforce Handb book


you want to dep ploy. Once you Upload the change set, th receiving Or sees it as an inbound u he rg n change set and c accept and deploy it with a few clicks. can h A change set is deployed as a single tran nsaction. If the deployment fails for any re eason, the en ntire change se is rolled bac After a dep et ck. ployment completes successfully, all chang in the ges set are committe to your Org and the modi t ed g ifications cannot be rolled ba ack. Unfortunat tely, as of W Winter 11, cha ange sets do not support d deploying componen with respec to profile s nts ct security. There efore, new com mponents will not automatically be available to n non-SysAdmin users. You wi need to ill edit each profile individ p dually and adju the field-le security an access ust evel nd levels as required for each component deployed. h

St toring Appli ication Met tadata

Salesforce.c com recently introduced Cu i ustom Settings in Winter 10, which allow you to s ws sto custom da sets and associate them on an Org-w ore ata a m wide, profile or user basis1. Custom o Settings are essentially custom objects tha are exposed in the application cache and are m at e acc cessible via th own API. They are ma heir . anaged by clic cking Setup -> App Se etup ->
De evelop -> C Custom Sett tings.

You can ce ertainly build your own cust y tom objects to store settings (many peopl do) but o s le usi custom settings is much quicker (agai they are sto ing h in ored in the app plication cache and do e) no count again SOQL limi when fetch ot nst its hed. You can also use custo settings in formula om n fie elds, validation rules, Apex co and the W Services AP ode Web PI. List Custom Se ettings List custom settings allow you to stor Org-wide st m re tatic data that is frequently used. For ins stance, salesfo orce.com does not have ISO country co odes baked into the platfor Many rm. companies main ntain this list of countries an their ISO c o nd codes in a sepa arate custom o object. So wh henever they n need this data they have to query this c a o custom object which bring with it t, gs additional overh head pertaining to the SOQL limits. Using a list custom setting comp g L g m panies can sto these code and use them virtually any ore es m ywhere needed and retrieve them quickly from the d application cache e. When you create a new custom sett w ting the platfo orm creates a custom obje in the ect background for you. You then add addition fields to the custom setti in the sam manner n nal ing me tha you do for custom object (you are lim at ts mited to checkb box, currency, date, date/tim email, , me, nu umber, percent phone, text text area an URL fields After youv set up you custom t, t, nd s). ve ur set ttings and added your fields, you can selec the Manage link on the Custom Setting page to , ct e C gs add, edit and del records. lete List custom settings hav their own instance meth m ve hods to allow easy access t cached to val lues.
// retur rns all lis hierarch values st hy Map mapC Codes = ISO O_Country__ _c.getAll( );

cu ustom-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);

Hiera archy Custom Settings m Hierarchy custo settings all you to per H om low rsonalize your applications for different pr f rofiles and/or users. The in nterface has baked-in logic t that drills dow into the Or profile, and user wn rg, d ( the rns owest value in the level (based upon t current user) and retur the most specific or lo hierarc chy. Hierarchy cust H tom settings are extremely useful for t y those one off occasions For o s. instanc suppose yo want to auth ce, ou horize your sa teams to b able to offer a specific discount ales be r to cust tomers. You m might set up an Org-wide cu n ustom setting o a 1% discou that everyo is of unt one author rized to offer. Now, of cour you have a set of high-p rse, producing sale people that are in es their own profile an are able to offer a 5% d o nd discount. How wever (and here is the one off), e there is that one sale person in th same profil that has lobb the VP of Sales to be a to i es hat le bied able offer a 15% discou unt. With hier rarchy custom settings you can accomm m u modate all of these scenar rios. After youve s up your custom setting and added your fields, you can selec the A set c gs ct Manag link on the custom settin page to ad edit and d ge e ngs dd, delete values fo the entire O a or Org, specifi profile or ind ic dividual users.

Figure 2 - 2 Hierarchy se 23. eting with 1% O discount and settings for the Standard Org d e Emp ployees profile a a specific us and ser.

Developers ca programma D an atically access hierarchy cu s ustom setting based upon the gs n runnin user and re ng eturn their mo appropriate value (Org-w ost e wide, profile or user) in formula o fields, validation rule Apex code and the Force.com Web Ser es, rvices. Y You can only access hierarchy custom settings in formula field and y m d v validation rules List custom settings are so s. omewhat limite and not ava ed ailable f formulas or validation rul for r les. The generic syn for using a hierarchy cu T ntax ustom setting in a formula fie is: n eld
{!$Setup.Cu ustomSettin ngName__c.C CustomFieldName__c}


Salesforce Handb book

Figure 2 - 24. Using a hierarch custom settin in a validatio rule. U hy ng on

Monitoring y M your Org

Salesforce.c com provides some level of insight int the platform with various debug to m scr reens and job q queues. De ebug Logs For applica ation developm ment, the debu log is your b source of information to uncover ug best o wh is actually t hat taking place on the platform. The debug lo records data n og abase operations, debug sta atements, warn nings, system processes, and errors that occur when exe p d ecuting a trans saction or wh running u tests. The platform gen hile unit e nerates a debu log every time a user e ug executes a tra ansaction that is included in the filter criteria. You can specify to gene erate debug log for any gs use on the platf er form to help tr rack down issu with particu user or pro ues ular ocesses. Em Logs mail Email logs provide access to all emails sent and recei ived through the platform fo the last t or 30 days. The log files contains both to and f g s from addresse date and tim sent or rece es, me eived, the sal lesforce.com u and any as user ssociated error information. Lo ogin History This log displays the last 20 user logins (successful an failed) via browsers, SAM APIs, s nd b ML, Re emote Access Clients and pa artner product You can als download the login histor for the ts. so t ry las six months. st Vi Setup Aud Trail iew dit The setup audit trail trac recent setu changes th administrat cks up hat tors have mad to your de Or The last 20 changes are displayed by de rg. 0 d efault but you can download a CSV files c d containing all changes for the last six months. The lo tracks a w m og wide range of changes includ ding 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.


Salesforce Handbook

Bu Data Load Jobs ulk d This page d displays the sta of current and recent bu data load jo created by the Data atus t ulk obs y Lo oader and othe Bulk API cli application The page a displays yo Orgs curr er ient ns. also our rent batch im mport quota for the current 24-hour period. r

Go oogle Integ gration

Its no surp prise that sales sforce.com and Google have a close relati d e ionship given t their long his story of compl limentary prod offerings and the fact th both domi duct hat inate the cloud space. A d nu umber of Goo ogle services are baked int the Force.c to com platform allowing you to take m u 1 adv vantage of the without le em eaving the sale esforce.com en nvironment . Administrators typically A s need to simply activate these fe eatures to get s started using th hem. These serv vices are design for busine users and require a Goo Apps ned ess ogle account. The Google Ap domain you set up in salesforce.com must be T pps s m the domai you registe in ered with Goo ogle for your company rat r ther than consumer account (i.e., G a Gmail.com). Ad Google Do to Salesforce.com dd ocs When activ vated, the Add Google Docs to Salesforce. .com service al llows you to co ollaborate and share Googl docs with an user in your Org; use Goo Docs & Attachments as a related le ny r ogle A s list on any salesf t force.com reco to create, e ord edit, or view G Google docs an easily assoc nd ciate them to a record; use the Add Goo Doc to Sa ogle alesforce.com browser butt to associat Google ton te do with salesf ocs force.com reco ords even whe not current working in the salesforce en tly e.com UI; cen ntralize the ad dministration of Google doc by allowing salesforce.com Customer P o cs m, Portal and Pa artner Portal us to add Go sers oogle docs to S Salesforce CRM content. M Go oogle Docs T Tab When activ vated, the Goo Docs tab a ogle allows you to a access all of yo Google do from a our ocs sim mple docs home page with hout leaving t salesforce. the .com UI. The home page not only e dis splays all docu uments, spread dsheets and pr resentations th you have created by all docs that hat c hav been share with you. You can even create a Go ve ed n oogle doc fro within the tab and om e ass sociate it to an record in sal ny lesforce.com w a few simp clicks. with ple Gm to Salesf mail force.com Gmail to Salesforce.com allows you to seamlessly rou emails sen from the Gm UI to ute nt mail rec cords in salesf force.com. On set up, the Force.com p nce e platform will generate a uniq email g que address for your account. Simp add this em address to the bcc field of your outgoi Gmail r ply mail o ing me essage and it w be routed to salesforce.com and crea will d ated as an acti ivity on match leads, hed contacts, opport tunities, and ot ther records th support act hat tivity history. Gmail to Salesf G force.com wo for chats a well. orks as

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.


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 users 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


Programmatic Development Tools & Strategies

n previous chapters youve 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. Wouldnt that be great? Salesforce.coms Platform as a Service (PaaS), also known as Force.com, does exactly this and thats 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 youll learn more about the tools and strategies required to build, test and deploy applications on Force.com. Not only that but well 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. Thats 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 Softwa Developmen Topology . are nt

Devel loping in the Clouds Force.com use a similar set but we fin that instead of having ou environmen sit F es tup nd d ur nts within the usual hardware infrastru n ucture they are now cloud-b bound. In figu 3 - 2 we see that ure develo opers still create code locally but something to note is that code isn compiled lo y, nt ocally. Instead it is deploye (in real-time by default) t developer e d ed to environments, which compi the ile source e-code and form our develop m pment runtime environments e s. D Developers ca also create and edit appl an lications direct in their bro tly owser t thereby leap-fr rogging the local developme step, but this is generall not ent t ly a advised for larg applications and/or collab ge s borative develo opment. Thankfully you still have the option of co T u e ommitting cod to your fav de vorite VCS and it is d genera advised. A packaging st is not req ally tep quired with the Force.com platform as w can e p we deploy directly into a developer and/or produ y any uction environm ment.


Salesforce Handb book

Figu 3 - 2. Force.c ure com Developme Topology ent

In figure 3-3 weve no oted an altern native setup w with a build manager han ndling the deployments dire ectly from the VCS reposito Using build managers ca be a neat pr ory. d an ractice for a number of reas n sons including predictable de g eployment rhy ythms, code qu uality checks, a automated tes sting and build d/deployment history.

Figure 3 - 3. Alternative Force.com Devel lopment Topolo ogy

Jeff Dou uglas & Wes Nol lte


From what we F eve seen, dev velopment ma anagers usuall employ a combination o the ly c of metho shown in figures 3 - 2 and 3 - 3 wi developers deploying di ods ith s irectly to deve eloper enviro onments and us build man sing nagers to deplo code to thei production environment. oy ir e A youll see la As ater, Force.com projects can be deployed using Apache Ant. m n e T means tha server applications such a Hudson (http This at as p://hudson-ci.org can rg) b used to man be nage and deplo code. oy The Im mportance of Metadata f In previous cha I apters you saw that metadat plays a very important role in salesforce w ta e.com. It desc cribes the structure of objec and their fie cts elds, as well as the page layo associated with s outs d them. In fact, metad describes many more st data tructures in Fo orce.com but what you migh ask w ht is, Why use metada at all? ata Metadata is a s M simple lightwei ight language ( (based on XM for describ the structu of ML) bing ure salesfo orce.com and F Force.com dev velopment art tifacts. Later o youll see th Force.com code on hat m can be organized int projects, wh are essent e to hich tially groupings of metadata files. Instead o the of traditio onal developm ment approach of code-com h mpile-package-d deploy, with Force.com you only F u need to code. The m t magic here is that the metad is zipped a transferred to the Force t data and e.com servers (much faster than uploadin compiled co where it i unzipped and compiled on your s r ng ode) is n behalf Not only is t super fast, but your chan f. this , nges are imme ediately availab through any web ble y browser, and theres no downtime at all!

The Right Tool for the Right Job R

Now that you equipped with an over N ure rview of how your cloud-b w based develop pment networ might be or rk rganized, it is im mportant that you learn: What Force e.com develop tools exist per When it is a appropriate to use specific to o ools How to use these tools e

In this section we will disc I n cuss everythin you need to create, tes and deploy your ng st Force.com code wh hilst being min ndful of the a above points. We will also touch on de esktop ations or areas of Force.com that youll n s m need when anal lyzing and mo onitoring your code, applica as well as the various support optio available to you. l s ons C Certain tools overlap severa developmen tasks, and some develop al nt pment t tasks overlap each other. Its for this reaso that the firs two points a so e s on st are i important whe discussing d en development to oolsets. Devel loping Applic cations on the Force.com P e Platform Creating code i any modern language is us C in n sually done thr rough an Integ grated Develop pment Enviro onment (IDE) that offers a number of a ) advantages ove coding thro er ough a simple texte
104 Salesforce Handb book

editor or somet thing equally archaic. By th end of th section you know whi IDEs he his ull ich Fo orce.com offers and when to use each of th hem. Fo orce.com App Builder Too p ols Salesforce.c com has created one of the best browser-based develop pment environ nments in the world and it delivers most, if not all, of t core functi e , the ionality youd expect from a desktopbased IDE. The are two wa to access t functionali each of which presents a slightly ere ays the ity, w dif fferent experie ence. The first w involves cli way icking Setup -> Develop as a logged in user. From there you p i hav access to ea Force.com area of develo ve ach m opment, name ely:
Apex Classes Apex Triggers Components Pages

S-Controls are now dep precated and a the functio all onality they pr rovided is now availab through Vi ble isualforce page es.

on ou y well Each sectio presents yo with a list of code units of that type in your Org, as w as the op ption to edit th list items, an - in the case of Apex Classes, Components, and Page - create he nd e es new code units. We wont go into the langu uage specifics right now (we cover each language ell h and coding com mponent late but essent er) tially touch o key areas of the dev on s velopment en nvironment to d demonstrate th strengths. heir In figure 3 4 you can se the list of A ee Apex classes th are created when you sign up for a hat n new Developer Edition (DE) Org1. Notice the link label Edit on the left and th button led t he lab New at the top of the list. bel .

Figure 3 - 4. The initial list of Apex Classes i a DE Organiz T f in zation

Developer-edition D n-signup Jeff Dou uglas & Wes Nol lte 105

If you click the New button you will be presented with a screen simila to the one shown I e y ar in figu 3 5. Weve taken the liberty of dec ure claring a class and a single member meth in m hod order to demonstrat syntax highlighting. It has other feature such as mar te es rking syntax e errors, search and replace, a tabbed ind h and dentation (not such a simple feat in a brow window). t e wser Youll also not a button la Y tice abeled Versi ion Setting . You will only need to m gs o modify the va alues on this tab if your class needs to maintain spe c ecific behavior not support in r ted subseq quent releases.

Figur 3 - 5. Creating an Apex Class with Force.com App Builder Tools re g m T

Y might hav already not You ve ticed the two save buttons, which might seem c confusing. The difference is that the Save button will sa any change and e e ave es d drop you back at the list-vi page, whil the Quick Save button will k iew le n s save your cod and keep y on the sam page. For keyboard sho de you me r ortcut junkies, pressin Ctrl/Cmd- will also qu save. ng -S uick Coding Apex C C Classes and Tr riggers in this e environment o offers very sim experience but milar es there are some surpr a rises when dev veloping code i the Pages a Components sections. in and Its in these sec I ctions that you can create an modify the pages (or pag components that u nd ge s) your users interact w u with, and here the browser ed t ditor offers som bonus feat me tures. In figure 3 6 e weve started coding by typing an open angle b g n bracket and hav been presented with a po ve op-up ion ns. list of code completi suggestion


Salesforce Handb book

Fig gure 3 - 6. Creati a Visualforce page with For ing rce.com App Bu uilder Tools

This auto-c completion fea ature is superb for beginners and is compr s rehensive for th code hese un types. In add nit dition to this youll notice an extra button labeled Compo y n onent Reference at the top of the p e page which lin through to a library doc nks o cumenting the language com e mponents alo with worki examples. ong ing The second way to acces the Force.co App Builde Tools devel d ss om er lopment enviro onment is by enabling Dev y velopment Mode; this can be found by clicking Setu -> My Pe M n up ersonal In nformation -> Perso onal Information, cl licking Edit and then checking t De evelopment Mode as show in figure 3 7. wn

Fi igure 3 - 7. Enab bling Developm ment Mode

This featur allows you to code and v re view the comp piled results within the same browser w e window. It offer all the featur we mention previously but adds a rea rs res ned y al-time view of the code f youre amending or creating. In figure 3 8 you can see that the dev g e velopment env vironment
Jeff Dou uglas & Wes Nol lte 107

(also known as the Development Mode Footer is unobtrusiv and more than this it ha the k r) ve, as compo onent referenc handy as we as offering t expected assistance when syntax is inco ce ell the n orrect or if particular depen p ndencies are missing. For all these reasons we proclaim this to be Ki of m l s ing Beginn Development Tools. ner

Figure 3 - 8. The Development Mode Footer

From our commentary its qu obvious th the Develo F uite hat opment Mode Footer is super for F rb beginn ners, but some would conte that its al just as goo for quick changes. We w e end lso od c would disagre arguing tha a good dev ee at velopment inf frastructure loses a lot of value without good v develo opment practic We would consider some of these to be: ces. e All changes must be teste and this usu s ed, ually involves several test-ph hases. All changes should be committed to a V (at very la s VCS atest) prior to deployment. d All changes should be val s lidated and acc cepted as corre by a colleag ect gue. All testing should be valid dated and acce epted as correc by a colleagu ct ue.

These principl are especially important if youre wo T les orking in deve elopment team as ms this in ncreases the p potential for overriding v valid code or working with the wrong code h version. I is easy to ov It verwrite code in these brow wser-based env vironments and this h the potent to cost ho has tial ours or even d days of work. Bugs can oft be ten i introduced wh making quick change through th browser as little hen es he s t thought goes in their imple nto ementation.


Salesforce Handb book

Fo orce.com IDE E Developers will be pleas to learn th they can us the Eclipse IDE to code with the s sed hat se e e help of the For rce.com IDE plug-in1. The Force.com ID is a defini p DE itive interface for rapid dev velopment, tes sting and depl loyment of cod on the Force.com platfor It also pro de rm. ovides the ability to explore your salesfor e rce.com schem as well as t ma, tools to execu database qu ute ueries and execute short co scripts on the fly. The th ode t heme of this se ection is How to create cod and as w de suc well only e ch explore that fea ature for now. Once the I IDE is installed you will hav a new devel ve lopment persp pective available to you. Op this up by clicking Wind pen dow -> Open Perspecti n ive -> Othe -> Forc er ce.com at wh point you be presente with a page detailing info hich ull ed e ormation and other resource for the es Fo orce.com IDE. .

Figure 3 - 9. The Force.com IDE m

To get star rted coding, ri ight-click in th Package E he Explorer wind dow and click New -> Fo orce.com Pr roject. If youve signed up for a DE (or any) Or youll have a set of y E rg e cre edentials that n need to be ent tered in this wi indow. If you havent signed up yet, click the Sign d Up Now! link to the right of the Environm p o t ment drop-dow box. wn Many peop get confuse as theyre n sure what the difference b ple ed, not t between a Security Token and a P T Password is. I Force.com jargon a securit token is In ty a randomly generated alph y hanumeric strin that adds strength to your c ng credentials in conjunct with your password. If yo dont have a security toke you can tion ou en get a new one emailed t you by logg to ging into your target Org an clicking nd
Setup -> My Person > nal Inform mation -> Reset My Se R ecurity

fo orce.com-ide-dow wnload Jeff Dou uglas & Wes Nol lte 109

T Token -> Re eset Securi ity Token. Its also impo ortant to note t if that

y change yo password, a new securit token is issu invalidatin the you our ty ued ng p previous one. I youre havin trouble log If ng gging in and yo oure certain that your usern t name, p password and security token are correct t n then the likely culprit is tha the y at w wrong environ nment type has been selected Most develo s d. opers will only work w Producti with ion/Develope Edition or Sandbox Orgs, so trying each er O g o these shoul solve the pr of ld roblem. As an additional ha n andy tip, if yo use ou h http://logi in.salesfor rce.com to login then the first opt o n tion is c correct, where a login URL of htt eas tp://test.s salesforce.com m means that you developing in a sandbox ure g x. Clicking the Ne button in the wizard pres C ext t sents a page sim to that in figure 3 10. Here milar n . we enc counter metada once more, selecting those components youd like to pull into your pr ata e roject. You ca select a defa set of comp an ault ponents, custom the selection or choose none. mize n

Figure 3 - 10. Selecting initial project co ontents 110 Salesforce Handb book

A lot of w what you see in this windo might be unfamiliar at this point (e Apex ow t e.g. Co omponent, Ap Trigger, St pex tatic Resource but you can revisit this page at any tim during e) n p me dev velopment and customize which metadat components youd like to work with in Eclipse. w ta s o n Th important c he concept here is that Eclipse wants to do e ownload a sub of your F bset Force.com application in t form of metadata into a local pro the o oject, thereby setting up a two-way sub bscription to a application cha anges. The default option is fine for now so yo can click Fi t e ou inish to com mplete the wiza ard. Looking at figure 3 11 youll see that weve expanded our projec and opened the class t ct d tha we created t at through the Fo orce.com App Builder Tools IDE.

Figure 3 - 11. V Viewing an Apex class x

On the left the project is laid out in a neat folder s t, i structure, grou uping code uni types in it the particular f eir folders. On the right we hav the code edi where you notice that the code e ve itor ull t lay yout and highli ighting is cons sistent with wh we saw bef hat fore. At the bo ottom of the r right pane you can flip bet tween the So ource view where you ad actual code and the M dd e Metadata vie that shows how Force.com describes th class, as dem ew his monstrated in listing 3 1. Listing 3 - 1. Example of Apex Class Metadata o s
<?xml ve ersion=1.0 encoding 0 g=UTF-8?> > <ApexCla ass xmlns= http://soa ap.sforce.c com/2006/04 4/metadata> <apiVer rsion>20.0</apiVersi ion> <status s>Active</status> </ApexCl lass>

To create new code in the Force.com IDE right-click on any folder or file in your e Fo orce.com proje and highlig New. The available optio are shown in figure 3 12 and as ect ght ons n you can see the eres a mixtur of program re mmatic develop pment and de eclarative prog gramming ele ements. Feel free to experiment with creating declarative ele ements such a custom as objects as this will give you feel for how theyre represented u e r under the hood. Beyo experimen though, wed advise steerin clear of editing these ond nt d ng files by hand as its erro prone, and can be tough to debug if s or something goes wrong g.

Jeff Dou uglas & Wes Nol lte


This chapter w only cover the programm T will matic elements and since the creation wizar for rd each element is a litt different, th will be discussed in later sections. tle hese r

Figure 3 - 12. Force.co IDE New Menu om

Earlier we high E hlighted how integral metad data is to the platform and how a Force d e.com project is a collection of metadata files. To expan on this, eac time you create or save a file in n nd ch the Fo orce.com IDE the metadata representatio of that file is zip-archiv and sent t the E a on e ved to Force.com servers fo compilation The result o the compilat for n. of tion is then ret turned to your IDE r to let you know whe y ether it was su uccessful or wh hether there w problems encountered. A of were All this is achieved at br reak-neck spee via the Me eds etadata API, wh will be di hich iscussed at leng in gth a later chapter. T process is similar to w This what is usually termed deplo oyment, althou in ugh t Force.com programming paradigm th name is re the m g hat eserved for an nother p process. Deplo oyment in the Force.com sen of the wor will be disc nse rd cussed l later in this cha apter. After working w the Force A with e.com IDE for some time yo will realize that its much richer r ou t than th browser-ba he ased version of ffering code completion for Apex classes, system classe and r , es schem objects; ve ma erbose syntax and compila ation error m messages; quic code navig ck gation includi ing keyboard shortcuts (c courtesy of E Eclipse); bette code orga er anization and VCS
112 Salesforce Handb book

int tegration. Ther are also fea re atures that enab deploymen analysis and testing. It is for these ble nt, d rea asons that this IDE is the only true pro s oject developm ment tool avail lable to us. Lu uckily its excels in this role e. As you mo from a be ove eginner through to an interm gh mediate, and fi inally to a guru Force e.com develope youll use th Force.com IDE more, an in most er he I nd cases will stop using the browser-base IDE compl s e ed letely. Thats n to say not the Force. .com IDE is a tool for a advanced deve elopers, more that the browser-ba ased IDE is a b beginner-to-intermediate lev tool. vel If youd lik more detail there is an off ke ficial Force.com IDE article1, as well as a f m frequently 2 ask questions (FAQ) docum ked ment and the IDE release n notes3. After youve gotten your feet y we wed suggest checking them out. et t m An nonymous Blo ocks Anonymou blocks prov us vide a way to execute Apex code on the fly. The cod that is x e de executed in anon nymous blocks is not persist in the way that youve se in the IDE instead s ted een Es; it is lost when yo close the anonymous bl i ou lock. Because th execute im hey mmediately and create debug logs in their wake they are valuable d g e wh performin analysis, ex hen ng xecuting data fixes on the fly, experime enting with c chunks of fun nctionality, run nning batch jobs, or scheduli jobs. ing There are t three ways to access the anon a nymous block functionality namely: n System Log Console Force.c com IDE A Web Services API call

Strictly spe eaking the third method sit outside of Force.com an as such wi not be ts nd ill dis scussed here. In a nutsh the system log console is the brow hell m e wser-based me ethod used to execute o anonymous bloc and the Fo cks, orce.com IDE has a pane th delivers this functionality from the E hat s y desktop. Sy ystem Log Co onsole
Sy ystem Log lin 4. Figure 3 13 shows the System Log C nk e Console windo that pops up ow p.

To access the system lo console yo need to log into your Org and then click the og ou g O

fo orce.com-ide-doc cs fo orce.com-ide-faq 3 fo orce.com-ide-reln notes 4 sy ystem-log-console e-docs

1 2

Jeff Dou uglas & Wes Nol lte


Figur 3 - 13 System Log Console (P re Pilot)

Clicking in the input area in the top left c C e corner of the w window will po up an addi op itional window that allows you to enter the code you wish to run. I you click th Execute b w If he button and yo code runs successfully ea of the windowpanes will populate with a different ty of our ach l h ype inform mation concern your script execution. ning Logs - A line will appe for each ap ear pplication transaction execut Clicking o any ted. on of these w populate th other panes with informat will he s tion about that transaction. Stack - A top-down na avigable tree of items e.g. DM operations, trigger invoca f ML ations or metho calls, as they are called in the process o executing yo code. The pane od y n of our e below is t back trace, or bottom-up view, of the s the p same tree. Executio Log - This is similar to th old bare-bon debug log and system co on he nes onsole output, b with some important en but nhancements. O Options in th pane allow for a his number o filtering opti of ions making th output easily readable. he y Source - Displays the executed sourc code or met e ce tadata definitio of items us in ons sed the execu ution process. The pane is context sensitiv in that selec ve cting items in other panes filte the output. ers . Executed Units - A gr d ranular view of the resources consumed by individual pr y rocess items. Bu uttons at the bo ottom of the ta allow you to filter out unw ab o wanted inform mation. Limits - Shows the lim involved in your code ex mits n xecution (by na ame) as well as how s close you are to hitting them.
Salesforce Handb book


Besides bei used to run scripts as An ing n nonymous Blo ocks the System Log Console can also m e be used as a full fledge debugg tool. As shown later you can enable debugging on a per user ging u d basis; if youve d done this for your currently logged in use and keep th System Log Console y y er he g op during you developmen and testing, log entries wil populate the Logs pane. E pen ur nt ll e Each entry wil detail every t ll transactional event during yo application interactions. This is incredi useful e our n T ibly in testing either user-flows or the smallest application un Using this tool you can pinpoint r nit. s n elu usive bugs or e even just narro down ineffi ow iciencies within your applicat n tion. Fo orce.com IDE E The Force.com IDE pro ovides a cut d down version of the functio onality provid in the ded System Log Con nsole through the Execute A t Anonymous v view.

Figure 3 - 14. Execute A Anonymous in F Force.com IDE

In figure 3 14 weve ex xpanded this p pane and run t through the pr rocess of enter ring some Ap code and clicking Exec pex cute Anony ymous. The l labels and pro ocess here are a touch e dif fferent but the result is simila to that of th execution lo pane in the System Log Co e ar he og onsole. ltering function nality is availab through thi interface alth ble is hough the help for each p Similarly fil op ption isnt as ex xplicit as in the web interface. The choices a quite straigh forward and with you . are ht d bei able to set the verbosity (+ is more ve ing ( erbose while - is less) for each Log categ e gory. Ve ersion Contro ol Unless you a develope working in isolation then version cont is essential Even if ure er n trol l. you are the sole developer vers control sy sion ystems work as effective back s kups. Version co ontrol system are used to track changes in files assig s gning each su ubsequent change an increm mental version number e.g. the initial file version migh be 1, the fir change n ht rst wo ould then beco ome version 2. Typically th 2 hese systems p provide functio onality to avoi and/or id me conflicting changes, the erge g ereby allowing teams of developers to work on overlapping source k code. Additional these system record a his lly ms story of chang allowing co ges omparisons or reversion to a historical so ource code sta This has la ate. arge advantage over traditio backup sy es onal ystems as

Jeff Dou uglas & Wes Nol lte


the access is provid in real-time, usually with line-by-line c ded h comparison to ools, and allow the ws develo oper to step ba further than a single versi ack n ion. Force.com IDE The Force.com IDE provide a mechanism to compare a local and se T m es m erver-side versi of ion any fil although in reality this isn suitable as a full-blown V le, nt VCS. As an exa ample conside that er you ha two developers working on the same Apex class C ave g e ClassA. Each developer in h nitially has th same versio of the class in their loca project. The first develop then create the he on s al e per es metho doAction( ) in a sha od ( ared sandbox. Later the sec cond develope adds in a se er econd metho getBoolea od an( ) withou first fetchin the updated code from th server. Whe she ut ng d he en saves the class shell get an error in the IDE stati t n ing:
Conflict fo C ound while preparing to save ClassA.cl e g ls to server. Remot instance has been updated since last save or sync. Use the te e n t Synch hronize Per rspective to resolve the confl t lict. Right-clicking on the proble file and th selected F R em hen Force.com -> Synchro onise with Server bri ings up a dia alog box asking if youd l like to the Team Synchron T nizing perspe ective. Clicking Yes, a new view will appea with a little two-way red arrow indicatin the g v ar a ng

conflic file. Doub click the file to enter the cted ble e Text Compare mode, which will look sim to e h milar figure 3 - 15.

Figure 3 - 15. Text Comp pare in Force.co IDE om

The options re T elevant to this type of conf s flict are availab in the top ble p-right hand co orner, offerin to overwrit the highligh ng te hted local code with the so e, ource code on the server. In this n n situatio however yo want to merge the chan on oull m nges into one file, so select the doAction ) n( metho in the right p od pane and copy y-paste it into t left pane. S the Saving the chan youll notic the nge ce IDE doesnt yet kno the conflict has been reso d ow olved. Right-clic on the conf ck flicted file and select Apply Project t Server. The file is no saved and you can retur to the Force y to ow rn e.com perspe ective.


Salesforce Handb book

When you move from a perspective back to the Force.com pe any erspective the Force e.com Start Pa age is opened and given foc This page is useful d cus. e but this behavior isnt always desira b able. To prev vent this open Eclipse n preferences and click Force.com -> Start Page and deselect t
Display when Force e.com Persp pective is opened.

The Synch hronize with Server feature can be used fo incoming, outgoing and c or o conflicting changes, as well as any combin nation of all thr types. ree Su ubclipse There are a number of version contr server app rol plications on the market an in this t nd sec ction well dis scuss one of the best, name Subversion (SVN). If yo dont have an SVN t ely n ou e ser rver installed y can down you nload the softw for free f ware from http://su ubversion.apac che.org or you can use one of the on-dem mand SVN serv vices such as G Google Code. Subclipse i an SVN clie that can be installed as a plug-in for Eclipse (availa is ent able from htt tp://subclipse e.tigris.org) and which allows you Force.com proj to work wit an SVN serve 1. d ur ojects th er Working w Force.com and Subclipse usually includ with m e des:

Copyi ing your sour code to the SVN ser rce rver. The cop pying process is called com mmitting and the area where the code exist is called the repository. t ts Devel lopment team members w import th project co m will he ode and mark it as a k Force e.com project by right-clicki on the project and sele ing ecting Force. .com ->
Assi ign Force.c com Nature. .

Devel lopment prog gresses with e engineers reso olving conflict importing, merging, ts, branc ching, and tagg code. ging The c commit histor allows code comparisons and the abil to revert to earlier ry e s lity versio of the sour code. ons rce

The topic of version co ontrol has tran nscended technical debate and for some has even a become philosop phical. The go part is that tools such as SVN and Subclipse are platformood S ind dependent so once youre ex xperienced the skills are tran e nsferrable. The bad news is that each e has several book detailing how to gain said e ks w experience. Although the details of forming a ver t rsion control strategy are be s eyond the scope of this book it is important to note that Su t s o ubversion doesnt work particularly well with lar files. If a development team is work y rge t king with metadata or source code files larger th 1000 lines you may have difficulty o han combining the changes. g The value of version con ntrol systems is worth the s steep learning curve. Signifi icant time n hen perly) because of the version history, an tools to ma ning nd anage and can be saved (wh used prop me erge source co ode. Additionally it is poss sible to have o other tools pl into a sou lug urce code

fo orce.com-ide-svn Jeff Dou uglas & Wes Nol lte 117

reposit tory offering valuable servi ices such as c checking code quality, feed e ding informatio to on project managemen suites or automatically b nt a building comm mitted change into produ es uction enviro onments. Deplo oying Applica ations on the Force.com Pl F latform Deployment on the Force.co platform c be summa D n om can arized as the process of mig p grating metadata from one Org to anothe Usually this feature woul be used wh promoting code er. ld hen g from a sandbox or D Org into a production en DE nvironment. The Metadata API facilitat deploymen using eith the Force T tes nt her e.com IDE o the or Force.com Migration tool. The Fo n orce.com IDE deployment p E process is the simpler of th two he using a deployment w wizard. The Force.com Migr ration Tool is a more advanc tool (at lea for ced ast those without Apach Ant experie w he ence) but its ow set of advan wn ntages. Assuming you reached the point where youve created and tested a collection of s A ve e d source code files, the next step to deplo them to a QA, UAT or production environment. Well f oy r demon nstrate the step necessary to achieve this w each tool. ps o with . S Salesforce.com wont allow y to deploy c m you changes to an Org unless the total e u test cover unit rage for all cod in that Org is 75% or ab de g bove. Not only does y t this ensure a high quality o deployed co of ode, it goes a long way tow wards m making sure th tenants on their platform dont write code that nega hat m c atively i impacts their neighbors. n Force.com IDE In the IDE sele the files yo wish to depl (hold CTRL I ect ou loy L/CMD while clicking for mu c ultiple selectio ons). You can also select entire folders, or the projec root folder. Right-click o the n e ct on selectio and choose Force.com -> Deploy to Server. on e m y r The first page o the deploym wizard wil appear and y T of ment ll youll need to enter your usern e name, passwo and securi token for the target Org The next pag will allow you to backup your ord ity t g. ge y p project and destination environmen the defaults (backup the target environm t nt, s ment) are suffi ficient. Page th of the wiz will list the files you are deploying. If y hree zard youd like to de eploy a subset of the files listed youll nee to uncheck the unwanted files. The w ed k d wizard color co odes the chang to ges visually let you know if a source code file has chan y w nged (yellow), is new (green), or has not changed , (grey). Clicking on Validate Depl loyment perfo orms a test dep ployment but doesnt comm the mit change Clicking nex will attempt deploy your co and metad es. xt ode data. O Often your dep ployment pack kages have dep pendencies on other file elem ments, o objects and their fields. If th hese dependen ncies are creati issues or y ing youre s simply perform ming pre-deplo oyment checks the Force.co IDE is the only s, om e t tool through which you can perform key-w w word searches through all of your f m metadata.


Salesforce Handb book

If all goes w the last page will notify you if the de well, p y eployment succ ceeded, otherw youll wise arr at a page that details th failures. Aft a successfu deployment your new fun rive he ter ul nctionality wil be available i the target Org. ll in O Deploymen can take up to fifteen mi nts p inutes to comp plete because a current all and new un tests are ru as part of th migration process. Things that can nit un he p slow down deployment include a large number of unit te n ts rs ests, large amounts of data in your Org, lots of f files, the types of componen record nts, locking, ser availability and inefficien unit tests. rver y nt Th Force.com Migration Tool he m T The Force.com Migration Tool uses th Java-based b n he build tool calle Apache Ant to move ed t me etadata and so ource code fro a directory on a local ma om achine to a sa alesforce.com O This Org. pro ocess is more complex than using the dep n ployment wiza in Eclipse but salesforce ard e.com has do ocumented the tool compreh hensively1. The officia documentati covers eve al ion erything you m might need to use with the tool so a sum mmary should be sufficient The tool use configuratio files to det d t. es on termine which Org and h cre edentials to use in the conne ection. It also uses a file call package.xm (which you may have led ml no oticed in your Force.com pro oject) to deter rmine what ne eeds to be dep ployed. The de eployment becomes highly configurable through custo omization of these files allo owing granula control ar ov what is dep ver ployed, where its deployed to and even w i o, which unit tests are run. Ther are also s re configuration file that can destroy metadata to the target Org allowing you to perfor housees a rm keeping prior to any deployme ent. Once the to is executed it behaves sim ool milarly to the de eployment wiza in that it ar ard rchives the file sends them to salesforce.co for compila es, om ation and posts the results to the command l s t line. Ant is a po opular tool and there are a n d number of Jav va-based server and applica rs ations that can execute and monitor Ant builds. Using s n b some of these t tools you can have deployme build h ents automatically on any VCS com n mmits, monitor the quality of code and gath build statistics. r f her Hudson was mentioned in a previous chapter, and besides perfor w rming the role of con ntinuous integr ration server i supports a number of plu it n ug-ins that facilitates the aforement t tioned feature Some of these can be found at es. t http://wiki. .hudson-ci.org/di display/HUDSO ON/Plugins. Pa ackages Packages o Force.com are collections of code that can be distrib on s buted without using the Fo orce.com Migr ration Tool or the Force o e.com IDE. A a minimu all you n At um need is a sal lesforce.com O and the URL for the pa Org U ackage to insta it. Packages come in two varieties, all s ma anaged and un nmanaged, each with its own purposes2. h In short un nmanaged pac ckages are used to organize code into com mpartments, y might you thi of them a libraries or templates. F example th work ver well as ope source ink as r For hey ry en
1 2

fo orce.com-migratio on-tool ap pplication-packag ges Jeff Dou uglas & Wes Nol lte 119

projects. Managed packages are typically used for comme d ercial products as they hid the s de applica ation source co from the package consum and restrict certain custo ode p mer omizations. B aware of the limitations of managed packages be Be d efore diving i into a p project. Not all application components c be packag (although more a can ged h have become packageable w with each rel lease), and da is currently not ata y p packageable. This typically means some post installatio configurati is T on ion n necessary for th package pro he oducer. The producers of managed packages also have some useful tools at their finge tips T s o er includi ing license m management of installed packages, the ability to pu upgrades, code o ush deprec cation and app plication versio oning. For a pa ackage to appe publicly on the AppExch ear n hange it has to be managed t d. A Dep ployment Alte ernative There is anoth method of migrating cod born more out of proce than techno T her f de, e ess ology. The method we will describe is fast, and because of the inclus m l sion of a VCS minimizes the risks e associa ated with mig grating code. Note that this method onl works for migrations bet N s ly m tween sandbo and/or D Orgs. oxes DE For this type o deployment youll need tw Force.com IDE projects, each connect to F of wo ted its ow Org but sh wn haring the sam VCS repos me sitory. From f figure 3 - 17 it can be seen that i n change are made in a developm es n ment project, c committing ch hanges to your VCS at mile r estone points. When you ar ready, impor the required changes into the deployment project and push re rt d d them to the target O t Org.


Salesforce Handb book

Figure 3 - 16. Deployment vi Force.com ID Projects and VCS ia DE d

You might ask why not use the Forc t t ce.com IDE d deployment wi izard or the F Force.com Mi igration Tool. The answer to both is that its a matter o saving time and reducing r o of risk. With the Force.com I e IDE deployme wizard you need to find and enter cre ent u edentials for ea target ach Or and all tests are run on ea deploymen which can occupy your IDE for 15 minutes at a rg, s ach nt, tim With the F me. Force.com Mig gration Tool y youll need to manage deplo oyment descrip ptors and po otentially fiddle with configu e uration files. B Both of these methods also allow you to skip the o o VC step. We th CS herefore gain ti because al we need to d is move fro one Force.com IDE ime ll do om pro oject to the oth and we reduce risk since the VCS form our deploym conduit. her, e ms ment Note that y can have several target d you s deployment pr rojects all conn nected to the s same VCS rep pository. Then its just a matter of pu n ulling source code into the appropriate Org for e d deployment.

Jeff Dou uglas & Wes Nol lte


Monitoring Deployments We previously noted that deployments could take upwards of 15 minutes to complete. If youd 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 s should lead to better respon times for t o nse things like list views and rep t ports, for exa ample. Divisions are desig gned to scale up to 100,0 e 000 users for Orgs based on data r seg gmentation in the 1M+ rang Salesforce.c ge. com specifies that you shoul aim for less than 1M ld s rec cords per object per division See chapter 2 for more info n. ormation on Divisions. D Ar rchive Data Determine if you can arc chive data in an nother custom object or syst for record that are m tem ds typ pically only ne eeded for historical purpose It may not make sense to force users to wade es. t s thr rough millions of record tha are, say, 5+ years old whe all they are really concern about s at en ned are leads that hav been created within the la 6 months. e ve ast Cr reate Addition Indexes nal Any field marked as an External ID will auto a omatically cre eate an index. If your application cons sistently perfor searches o the Email field, then marking that fi as an rms on l m field E External ID sh hould significa antly increase r response time. You can also contact salesf . o force.com Su upport and disc with them the possibilit of creating m cuss m ty multi-column or additional in o ndexes on an object to spe up searche and reports Salesforce.co periodically monitors qu eed es s. om y ueries and trie to detect ne indexes that need to be cr es ew reated but you may be better off making th request u r he for rmally via supp channels. port Creating in ndexes may sig gnificantly incr reases data load and delete p processing times as these indexes ha to be maint ave tained.

Op ptimize Secur Model rity Use private sharing models sparingly and strategic y cally when po ossible. The F Force.com database is desig gned to be opti imized by reco owner to d ord determine whic user can see a record ch e or group of rec cords. Try to minimize the number of sh m haring rules per object. Per rformance de n aring rules app proaches 250. Also attempt to avoid t begins to degrad when the number of sha nnecessary leve of role hiera els archies, groups and territorie as it has an impact on per es rformance un as well. A wide-o open sharing model will alw be more p m ways performant due to the lack o security e of checks when fetc ching records for display, list views, report etc. t ts, Tr rain Users to Search Effect tively Provide en nd-user training so that user constrain th searches to provide bett results g rs heir o ter with less time. So instead of se earching for S Sm* across al objects, have users enter a keyword ll e tha is more sign at nificant or imp pactful like a S SSN or phone number. Anot ther technique to speed e up searches is t use the ne advanced search to onl search a sp p to ew ly pecific object. Utilizing div visions will also speed up sea o arches as it use the users su es ubset of record by default. ds

Jeff Dou uglas & Wes Nol lte


Use Asynchronous Apex Whenever possible, use Asynchronous Apex to process records or other operations in the background. If the user isnt dependent on a process, dont make them wait for it to finish. Perform it in the background while they go about their business. Asynchronous processes dont 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 its traditional counterpart youll 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 well 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 testi ing o U acceptance testing User e o Q Quality assuranc testing ce Testing methods g o Bl lack box o W White box Testing processes g o W Waterfall o A Agile There are a additional testi levels, met ing thods and proc cesses1 but we argue that t above ed the are the most po e opular, and ty ypically a deve elopment team wont (altho m ough they should) even em mploy all of the testing le evels and methods mentio oned above. Each of these is well E do ocumented, spa anning thousands of website and many a book, so we not detail th es ll hem here. Instead well intr roduce the area that are most popular with Force.com developers. as h d Un Testing nit Unit testing is common in software d development a in short could be defin as the and c ned pro ogrammatic v verification of application code at a gran nular level, typ pically per fun nction or me ethod. Often time developers confuse unit testing with integration te es s t esting and instead of determining w whether the fu unctionality provided specifi ically by a code funct tion works, the instead test whether it works with other elements ey r of the syst tem. On the p platform both types of testin exist, but a largely ng are referred to by the same n name. g e.com platform is a feature of Apex code and Apex trig m ggers, and Unit testing on the Force wil be explored in their respe ll ective sections. It is importan to note that you cannot d . nt t deploy (in the Force.com sense) to an Org unless your unit tests exe e r ecute at least 75% of the sou code 7 urce tha has been wr at ritten. Sy ystem Testing g Developers will breathe a sigh of relie to learn tha many aspect of system te s ef at ts esting are handled without them having to lift a finger Scalability, s t r. stress, load, pe enetration and reliability tes sting are some of the types of testing tha you no long need to wo about (ho e at ger orry oorah!) as the eyre salesforce e.coms respon nsibility.

so oftware-testing Jeff Dou uglas & Wes Nol lte 125

Testin Environme ng ents and Arch hitecture One of our fa O avorite testing features of th Force.com platform is th ease with w he he which you can create re c eplicas of your production environmen In traditi n nt. ional develop pment topolo ogies this is u usually a nightmare as you need the har rdware, softw ware, licenses, staff, infrast tructure, etc. t support the duplicated en to e nvironments, and even then they typicall will n ly not be precise copie e es. Note that sand N dboxes are onl available to salesforce.com customers who have purc ly m w chased Enterp prise or Unlim mited Edition li icenses1. There are different types of sand t dboxes that su upport copyin data, config ng guration or bot and it is po th, ossible to have multiple, inde ependent sandb boxes at once. I you do not have access t sandboxes with your sale If to esforce.com ed dition t then you can sign up for a fr DE Org (h ree http://developer.f force.com). You could c create a proce that deploy code and d ess ys data to this Org giving you near O u s sandbox capab bilities. For the rest of this section we will only m F f w mention sandbox and produ uction environm ments but be aware that in most situati e n ions it is tech hnically viable to replace sa andbox with DE Org. It is widely reg I garded that dev velopment and testing enviro d onments shou be kept sep uld parate. This im mplies testers a and/or users can evaluate fu c unctionality wit thout holding up developers This s. setup was demonstr w rated in topolo of figure 3 - 2 and figure 3 -18 shows that each pha of ogy s ase testing also serves a a feedback mechanism. If new features are requested or functiona g as m f s d ality is faulty, the requireme are analyzed and develop ents pment returns to the first ph hase.

enviro onment-types Salesforce Handb book


Figu 3 - 17. Force.com Developme Lifecycle ure ent

This devel lopment lifecy ycle coupled w with a regula release sche ar edule would form the heartbeat of yo software output effort Note that salesforce.co has a boo called our ts. om ok D Development Lifecycle Gui ide that exte ensively discu usses developm ment, deploym ment and tes sting strategies1.

fo orce.com-develop pment-lifecycle-gu uide Jeff Dou uglas & Wes Nol lte 127

S Salesforce.com offer a fre cloud-based service call m ee d led the Force e.com S Security Code Scanner1. This developer tool will scan th code in the target s he O for securit (e.g., cross s scripting, S Org ty site SOQL injectio and code q on) quality ( (e.g., DML sta atements or SOQL/SOSL i inside loops, non-bulkified Apex n m methods) issue and send you a handy PDF with the deta es u F ails. Analy and Maintenance on th Force.com Platform ysis he m Now youre aw N ware of the to ools available to aid you in creating, tes n sting and depl loying applica ations, so wha next? What if something goes wrong o its requeste that some p of ats t g or ed part the ap pplication be c changed or enh hanced? Its th that you n hen need a sound knowledge of tools f that ca help you analyze and/or maintain your a an m application cod de. Broadly speakin the tools av B ng vailable can be categorized as data-analysis tools, code-an s nalysis tools, or both. Some tools are offic e cially supporte by salesforce ed e.com while ot thers are not. Force.com IDE S Schema Explorer The Schema E T Explorer is a tool used for data and sche t ema analysis, and is conven a niently located within the F d Force.com IDE Double-clic E. cking on the file called salesf force.schema i any in Force.com IDE pro oject will open the schema fo the connect Org. Figur 3 18 show the or ted re ws typical DE Org sche l ema. Expanding the schema tree in the right pane youll se all the obje in your O a E e ee ects Org, descrip ption of each o objects field, as well as detai of object rel a ils lationships. Ex xploring the sc chema this wa is often muc quicker tha navigating th objects thro ay ch an he ough the salesf force.com UI. L Looking throu the list o schema ob ugh of bjects youll se objects su as ee uch A ApexClass and ApexTri a igger. Here you start to get a feel for how g r d deeply metada penetrates the platform. For example Apex classe are ata es s simply metada (XML) plu persisted d ata us data, making for a powerfu and f ul i incredibly flexi programm language. ible ming The left-most pane in the Schema Explo T orer lets you run SOQL queries against that q particu Org. You have the opt ular u tion of typing out the quer manually, but for quick query g ry b buildin you can select the appropriate objec fields in th right-most pane and Sc ng ct he chema Explor will generate the query fo you. Clickin Run Me will yield the quer results just b rer or ng l ry below the qu input area. uery . Force.com Explore er The Force.com Explorer is a Windows only tool of T m s ffering the sam functional as me lity Schem Explorer an more2. Afte logging in y ma nd er youll arrive at the main app t plication windo as ow shown in figure 3 18. n

1 2

apex-s security force.c com-explorer Salesforce Handb book


The passw word that F Force.com Ex xplorer expec is your password cts concatenat with your security token i.e. if your password is P ted n p Password and your token is Tok ken then you Force.com Explorer pas ur ssword is Password dToken. You find that if a tool does not explicitly ask for a ll f n token it ass sumes that you supply it with this concaten u h nated password instead. d The landing tab is immed g diately familiar in that it mirr the Schem Explorer vi r rors ma iew. Note tha the languag used for qu at ge uerying here is structured ob s bject query lan nguage (SOQL which L), we discuss later. The next tab offers the ability to test structured object search language ell e (SO OSL) statemen and helps to learn the l nts, language with a search state ement builder similar to tha first seen in Schema Explo at orer. The Da Editor tab lets you exam data for an object, ata b mine ny as well as armin you with so ng ome editing ca apabilities. Last but not least the Docum t ments tab let you interrog ts gate a special object called Document. You can sto binary larg objects ore ge (BLOB) in the D Document ob bject; this allow you to uplo images, off files, or m other ws oad fice most lar file types. rge For the mo part Force ost e.com Explore falls into th Analysis category and a helps er he c also tho starting of with the Fo ose ff orce.com query and search l y languages (bes sides the query builders y the are sample queries availab from the a ere ble application men nu).

Figure 3 - 18. Force.com Exp . plorer Jeff Dou uglas & Wes Nol lte 129

SoqlXplorer SoqlXplorer is a Mac application offering similar features to those of Force.com Explorer built by one of salesforce.coms brilliant minds1. It doesnt 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 wouldve 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 its 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, youll need the ported version called LexiLoader4. Workbench This community built application stands out from the aforementioned tools. Its webbased (although youll 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


Salesforce Handbook

Not only d does it suppo describing, inserting, upd ort dating, deletin undeleting, purging, ng, , qu uerying and ex xecuting Apex, the interface is arguably better than in the other tools and the , t do ocumentation is in-depth and precise1. d Since most of the feature available fro this applica t es om ation have been covered n already its not necessary to revisit them Dont be de y m. eceived by the length of this summa though, W ary Workbench is th bees knees as its a web-b he based one stop shop. Fo orce Metadata JDBC Drive for Schema a er aSpy A superb t tool created by a rising star of the Force.com commun y nity, it generat entitytes rel lationship diag grams for your Org. Moreove it generates an interactive local site that describes er your schema from the highest level down to the smallest d m detail. The tool sits firmly withi the analysis arena, and its implementatio might be re in on egarded as me edium to dif fficult, althoug Jeff Dou gh uglas has writ tten up an article that m makes its im mplementation clear2.

Fig gure 3 - 19. A Sc chemaSpy Gener rated ERD

1 2

workbench w fo orce-metadata-jdb bc-driver-schema aspy Jeff Dou uglas & Wes Nol lte 131

Debug Logs g Logging is par L rt-and-parcel of any develo o opers life. De ebug logs for Force.com ca be an accessed through a salesforce.com instance by clicking Set m y tup, and und Administr der ration Setup clicking Moni itoring -> Debug Log > gs. Debug logs can run continu D nt uously and ins stead are reque ested on a per user basis, wi 20 r ith logs being provision at a time i.e. one log b ned file will be c created for ea user transa ach action which for a typical p page or API tra ansaction woul include: ld Any contro code run on a page load oller o d Any contro code run as part of an A oller a AJAX request Any trigger workflow, va r, alidation rule o database act or tivity initiated from the page f

Transactions ca also be mor nuclear, and not necessaril user-initiated. T an re d ly After clicking N and select a user you have the abil to delete, reset or apply filters A New ting u lity r to the request. The delete option is obvious, t reset option will refre n the eshes the debu log ug reques so that you once again hav 20 logs ava st ve ailable, and the filter option works precisel like e ly those seen in anonym s mous blocks i.e. it controls th log verbosit he ty. A Although only 20 logs should be available at any time, it seems that for each d r c click on Reset an additiona 20 logs are p t al provisioned. Dont tell anyon we D ne t you thoug told gh. The output of the log is nece T essarily comple as it has to t ex track code at several levels, a to s and be of any use, needs to be granula to the sub-a s ar atomic level. W would high recommend that We hly d instead of just readin through the logs line-by-l that you in d ng e line nstead fire up the System Co onsole Log (S System Log as the tools available there make for a fa superior deb g) e far bugging exper rience. 1 Note that you will st need to hav the official log output gui close at ha until you g a t till ve ide and gain fair am mount of exper rience. Tools to Assist Pro oductivity & More M Every develope has tools th whilst not used directly i their develo E er hat in opment aid them in one wa or another. List here are a notable few. ay Force.com Utility B Belt This Google C T Chrome Extens sion provides shortcuts to so of the most commonly used ome y salesfo orce.com docu umentation, a quick search in q nterface for mo salesforce.c ost com documentation plus a large number of other sites (e.g., Messag Boards, Snip r s ge pplr, Code Sha AppExcha are, ange), links to number salesforce.com res o sources and a 1 15-digit salesfo orce.com ID converter.

unders standing-debug-lo og Salesforce Handb book


Av vailable from http://blog.jeffdouglas.com/force-c h com-utility-belt Tr rapdoor This neat M OS tool will keep track of your salesf Mac w k force.com cred dentials. As an example n we currently ow more than 20 salesforce. e wn n .com Orgs so t tool is han this ndy.

Av vailable from http://www.pock h ketsoap.com/osx/ /trapdoor Se etup Enhance for Salesforce er Those fam miliar with GreaseMonkey a aware tha its a brows plug-in th allows are at ser hat dev velopers to create JavaScript tweaks to we t ebsites. The Se etup Enhancer is one such script, and r it simply injects a search dialo box into th top of the navigation pa in the setu menu. og he ane up Ty yping in the se earch box will filter the setu menu items in real-time. This simple to makes up T ool the setup menu l intimidatin and helps b e less ng, beginners find the proverbial needle in the haystack. l

Av vailable from http://userscripts h s.org/scripts/show/60438 Ap pplication Sup pport on the Force.com Pl F latform Many platf forms have fall flat simply because of support issues, Force.com is n one of len F not the Support is available in a variety of form and youll f that salesf ese. s ms find force.com, as w as the well dev veloper comm munity, are alwa willing to e ays extend a helpin hand. ng Of fficial Suppor Channels rt Fo orce.com Disc cussion Boards A live, evo olving support option, this channel is inva aluable for beg ginners. The fo orums are bro oken into man channels, an youll eventually learn the names of the experts in each section. ny nd Wed like to stre that no qu ess uestion is too s to ask as most people that browse th boards silly he answering questi ions were educ cated from the forums. e

Yo can find the discussion bo ou e oards at http:// /boards.developerf rforce.com

Jeff Dou uglas & Wes Nol lte


Direct Support t There are level of direct sup T ls pport offered by salesforce.c com. The basi support opt ic tion is availab to all custo ble omers and inclu udes telephoni email and c ic, case-based chan nnels. At the h higher levels of support t turn-aroun times are much shorter and even offer administ the nd r, o trative service To drill do es. own into the su upport offerin open up th below URL and check ou the ngs he L ut links under Related Documents. u d .

Availab from https://www.salesforc ble ce.com/ap/service es-training/custo omer-support Twitte er One of the n O newer support options, thi channel is available for concise ques t is stions. Turnar round times o questions asked via twitter are typically fast, althoug due to its n on a y gh nature questio cannot be complex or require long e ons e explanations. T There are also a number of subo f channe each availab from the below URL. els ble b

Availab at http://tw ble witter.com/Salesf force Docum mentation Documentation is one of the most importa support c D n e ant channels, and salesforce.com has d m lots of it. Google ca help you fin the right do f an nd ocumentation a lot of the tim but some o the me, of jewels of the platform are found in PDFs that ar m n rent Google-in ndexed1. Most d developer docu umentation is a available from m http:// /wiki.developerfor rce.com/index.ph hp/Documentatio on Visiting the pa the first few times seems like an infor V age rmation overlo so well li the oad, ist docum ments youll m most need to st out with ( tart (assuming you intention is to become fa ur amiliar with th Force.com p he platform langu uages). Introductio to Force.com - Core Reso on ource Articles Force.com Workbook: Getting Started Building Your First App in the Cloud G r Force.com Fundamentals Custom App s: plication Development in the Cloud e Visualforce Quick Start Tutorial e T

officia al-documentation Salesforce Handb book


Apex T Tutorials Under Reference Gui ides o A documents under Genera All u al o A documents under Ap All s pex and Visu ualforce (cor language reference re do ocuments)

Force.c com Cookbook Code Sampl and Best Pr k: les ractices All doc cuments under Developer C r Cheat Sheets

Un nofficial Supp Channels port s Bl logosphere A number of talented in ndividuals have setup blogs t share their experiences an advice e to nd 1 with the Force.com commun . The top here rang from the sa nity pics ge alesforce.com CRM to adv vanced topics of integration. Tw witter Many Forc ce.com develo opers that you can befrien through Tw u nd witter will fre eely offer sup pport and ad dvice. It was realized by Quinton Wal that perhap anyone loo ll ps oking for community supp should us the #askforc hash tag, an this has pla port se ce nd ayed out quite well. For mo in-depth q ore questions its customary to p on the Fo c post orums and the link to the issue in a en tw with said h weet hash tag. Sa alesforce.com Certification ns Message bo oards, LinkedI and staffing firms are co In g onstantly tryin to fill salesf ng force.com po ositions with q qualified profe essionals. The industry is bo ooming and that is great fo people t or loo oking for jobs. One of the best ways to de . b emonstrate to p potential empl loyers that you have the u ski and exper ills rience necessa to do the job is to bec ary come certified Salesfoce.co offers d. om cer rtification for consultants, ad dministrators a developers There are fiv levels of cer and s. ve rtification two for admin nistrators, two for developer and one for consultants. o rs, r Training videos for D v DEV-401, DE EV-501 and Admin to H A Hero with Force.com are available for free on iT Tunes. Simply search the iTu unes store for salesfo orce.com. com offers tra aining classes t prepare you for the certifi to u fication test bu they are ut Salesforce.c no required. Tr ot raining is recom mmended but nothing preve ents you from studying on y m your own (st tudy guides ar freely availa re able) and taki the test a a local test center or on ing at nline. The cer rtification exam feature mu ms ultiple-choice and multiple-select question (60-70) tha cover a ns at

co ommunity-blogs Jeff Dou uglas & Wes Nol lte 135

broad range of topic in that area. The Advanced Developer e cs d exam also inclu udes a program mming assignm ment and sho ort-answer ess exam. Most certification exams cost $200 howeve the say n er Advan nced Develope certification exam is $400. er Youre conside Y ered qualified once youve successfully p passed your exam. However, to e mainta your certifi ain ication over su ubsequent relea ases, you are re equired to take interim exam that e ms test yo knowledge of the new release feature The cost o these interi release exa our e es. of im ams is included in the initia certification fee for 1 year After that ye maintainin your certific al r. ear, ng cation require a yearly mai es intenance fee of $100. o Visit http://www.salesf sforce.com/service es-training/traini ing_certification/ /certification for more inform mation.


Salesforce Handb book

Programmatic Development Languages

n this chapter youll learn more about how to create and maintain applications on the Force.com platform. In doing so youll 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

Weve addressed the topics of software development models and the tools that youll need as a Force.com developer. A natural next step is the exploration of the languages and technologies that youll 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 applications 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 platforms 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 youd 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 4 - 1. MVC on Force.com F C m

The model, the view and th controller c T he clearly have sep parate domain of operation and ns n this all lows you to wo on each co ork omponent inde ependently. Since the Force S e.com platform alludes to th design patt m his tern we will dis scuss each platform langua and techno age ology within th context of th roles. he hese S Salesforce.com is a multiten m nant architectu as explaine in chapter 1. In ure ed o order to preven any applicat nt tion from con nsuming more than their fair share o the platform resources th have introduced restricti of m hey ions on measu urable p program opera ations. These r restrictions fall under the na l ames governor and rs l limits and toge ether they forc the develop to create code that is eff ce per ficient s such that all tenants get a equal share of the resour pie. Devel an e rce lopers d dont like Gov vernor Limits v much as their developm very ment style is f forced i into certain pr ractices used to remain wit thin these lim mits. However these p practices ensu a code ba that is ne in architec ure ase eat cture and qui in ick e execution. Go overnor Limits are applied differently to each area o the s o of d development platform and w be discusse those contex p will ed xts.

The Model M
Within the Fo W orce.com platf form data pers sistence is pro ovided throug what are te gh ermed Object These come in two broad flavors as sho in chapter 2. ts. e d own r Objects are an excellent way to abstract aw the database and its corr O way responding fie as elds this all lows develope to work wit data in an o ers th object-oriented way i.e. inste of working with d ead g data ro ows, on the Fo orce.com platfo data is en form ncapsulated in a class-like stru ucture with the data e fields accessible via member varia ables. If we peek into the co ontroller domain briefly you see, ll


Salesforce Handb book

as show in listin 4 - 1, that objects can b instantiated, and their me ng be ember variable can be es ass signed values i much the sa way as clas variables. in ame ss Listing 4 - 1. Object Ma anipulation in an Apex Cla n ass
Account myAccount = new Acco ount( ); myAccoun nt.firstnam = Zack; me

What do d developers exp pect from the model? Usua youd need several abilit to be ally d ties exp posed: o Data Creation o Data R Retrieval o Data U Update o Data D Deletion o Data Se ecurity The first fo features ar sometimes r our re referred to as create, retriev update and delete or ve, CR RUD. Data retrieval is the most complex of CRUD on the platform having two languages m x n m dev voted to this s purpose. The other ope sole T erations are sem mantically quit similar, and vary only te in syntax and res and therefo make a good starting poi sult fore int. Data secur is configured using a com rity mbination of fe eatures such as profiles, roles and field-level secu f urity. These to opics are discu ussed in more detail in e chapter 2. ata n, d Da Creation, Manipulation Update and Deletion With most types of data abases youll en ncounter oper rations to inse 1, update2 an delete3 ert nd data. Force.com is similar in this regard, w listing 4 - 2 demonstrating how to insert, m with up pdate and del lete a data record. r Listing 4 - 2. Insert, Up pdate and Del lete a Record with Apex Code d 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 = Jon; me ; update m myAccount; // Update the above record delete m myAccount; // Remove the record from the data store d

dm ml-insert-docs dm ml-update-docs 3 dm ml-delete-docs

1 2

Jeff Dou uglas & Wes Nol lte


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. Theres 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 well 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 youll find that structured object query language (SOQL), which has its roots in SQL2, is the one youll use more frequently. This is another topic that is covered by torrents of documentation, so wed 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


Salesforce Handbook


Qu uerying with SOQL Looking at listing 4 5 you can see how this sy t e yntax can be applied with the Apex pro ogramming lan nguage, as well as how you c work with t results of a query1. l can the Listing 4 - 5
Account account = [SELECT id name FRO Account d, OM ame = Zack k]; WHERE na // Or if we only require the account n f r e name String n name = [SEL LECT name F From Accoun WHERE nt name = Zack].nam me;

Note that queries will always return data as comp a plete object re ecords unless aggregate fun nctions are us (more on these later). I the second query weve demonstrated how you sed In d mi retrieve a single field val by derefere ight lue encing the nam field. me The above example assum that exactl one record w be returne by the query and this mes ly will ed y, is often a danger rous assumptio to make. If the query we to return zero or greater than one on f ere res sult, your appl lication would throw a runti ime error. In s some cases it would be bette to feed w er the results of a q e query into a list of objects as shown in listin 4 6. t ng Listing 4 - 6
List<Acc count> acco ounts = [SE ELECT id FR ROM Account WHERE t last tname = de la Rocha]; e

Here you s the Apex syntax for lists of objects bu dont panic, it will be revisited later see s ut in more detail. T query is not capable of c This creating runtim errors; if no records are f me o found the list will be empty and if more than zero are f t y, found theyll b added to the list. be e There is an nother way to deal with a qu that return zero results. At times uery ns . its better to implement a Apex langu t an uage feature ca alled exception handling n to avoid th type of run his ntime error; th feature will be examined in a later his l section. Ap Variables in SOQL pex s Once you dive into SOQ programm QL ming with Ape youll often find the need to filter ex d your queries usin the value in an Apex varia ng n able. As an exa ample consider the query in l r listing 4 6, but imagine th now, at de hat evelopment tim we dont k me, know what the last name mi e ight be as its determined b user input. In this case you use the syn presented in listing 4 7 s by I ud ntax 7. Listing 4 - 7
String l lastname = de la Roc cha; List<Acc count> acco ounts = [SE ELECT id FR ROM Account WHERE t name = :lastname]; ;

working-with-soql w l-results Jeff Dou uglas & Wes Nol lte 141

Here weve de H eclared the var riable that will hold the last name value, and delimited said l t d variabl with a colon Using a loca variable with a SOQL statement is kn le n. al hin nown as a bind and d, they ca be simple v an variables (as shown above) or formed by ex r xpressions1. Objec Relationshi & SOQL ct ips In modern dev I velopment most databases ar relational i.e records in one table are related re e. o to records in other tables throug an establish relationsh The situat gh hed hip. tion is similar with r salesfo orce.com objec and weve seen in previo chapters th types of relationships tha can cts ous he at exist. On any platfo orm youll nee a way to t ed traverse these relationships and salesforce e.com encaps sulated this in a concise and powerful way. From an objec point of view you can eith be related to a parent or a child object The F ct w her r t. differe ence in the syn for each si ntax ituation is show in listing 4 8. wn Listing 4 - 8 L
// Syntax f / for selecti ing all acc counts and their chi d ild contact ts List<Accoun L nt> account = [SELEC Id, (SELECT first ts CT tname, lastnam FROM Con me ntacts) FRO Account] OM ]; // Syntax f / for selecti ing all con ntacts and their par d rent accoun nt List<Contac L ct> contact = [SELEC id, Account.name, ts CT Account t.firstname Account. e, .lastname F FROM Contact];

B careful whe using the fir type of SO Be en rst OQL query as it can be diffic to i cult p predict (and re estrict) the num mber of data ro returned i. each accoun can ows .e. nt h have any numb of child co ber ontacts. Later w see that th are opera well here ational l limits on thing such as the n gs number of dat rows retrieve by a single query ta ed o within a tran or nsaction. The syntax fo each of these query typ is quite d T or pes different but simple noneth s heless. Access the related objects for each type of re sing d e elationship is al different as is shown in l lso listing 4 9 with follows on from listing 4 - 8. w n Listing 4 - 9 L
// Accessin child co / ng ontacts of an account Account a1 = accounts A s[0]; List<Contac L ct> account tContacts = a1.Contacts; // Accessin the pare / ng ent account for a contact t Contact c = contacts[ C [0]; Account a2 = c.Accoun A nt;

Through these Apex variab T e bles you woul have acces to the contents of eithe the ld ss er 2 childre or parent of the object in question . Be aware of the syntax when dealing with cu en n e d ustom
1 2

soql-b bind-variables soql-re elationship-querie es Salesforce Handb book


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<Father__c> fathers = [SELECT id, (SELECT FirstName__c FROM Sons__r) FROM Father__c]; // Syntax for selecting all sons and their specific father List<Son__c> sons = [SELECT Id, FirstName__c, Father__r.FirstName__c FROM Son__c]; // Accessing sons contacts of a father Father__c f1 = fathers[0]; List<Son__c> sonsOfTheFather = f1.Sons__r; // Accessing the father of a specific son Son__c s = sons[0]; Father__c f2 = s.Father__r;

Its 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


F Figure 4 - 2. Cre eating a Relation nship Between C Custom Objects s

Dynam SOQL mic Dynamic SOQ is a feature of the platform lets an appli D QL m ication dynami ically build a S SOQL 1 string at runtime . T way the value of a quer string can b determined by user-input as is This v ry be d t essenti with any da centric appl ial ata lication. The syntax for the query st T r tring is the sam as that of SOQL but the query exec me f t cution require a system me es ethod call as sh hown in listing 4 11. g Listing 4 - 11 L
// Declare a string to be used in the query / t String qs = SELECT id FROM Acc S i count; // Execute the query / List<Accoun L nt> account = Databa ts ase.query(qs);

Another super feature of dynamic SOQ is that the query results can be return as A rb d QL ned concre objects (as above) or they can be retu ete urned as the g generic sObjec data type ak to ct kin listing 4 12. Variab of this ob bles bject type can h hold any type of object valu be it standa or ue, ard custom This allows you to writ applications that cleverly reuse code and deal with data m. s te s y a h polym morphically.

dynam mic-soql-docs Salesforce Handb book


Listing 4 - 12
// Decla are a strin to be us ng sed in the query String q = SELEC id FROM Account; qs CT // Execu ute the que ery List<sOb bject> sObj jects = Dat tabase.quer ry(qs);

Using dyna amic SOQL also requires extra care as it involves more coding a a m and error checking, and po otentially expo your appli oses ication to SOQ injection attacks1. All the same, it QL a is a powerful too when used correctly. ol c SO OQL Governo Limits or SOQL Governor Limits2 are one of t most discu the ussed topics in the develope forums n er and many of th questions ar nearly iden he re ntical. The prim mary issues co oncern hitting the limit im mposed on: 1. 2. The to number of SOQL queries issued otal The to number of records retur otal rned across your SOQL quer ries

The first l limit is typical hit when developers ex lly xecute queries within some repeated str ructure such as a loop which will result in t following e s the exception:
System.E Exception: Too many S SOQL querie es

As its one of the most common lim that beginn e mits ners encounte well demon er nstrate an exa ample of the i issue in action as well as th solution. Li n, he isting 4 - 13 sh hows a SOQL for-loop L tha contains ano at 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;

Depending on the executing codes e g entry point th Governor a Limit he and value that is applied will vary e.g. if t first code to execute is within an l the Apex class you can issue 100 queries w e within the lifet time of that in nvocation. If execution began in a tr rigger however you can only issue 20 queri r ies. This proble ematic pattern is to be avoid at all cost. Salesforce.co restricts the number n ded om of queries because database round trips are e expensive and can quickly af ffect the perfor rmance of the multitenant environment. The idiom us to resolve this is show in list 3 - 15. N e sed i Note that youll need to b familiar with the Set and Map collectio types in or be h d on rder to unders stand and im mplement this p pattern effectiv vely.
1 2

dy ynamic-soql-exam mple go overnor-limit-doc cs Jeff Dou uglas & Wes Nol lte 145

Listing 4 - 14
// create a set of all the unique ownerIds Set<id> ownerIds = new Set<id>( ); // Fetch all the account youll need to process List<Account> 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<id, User> owners = new Map<id, User>([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 wed 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


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. group.
Textarea fields arent searched unless you specify ALL FIELDS for the search

Certain attachment records for some standard objects.

Its important to know that youll 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<List<SObject>> searchResult = [FIND hello* IN ALL FIELDS RETURNING Account (id), Contact];

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 doesnt 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<Account> accounts = ((List<Account>)searchResult[0]); List<Contact> contacts = ((List<Contact>)searchResult[1]);

When planning on using SOSL its 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<Id> 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

Knowing when to use SOSL as opposed to SOQL requires some thought initially, but with a little experience youll 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. Youll 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 Salesforce Handbook


Listing 4 - 19
String searchPhrase = PotOfGold; String filterPhrase = Zack; Integer lim1 = 1; String division = Long; Integer lim2 = 2; List<List<SObject>> 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 objects 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<List<SObject>> 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 werent 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.

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 its 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 its 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. Weve 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.

governor-limit-docs Salesforce Handbook


Figur 4 - 3 Apex: Fro Source Code to End User re om e

Here you s that a deve see eloper creates code locally a upon save the source co file(s) and e ode are sent to the p e platform applic cations servers The code is then compile into instructions that s. ed the Apex runtim compiler un e me nderstands. Th instruction are stored as metadata an when a hese ns a nd use triggers th Apex code these meta er he e, adata instruct tions are inte erpreted and evaluated pre esenting the us with the results. ser Notice tha only the Apex source co is written locally, com at ode n mpilation and execution happens on the F Force.com pla atform. There is a l of docume lot entation on Ap and one o the driving forces behind this book pex, of f has been the ne to help de eed evelopers, business analysts and company owners focu on the y us mo important resources. Thr ost rough this sect tion we will hig ghlight the mo important a ost aspects of Ap especially for those interested or begin pex, nning with the platform. If youd like to e e y expand on the tidbits we tou upon, wed recommend reading the do e uch ocuments listed below. You can f find all of th following l he links by using the official g l-documentatio tag at on delicious.com. Apex Code The World First On-D e: ds Demand Progr ramming Lan nguage A summary for anyone who needs an o y w overview of the Apex languag features1. e ges An Introdu uction to Force.com Apex Code x As the title suggests this is a primer on the language including a lig touch on th syntax, e n ght he Dy ynamic Apex a its role in the Model and View, unit tes and t d sting, web serv 2. vices
1 2

ap pex-ondemand ap pex-intro Jeff Dou uglas & Wes Nol lte 151

Apex Cheatsh A heet This short refe T erence docume highlights i ent important synt across the Apex language1. An tax A e excelle resource fo developers at all levels. ent or a Apex Code Be Practices A est This wiki articl should be used in conjunc T le u ction with any code design and review ses y a ssions 2 as it de etails common patterns that will ensure your Apex code is efficient and scalable . n d Security Tips for Apex and Visualforce D S d Developers An article that explores a number of secur attacks and how to a dev A rity d veloper might avoid 3 them. All developers should read and be familiar with this docu s a r ument . Force.com Wo F orkbook This excellent, short book th covers mor than just the Apex langua with 10 tut T hat re age torials 4 in tota . Each tuto al orial builds on the last to build a wareh n house application, but the most import Apex tuto tant orials are numb 5 and 6. bers Force.com Co F ookbook This book exte T ensively docum ments many fe eatures of the Force.com platform5. It con ntains scores of useful code samples and best practices. All developer starting on the platform should e rs t keep th close at han as many be his nd eginner questio are answered in this book ons k. Salesforce.com recently laun S m nched a com mpanion websi aptly calle the Force ite ed e.com Cookb book. This on nline version is of course, m s, more up to date and recipes are submitted b not e by only sa alesforce.com but by commu unity members as well. Book s kmark this site. . New a updated Fo and orce.com code recipes can be founds at e e http:// /developer.force.co om/cookbook Force.com Ap Developers Guide F pex Every Apex de E evelopers frien this refere nd, ence documen details all areas of the lan nt nguage togeth with a num her mber of code samples6. From beginner to guru you shou always keep this m uld site at the top of you bookmark li ur ist. Development with the For D rce.com Platf form: Buildin Business Applications i the ng A in Cloud d This book by J T Jason Ouellette of Appirio is an extensive guide to build applicatio on e s ding ons the pla atform1. It is an essential guide for anyo looking fo structured, concise way t get g one or to
apex-c cheatsheet 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


Salesforce Handb book

bu usiness applicat tions up and running. It delv into the depths of the la r ves anguage, explo many ores adv vanced topics and include nu umerous tips a tricks not a and available in oth documenta her ation. Key Conce epts As a deve eloper your ro is often to translate a set of busines needs into technical ole o ss req quirements. On the Force.co platform, m logic that supports those technical req n om most e quirements wil be implemen ll nted with Ape In order to create logic with Apex the are certain language ex. o ere n art tifacts and cons structs that are required, a few of which are s w shown in figure 4 4. e Listing 4 - 22
/* Varia able Declar ration */ List<Con ntact> cont tacts; // D Declaring a collectio on Integer count = 0; ; // D Declaring a simple pr rimitive

/* Execu uting an SO OQL Query * */ contacts = [SELECT id, lastn s T 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 will be fam n miliar to devel lopers. As Ap is a stron pex ngly-typed lan nguage, youll n need to explic declare va citly ariables before you can refer to them. In t above r the exa ample weve d declared a varia that can h able hold a number or Integer, as well as a l of the r, r list typ Contact. pe In Java and other langua d ages there are distinct collec ction-types call arrays led and lists. In Apex they are intercha y angeable in th you can declare a hat collection as an array (o vice versa) and then refe to the array and its or er y elements using array not u tation, or refer to it as a list and its eleme using r ents

development-force e.com-platform Jeff Dou uglas & Wes Nol lte 153

t List mem the mber methods. Next in the lis N sting youll see an SOQL st e tatement (as sh hown previously). Following that g weve included one of several loop p-structures av vailable in Ape as well as an example of an ifex, a statem ment used for code branchin Again both of these will be familiar to most develo ng. h l t opers. Lastly weve shown v variable manip pulation and th execution of a database up he f pdate-statemen nt. Excep ptions You can expec a large part of your develo Y ct opment effort to be focused on preventin and d ng dealing with runtime errors. Som of these err g es me rors are expect behavior but there are o ted b others 1 that yo cant anticip ou pate, and on th Force.com p he platform these are called exc e ceptions . T There is some jargon to get familiar with when workin with excep e t h ng ptions. W When an excep ption happens developers w typically sa that an exce s will ay eption h been throw To deal w an except has wn. with tion gracefully you would u y usually s that the ex say xception needs to be caugh An excepti that is cau s ht. ion ught is c considered to be handled. b Some situation where exceptions might be thrown are: S ns e You attemp an insert op pt peration on a re ecord that is m missing required data. d Assigning a query result that returns no rows to a sing variable. t o gle Accessing a member vari iable on an obj whose valu is null. ject ue

To catch excep T ptions requires a special cons struct called a t try-catch block this is comm in k; mon 2 other languages and works in much the sam way . The syntax of a try-catch blo is d m me ock demon nstrated in listi 4 - 23. ing Listing 4 - 23 L
try{ t account = null; n Account a account.A AccountNumb ber = 007; // Null lPointerExc ception } catch (Nu ullPointerE Exception e { e) // Catche above ex es xception xception e) { ) } catch (Ex // The ge eneral exce eption handler. // Catche all type of exceptions. es es } finally {
1 2

intro-e exceptions except tion-methods Salesforce Handb book


// Opt tional fin nally bloc ck. // Cod here run whether exception is thrown or not de ns n }

Best practi dictates th you dont just catch exceptions; you should han ice hat t u ndle them appropriately too This often depends on the situation but as an example it might be s o. d e t e suitable to sen an email to an administra or write a r nd ator record to a cus stom object us for logging sed g. Hitting a Governor Lim will throw a exception that cant be c G mit an t caught (all processing stops immed diately). To av void this situation you can use the n methods of the Limit class to grace o efully stop a process before a limit is encountere 1. ed There will be times wh youll ne to throw an exception based on p hen eed n predefined conditions. To d this youll ha to first dec do ave clare a custom exception usin syntax simil to that ng lar shown in listing 4 - 24. Listing 4 - 24
// Decla are a new type of exc t ception public c class myExc ception ext tends Excep ption {} // Throw an except w tion of the new type e if (true == false) e throw ne myExcept ew tion(True <> False) );

Catching cu ustom exceptio is done the same way as shown in listin 4 - 23. ons e ng CR RUD Operati ions Creating, re etrieving, upda ating and delet ting data is do through Apex command as seen one A ds pre eviously. The most common commands a seen previo n as ously are inse , update, delete ert and upsert (tw that appear less frequent are undel wo r tly lete2 and mer 3). Weve also seen rge ho to fetch and work with th results of an SOQL query. ow d he n . Apex also has a system class called D Database, wh hich allows more control o m over these op perations, as w as provid well ding transactio on-control fea atures4. As an example con nsider the exa ample in listing 4 - 25. g Listing 4 - 25
SavePoin sp1 = Da nt atabase.set tSavePoint( ); ( try{ eResult sr = Database e.insert(ac ccount, tru ue, Save
lim mit-class dm ml-undelete-docs s 3 dm ml-merge-docs 4 database-methods
1 2

Jeff Dou uglas & Wes Nol lte


Database.Dmlopt tions.Assig gnmentruleh header); } catch (Sy ystem.Dmlex xception e) ){ Databas se.rollback k(sp1); }

On the first lin weve used a feature not s O ne seen before, na amely Save Points. For those who e play ga ames on comp puters or consoles, this is lik a saved gam and allow you to jump back ke me ws p to a previous point should you choose to. I the try-part of the try-c p t In t catch block w are we attemp pting to inse a record in a different manner from before. We have used the insert ert i h metho of the Data od abase class with the record we want to insert as the first parameter The w d f r. next parameter is op p ptional and det termines wheth to allow p her partial success of the operatio i.e. o on if you are inserting a list of records and one of t those records i problematic, should the pr is , rocess move onto the next record or fail outright. The next paramet is also optio and allow you ter onal ws to spe ecify additional DML option such as ass l ns signment rule information. Note that with this N h metho a SaveRes od sult is return which con ned ntains informa ation about an errors that might ny have occurred and w o whether the tra ansaction as a w whole was succ cessful. Should the abo DML operation fail, th S ove hereby throwin an exceptio the rollback ng on, metho of the Dat od tabase class will be invo s oked and any DML perfo y ormed between the n savep point and th rollback will be undon You will f he ne. find this featu important when ure insertin many interd ng dependent records in a singl transaction w le where a failure to insert any single e record should remov all related in d ve nformation wri itten in that tra ansaction. A Anytime you insert a new re ecord, the vari iable used to hold the recor will h rd t then also conta that record ID in the data ain d abase. Trying to insert that r t record a second time will yield an error stating th you cannot insert a record that hat d a already has an associated ID. . One convenien most deve O nce elopers dont i initially realize is that DML can be perfo e L ormed directly on collection of objects; this helps con ns nserve DML o operations kee eping you safe from Gover rnor Limits (a while longer at least). Additi a ionally objects are passed by reference me s y eaning that when a variable containing an object is pa w e a assed around y your applicatio the variabl just on le contain a pointer to the true objec Weve dem ns o ct. monstrated this in listing 4 - 26. Listing 4 - 26 L
List<Contac L ct> contact = [SELEC id, firstname FRO Contact ts CT OM LIMIT 1 10]; for(Contact c: contac f t cts) c.First tName = Za ack; update cont u tacts;

Here you see th you can loo through a l of Contacts changing the first name val of H hat op list s e lue each in ndividually. On the last line youll notice w weve applied the DML ope eration to the entire list, an the result of this is that ea contact in the list will ha their first name updated t the nd f ach ave n to
156 Salesforce Handb book

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 well 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( )){ // ... } } }

apex-describe-info Jeff Douglas & Wes Nolte 157

Notice that you can ask an sObject whic specific type it has implem N u ch e mented (as sho in own the if-statement). Th are other methods avail here lable that allow you to interr w rogate just abo all out of the metadata that describes an sObject1. Ad t s dditionally you also have access to field describe u inform mation2, which yields all field related details such as the d d s default value, the type of fiel the t ld, field le ength, whether its unique, etc. By combining field and object describe information you e d n can wr source code capable of dealing with objects in a g rite f generic way th hereby creating neat g reusab component ble ts. A common us of field desc se cribe informat tion is the pro ogrammatic ret trieval o picklist valu Fetching t informatio directly fro the object fields of ues. this on om e ensures that yo avoid hard-c ou coding values in your source code. e It is also sensib at this junc I ble cture to point out that Apex describe infor x rmation is spli into it two data structures viz. sObje /field tok d ect ken and sObj ject/field describe result An d t. import tant difference between the two is that a token is a refe e ference to an actual entity bu the a ut describ result is an object that co be ontains all the describe prop perties for said entity. An exa ample of refe erring to a tok is shown in the if-state ken ement of the a above listing, with a token being issued either side o the equalit operator. I the else-br of ty In ranch of the same listing weve demon nstrated the ret trieval and usa of an sObj age ject describe result. Not only can you dynamica fetch and describe data (or data con N ally a nstructs), Apex also x suppor the ability to perform DML on this d rts D data. Aptly term Dynamic DML3 this fe med c eature also allows you to construct sO Objects dynam mically, and wr the result rite ting records t the to databa Listing 4 - 28 bring all of these concepts together: ase. f Dynamic SOQL to fetc a record. T type is det ch The termined at ru untime by the string passed to the dynamic cDML( ) meth hod. An sObject of the sa ame type as th queried type is instantiate using the to he e ed okens newSObj ject( ) meth hod. In the if-e statement we determine the object ty and copy the queried ob else t e ype, bjects field valu to the new object. We u the get( ) and put( ) field assign ues w use nment methods for the sObje type. ect Without k knowing the object type up front a recor is inserted into the appro o rd opriate object.

Listing 4 - 28 L
public void dynamicDm p d ml(String o objName){ // Dynami SOQL string ic String qu uery = SELECT id FR ROM +objNa ame+ LIMI 1; IT
sobjec ct-describe field-d describe 3 dynam mic-dml
1 2


Salesforce Handb book

// 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


D Dont feel tha its necessa to make every area of your applica at ary f ations r reusable and sm with Dyn mart namic Apex. Th real world is not perfect s not he i so a project piec are destined to be reusab It is impor all ces d ble. rtant to be awa of are D Dynamic Apex and its capab x bilities during the application design proce so ess t when an opportunity ari you are rea that o ises ady. The Future Annota F ation As you might h A have guessed the Apex langu t uage syntax inc cludes a numb of keyword and ber ds annota ations, but one comes up so often and has such great u e o utility that it de eserves independent mentio on. You would ann Y notate a metho with the fu od uture keywor when you need said meth to rd n hod operat asynchronou from the context in w te usly which it is calle 1. Some use cases for future ed e metho are: ods Your app plication needs to make a w service ca to a third party and to r s web all p reduce latency yo wish to mak the callout a ou ke asynchronous. When inv voking an Ape method that performs a c ex t callout from a trigger, the method must be a annotated with the future k h keyword.

Governor Limits withi triggers are typically sma r in e aller than thos of Apex cl se lasses. Firing a f future meth from trigg code ensur that all op hod ger res perations withi the in context o the future method are subject to Ap class limit instead of trigger of e pex ts limits. Two method si T ignatures are shown in listing 4 - 30; the fir shows a sim annotatio and g rst mple on the oth indicates th the method will perform a web service call out. her hat d Listing 4 - 30 L
// Future a / annotation in its si implest form @future @ public stat p tic void my yFutureMeth hod( ){ // Method Body d } // Future a / annotation with argum ment showing that // this met / thod will make a call m lout @future (ca @ allout=true e) public stat p tic void my yFutureCall loutMethod ){ d( // Method Body d }

future-method Salesforce Handb book


Before arch hitecting solut tions that use f future calls its important to note some of these t e im mposed limitatio ons: You c cant make mo than 10 fut ore ture calls per Apex invocat r tion. Metho annotated as future ca only take pr ods an rimitive types, collections or arrays of r primit types as th parameters. tive heir Metho annotated as future m be stat and can only have void as their ods d must tic o d return type. n Gette setter and constructors of Apex contro cannot use the annotatio ers, c oller e on. You cannot call a future me ethod from a future met thod either d directly or indire ectly. For each salesforce.com license in your Org yo can make 20 future ca per 24 n ou 00 alls hours For example if you have 100 user lice s. e, e enses then you Org has a b u bucket of 20,000 calls it can is ssue in a rolling 24-hour peri g iod.

A common pitfall conce n erns the secon to last poin above. Deve nd nt elopers will of ften mark me ethods that ar called from triggers as future. If these method then perfor DML re m ds rm sta atements there is a chance that the calling trigger might be fired agai In this case you will e t g in. e ha inadvertently created a recursive loop1 and the futu method wil indirectly be invoked ave r ure ll e by itself causing a System. y g .AsyncExcep ption to be thrown. For clarity the p r process is shown in figure 4 - 4.

Figure 4 - 4. Recursive Future C Out Call

One effecti solution is to maintain a global static B ive Boolean variab whose initia value is ble al set to false. Th value of th variable is interrogated when the tr t he his d rigger fires an if the nd appropriate the c callout is made. Within the callout method the variable value is set su that if d uch the trigger fires again the Boolean value w prevent the callout being made. Listin 4 - 31 e will e ng

re ecursive-future-ca alls Jeff Dou uglas & Wes Nol lte 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( ); } }


Salesforce Handbook

Figure 4 - 5. Control Var riable used to Pr revent Recursion n

Be aware that (unless built in) you w have no way of determ t will w mining if a future ca allout has been made in an installed mana n aged package. You thus cannot use the above des sign pattern n to avo oid the System.A AsyncExcept tion in such a case. Co ommon Syste Utility Cla em asses The Apex programming language has a number of system classe that handle common f es dev velopment tas such as par sks rsing XML or making HTTP call outs. Th reduce th amount P hese he of boilerplate co you can ex ode xpect to write, and in doing so speeds you developmen efforts. , ur nt He we will out ere tline some of the most comm monly used of these. Sy ystem Class A versatile class this is used for all th common sy u he ystem function such as determining ns sys stem time, killi and schedu ing uling jobs, debugging, unit te esting, resetting passwords an more1. g nd DO Classes OM The Docum ment Object Model (DOM) classes facilit the creatio and parsing of XML M tate on g str rings2. Usually the DOM re epresents a ne ested tree of X XML nodes. The XmlStream classes T off some low l fer level support to the DOM cl o lasses3.

sy ystem-methods dom-classes 3 xm mlstream

1 2

Jeff Dou uglas & Wes Nol lte


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 its 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


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 didnt 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, youd 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, youd 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 youve reduced your risk since triggers will always fire on DML operations and youve 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


they fa within the greater order of things. Any object-recor subjected to a DML oper all y rd o ration will move through th following ordered events: he 1. 1 2. 2 3. 3 4. 4 5. 5 6. 6 7. 7 8. 8 9. 9 The origin record is lo nal oaded from the database (or initialized for an insert statem e ment) The new record field va alues are loaded from the req quest and overw write the old v values System va alidation occu such as ve urs, erifying that al required fiel have a non ll lds n-null value, and running any user-defined v d u validation rules s All before triggers execu e ute The recor is saved to the database, b not yet com rd t but mmitted All after t triggers execute Assignme rules execu ent ute Auto-resp ponse rules exe ecute Workflow rules execute w e

10. If there ar workflow fi updates, th record is up 1 re ield he pdated again 11. If the rec 1 cord was updat with workf ted flow field upd dates, before an after trigger fire nd rs one more time (and onl one more tim e ly me) 12. Escalation rules execute 1 n e 13. All DML operations are committed to the database 1 e o 14. Post-com 1 mmit logic exec cutes, such as s sending email Y would be wise to keep the documen that detail the order of t You e nts t trigger e execution close at hand as th rules are complex and not always intuiti If e he ive. y have befor and after- i you reinsert, update, upsert and de , elete triggers o the on s same object, each data row will be subjec to their wor e ct rkings, the ord of der w which will be key. k Syntax x Trigger syntax is similar to that of Apex classes with t notable differences bein the T the ng trigger definition an a number of context v r nd variables only available wit y thin a trigger. The declara ation of a trigg adheres to the standards shown in listin 4 - 32. ger ng Listing 4 - 32 L
trigger MyT t Trigger on ObjectName (trigger_events) { e // Trigg ger Body }

In the above trigger_ev I vents is a c comma-separat list of on or more o the ted ne of follow wing:
166 Salesforce Handb book

before insert before update before delete after insert after update after delete after undelete

Observe th there is no before un hat o ndelete as t there wouldn be any data available t a before the undel operation has occurred. lete h The contex variables spe xt ecific to triggers allow your a application to determine wh type of hat trig is firing, w gger whether the tr rigger is firing, the number o records in the trigger invo , of ocation as we as access to the old and new values (i appropriate) of the record moving thr ell o if ) ds rough the trig 1. gger Triggers al lways execute in bulk i.e. ea trigger is passed a list o objects ach p of which are contained in Trigger.n , Trigge n new er.old or b both. Its therefore important to design your t i trigger code realizing that anywhere r from 1 to 200 records c be process in a single transaction. D can sed e Designing triggers thu is called m usly making them b safe and its essential t get into bulk to this habit early on or you will encounte issues down the road. e u er Listing 4 - 33 demonstr rates the usag of some tri ge igger context variables in p preventing Ac ccount names t be changed. to 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 r // Loop throug the set of Ids for all counts. Not this cod will te de // updated acc pdates // work for 1 or more up ldMap.keySe et( )){ for(Id oldId: Trigger.ol / // up pdate


the e





afte er


tr rigger-context-var riable Jeff Dou uglas & Wes Nol lte 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 changed.); e } } }

If this trigger w I were invoked via the insert DML com mmand and an Account r ny record had an error added during trigg execution the entire op n d ger peration woul fail althoug all ld gh erron neous record would be marked so. U ds Using the Da atabase.ins sert( ) method howev you could specify that pa ver artial success w acceptable1. Its also worth mentioning that was e g the sim mple compari ison functionality is purely for demons y stration and a validation ru is ule probab more apt in a real world scenario. bly n Trigger contex variables also have a numb of caveats most of whi are logical when T xt o ber s, ich given some thought2. Some import considerations are: s tant
trigger r.old and trigger.new c cannot be used in DML oper d rations.

You can only change the value of o t objects throug the trigge gh er.new variab in ble before trig ggers. Changin in it after tri ng iggers has no m meaning and will yield an err w ror.
trigger r.old is read-only. trigger r.new cannot be deleted.

R Relationship lo ookup objects in triggers are null3. So a tri igger on Child__c w will have ac ccess to all fields availa able on this object incl luding C Child__c.Pa arent__c but it w will not have access h to C Child__c.Pa arent__r.An nyField wi without query ying that o object. S Salesforce.com does this to r m reduce the over rhead involved when running data d g t through trigger Imagine the resource wast if they select all related o rs. e te ted object d for every trigger executio data t on! T There is no way to delete or deactiviat a trigger once deployed to a w te o p production Or One work rg. karound is to run your dep ployment in E Eclipse f from a sandbo (not the one you actually deployed the original code from) ox e t production. During the de to eployment pro ocess, deselect everything and then d c check the box next to De x elete for the unwanted trig gger. Executin the ng
trigger r-exceptions contex xt-variable-consid derations 3 trigger r-lookup-null
1 2


Salesforce Handb book

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<Task> reminders = new List<Task>( ); // Only execute the following code if the // hasnt been set if(!ReminderTask.haveCreatedReminders){ for(Task t: Trigger.new){ reminders.add(ReminderTask.create(t)); }

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. Well 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



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<id> ownerIds = new Set<id>( ); 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<id, User> owners = new Map<id, User>([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 maps get method to fetch the correct User object by its OwnerId and write the Users favorite color into a custom field (Owner_Favorite_Color__c) on the Account.

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 youd 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. Weve written one such unit test in listing 4 - 37. Listing 4 - 37
@isTest private class TestAccountColorTrigger { static testMethod void testBulkInsert( ) { List<account> accounts = new List<account>( ); 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=test1234@noemail.com, 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=test1234@noemail.com); 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=test12345@noemail.com, 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=test12354@noemail.com+System.now( )); insert u1; // add 200 accounts to the list to be inserted for (Integer i=0;i<200;i++) { Account a = new Account( Name = Test Account, OwnerId = u1.Id ); accounts.add(a); } // Switch to the runtime context Test.startTest( ); // run as a different user to test security and rights System.runAs(u) insert accounts; // Switch back to the original context Test.stopTest( ); // query for all accounts created and assert that // the color was added correctly for (Account acct : [Select Owner_Favorite_Color__c from Account Where OwnerId = :u1.Id]) System.assertEquals(acct.Owner_Favorite_Color__c, Pretty Pink); } }

Jeff Douglas & Wes Nolte


The above cod tests the si T de ituation in wh hich a user with the Stand dard User p profile owns a number of accounts, bu a user with the Market f ut h ting User profile permis ssions perfor the record insert. The fir few blocks of code setup the User and Profile rec rms rst d cords. Next, 200 Account records are instantiated b not comm t but mitted; then weve switched user w d contex and inserted the records as the Market xt d a ting User. T last loop is used to check that The s our as ssumption wa correct i.e. the Owner_ as . _Favorite_C Color__c field value on each Accou should be the same as th Account o unt e he owners Favor rite_Color_ field value __c e. T unit test above contains lots of unfam The a s miliar syntax th will be expl hat lained l later. The fund damentals poin to note he are that when testing tri nts ere w iggers y should thi about whi situations might cause your trigger to fire, you ink ich y o h you might setup test data to mock up these situation and what r how t p ns, results y youd expect fr rom each. Unit Testing T This topic is another conte T ender for Mo Discussed on the For ost d rce.com Discu ussion Forum and is a ke component of robust, hig ms, ey gh-quality softw output. Unit testing is not a ware U new concept and is common in most mod c i dern programm ming language One impo es. ortant differe ence is that sal lesforce.com will not allow y to deploy code to prod w you y duction that ha less as than 75% unit test co coverage. ode The primary go of unit tes T oal sting is to isola the smalles piece of tes ate st stable code (ca alled a unit) from the rest o the applicatio and determ whether it behaves as ex fr of on mine t xpected in a nu umber of situ uations. Each o these units would be teste independent before integrating them t test of w ed tly to their in nteractions. Unit testing is highly effective (bugs are dis h e scovered early on) and by its very s nature it reduces co e omplexity and increases testi rigor. For example if yo had created two ing ou d units, which need t be integrat with one another, a de to ted efect might oc ccur in any o the of follow wing: The first un nit The second unit d Both units The interac ction between the units Any of the tests

The easiest wa to find a bu in this scen T ay ug nario would b to start with the granular code be h r units. Once youre sure the units are compreh s hensively teste you can co ed onfidently test their t interac ction. Unit tests are a code, and in most case are units the U also d es emselves (don worry; you wont nt need to test them). O the Force. t On .com platform unit tests are written using Apex, and a u is m unit largely considered to be an Apex class method, o (if theyre ve simple) an Apex trigger. y o c or ery Weve introduc the What and to some extent the W W ced t e Why of unit testing and the next t e burnin question w ng would typically be How. M Most times as sking this que estion will res in sult
174 Salesforce Handb book

someone talking you through a working example, and while that is important we think that its necessary to step back and throw an analogy into the mix. Imagine that instead of building software you are coordinating the construction of a simple car. You have specialists working in teams to create each type of part e.g. the tires, brakes, chassis etc. It would be the responsibility of each team to test the parts that they manufacture i.e. the team making the tires would run tests for durability, balance, strength etc. They would do this by simulating real world situations that would make use of these parts in normal, and probably not so normal ways. Likewise each of the other teams would test their respective car parts in simulated situations relevant to whatever they made. Once all of the parts were tested and you were confident in their capacities you would start assembling the parts into more complex parts e.g. tires, rims and brakes, and apply further tests. After each successful testing-iteration you would integrate more parts until you finally had a entire car, and even then there would be some testing to do. It is much easier to test the parts of the car individually than it is to build the entire car, and then try to figure out what to test and how to abstract away the interdependencies. You can also be assured that youve tested the right situations, and that youve worked in a logical way instead of scrambling at the end trying to establish a testing methodology. If you consider that each initial car part is very simple then the tests that were initially performed would be considered analogous to unit testing. Everything beyond that would probably be considered integration and/or system testing and indirectly relies on the rigor and quality of the initial unit tests. Running Unit Tests Unit tests do not run as part of your application execution processes but instead need to be invoked explicitly. There are a number of ways to run unit tests viz. from the browser, in the Eclipse IDE, via the Web Services API or with the Force.com Migration Tool1. Each of these methods allows you to run your unit tests individually as well as executing them all at the same time. Since all of these features are well documented they will not be detailed in this book. Syntax Although some syntax will be explained within the context of code examples there are some core keywords that are important from the start. It is possible to define unit test methods in the Apex class whose methods they are testing as well as in an Apex class of their own. The case for using a separate class is strong with the following being some of the key reasons: Keeps each class smaller and more manageable Separates responsibility of classes i.e. one application code class and one test code class Although a VCS will help you merge code where developers work overlaps, keeping the test and application classes separate makes maintenance simpler

running-unit-tests Jeff Douglas & Wes Nolte 175

Code con ntained in test classes is not c c counted agains you 1MB Ap limit st pex By movin the test cod out of the c ng de class that it wil test you rem ll move the temptation to test pr rivate and pr rotected methods. Metho with these modifiers shouldnt ods be unit tested directly as that wo y ould reduce a agility when reworking public r methods.

isTest & testMetho t od Test methods d T defined in an application or a test class sh the same method signatu as a hare m ure is show in Listing 4 - 38. wn Listing 4 - 38 L
static test s tMethod voi test1( ) id ){ // Unit T Test Code }

From this exa F ample youll notice that un test metho are always static, us the n nit ods s se testM Method keywo take no ar ord, rguments, and dont have ret turn types (voi ). id T methods cannot be defi Test fined within tri iggers although you can ofte test h en a trigger by setting up test records, per t rforming the required DML and r L c checking for th expected res he sults. To define your own test cla is necessary to use the i T r ass y isTest annot tation and the class e must use the priva access mod u ate difier as shown in listing 4 - 39. n Listing 4 - 39 L
@isTest @ private cla p ass MyTest { static te estMethod void myUni itTest( ) { // Unit Test Code } }

Test.s startTest( ) & Test.stopTest( ) You will often need to create tests that ensu that your c Y e ure code can handl large dataset But le ts. one be practice pro est oponent that well discuss late is that you i w er initialize your own datasets, s this o so setup process can c consume some of the resou e urces that you need to test for. Realizing this u t g salesfo orce.com has made two methods avai ailable to you Test.sta u, artTest( ) and Test. .stopTest( ). With the co orrect entry poi ints, code that i executed bet is tween these me ethods is subject to a fresh set of Gover rnor Limits; thi allows you to prepare your test data with the is o r hin
176 Salesforce Handb book

unit test prior to testing. The limits that are applied will depend on the entry point defined between these methods. Its important to know that youll need to fire a trigger or method between these methods to give the running unit test an execution context. Listing 4 40 shows that you can execute code between these methods that will still consume the unit tests resources. Listing 4 - 40
static testMethod void myUnitTest( ) { List<Account> accounts1 = new List<Account>( ); List<Account> accounts2 = new List<Account>( ); for(Integer i = 0; i < 100; i++){ Account a = new Account(name=name+i); accounts2.add(a); } insert accounts2; for(Integer i = 0; i < 500; i++){ Account a = new Account(name=name+i); accounts1.add(a); } Test.startTest( ); insert accounts1; Test.stopTest( ); }

This test method will fail as its exceeded the Governor Limit for DML rows with the following profiling information:
Number of SOQL queries: 0 out of 100 Number of query rows: 0 out of 500 Number of SOSL queries: 0 out of 20 Number of DML statements: 2 out of 100 Number of DML rows: 600 out of 500 ******* CLOSE TO LIMIT Number of script statements: 1207 out of 200000 Maximum heap size: 0 out of 1500000 Number of callouts: 0 out of 10 Number of Email Invocations: 0 out of 10
Jeff Douglas & Wes Nolte 177

Number of fields describes: 0 out of 10 Number of record type describes: 0 out of 10 Number of child relationships describes: 0 out of 10 Number of picklist describes: 0 out of 10 Number of future calls: 0 out of 10 Number of find similar calls: 0 out of 10 Number of System.runAs( ) invocations: 0 out of 20

The fresh limits havent been applied as we have told the test what context to run them in. Now consider the code in Listing 4 41. Listing 4 - 41
static testMethod void myUnitTest( ) { List<Account> accounts2 = new List<Account>( ); for(Integer i = 0; i < 100; i++){ Account a = new Account(name=name+i); accounts2.add(a); } insert accounts2; Test.startTest( ); performDML( ); Test.stopTest( ); } public static void performDml( ){ List<Account> accounts1 = new List<Account>( ); for(Integer i = 0; i < 500; i++){ Account a = new Account(name=name+i); accounts1.add(a); } insert accounts1; }

This code executes without error and notice below that you now have two sets of profiling information, one for the unit test (with the appropriate limits) and another for the performDml method call (with Apex Class limits).
178 Salesforce Handbook

CUMULATIVE_LIMIT_USAGE LIMIT_USAGE_FOR_NS|(default)| Number of SOQL queries: 0 out of 100 Number of query rows: 0 out of 500 Number of SOSL queries: 0 out of 20 Number of DML statements: 1 out of 100 Number of DML rows: 100 out of 500 Number of script statements: 205 out of 200000 Maximum heap size: 0 out of 1500000 Number of callouts: 0 out of 10 Number of Email Invocations: 0 out of 10 Number of fields describes: 0 out of 10 Number of record type describes: 0 out of 10 Number of child relationships describes: 0 out of 10 Number of picklist describes: 0 out of 10 Number of future calls: 0 out of 10 Number of find similar calls: 0 out of 10 Number of System.runAs( ) invocations: 0 out of 20 TESTING_LIMITS LIMIT_USAGE_FOR_NS|(default)| Number of SOQL queries: 0 out of 100 Number of query rows: 0 out of 10000 Number of SOSL queries: 0 out of 20 Number of DML statements: 1 out of 100 Number of DML rows: 500 out of 10000 Number of script statements: 1004 out of 200000 Maximum heap size: 0 out of 3000000 Number of callouts: 0 out of 10 Number of Email Invocations: 0 out of 10 Number of fields describes: 0 out of 10 Number of record type describes: 0 out of 10 Number of child relationships describes: 0 out of 10
Jeff Douglas & Wes Nolte 179

Number of picklist describes: 0 out of 10 f : f Number of future ca f alls: 0 out of 10 t Number of find simi f ilar calls: 0 out of 10 : f Number of System.ru f unAs( ) inv vocations: 0 out of 20 Test. .stopTest( ) once within a unit test. n

An important consideration is that you can only use Test.sta A n u artTest( ) and

System m.RunAs( ) In a system th has variou levels of ac I hat us ccess to data records it imp portant to test that securit has been co ty orrectly applied you might n d; need to ensure that users with a certain lev of e vel privilege are the only ones that can create records of a certain type. For this pu t urpose salesfo orce.com has p provided the Sy ystem.runA As( ) method d. Y Your Apex cod usually runs in system mo i.e. recordde s ode -level and func ctional r restrictions are not taken in account. Y can chang this by usin the e nto You ge ng w with sharin keyword. U ng Using System m.runAs( ) lets you choos the se r running user-context, whethe it is for a ne or existing user. er ew u In Listing 4 3 it was show how to use this method, which would typically requir the I 38 wn e re follow wing: 1. 1 2. 2 Create a n Profile and create a new User th uses this Pr new e hat rofile, or se elect a current sy ystem User Using this User and a System.runA s S As( ) block e execute the co in question ode n. You can next System m.runAs( ) calls but only 20 calls are allowed in a single y transactio on Creating U Users within a System.Run nAs( ) doesn require that you have ava nt ailable user licen nses The origi system con inal ntext is started again after t System.r d the runAs( ) method completes s

When using thi method you should be awa that: W is u are

Settin an Exampl ng le There are a nu T umber of prog gramming situa ations that req quire the appli ication of a sp pecific testing approach. Its important to understand w g o when each migh be applied as well as what each ht a t approa is designed to achieve. ach d


Salesforce Handb book

Testing Essentials Continuing the analogy from earlier, assume youre building an application that models a car, and in doing so youve created a class called Tire. Listing 4 - 42 shows what such a class might look like. Listing 4 - 42
public with sharing class Tire { // Constant that sets the maximum pressure a tire can hold private final Integer MAX_PRESSURE = 200; // A custom exception thrown if the tire is filled too much public class OverfilledException extends Exception{} // The current pressure of the tire public Integer pressure{get;set;} // The tire constructor which takes one parameter public Tire(Integer pressure){ // If the tire is overfilled throw an exception if(pressure > 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 // units; pressure += units; // If the tire is overfilled throw an exception if(pressure > MAX_PRESSURE){
Jeff Douglas & Wes Nolte 181





thro new Over ow rfilledExce eption( E Exceeded ma aximum pressure.); } } d the tire by the units y s // Method used to deflate t // of pre essure stip pulated by the passed parameter d r public vo oid deflate e(Integer u units){ // Defl late the tire by the amount sp e pecified // if t the tire has suffici h 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 ber of unit is more than ts e // I the numb // t the current tire pres t ssure, just empty th tire. he pres ssure -= pr ressure; } } }

Essentially wev explored th property of tire pressure and some acti E ve he f ions we might want t to exp pose as methods. From the code you can see that a Ti has an in n ire nitial pressure and a maxim mum pressure, and can be inflated or d deflated. There are rules ar e round inflation and n deflation, and if a Ti is overfille it might bu i.e. an Ove ire ed urst erfilledExc ception is thrown. As a ru you need a least 3 test methods for thi class, one fo each of the public method and ule at m is or p ds anothe for the cons er structor. Y might think that testing such a simple constructor is unnecessar but You g r ry t simple act of setting up t unit test w aid in the design process. Later the the will w when other de evelopers add functionality to the const d tructor they w be will g guided by the sturdy foundat you will ha laid. s tion ave After creating such a class you need to consider how you might test each of these A w metho ods.

For the c constructor the test is simple pass in an ar e e, rgument and check that the value c of the me ember variable pressure is the same as th of argumen s hat nt.
Salesforce Handb book

For t inflate method the obvious situat the tions to test are inflating t Tire the within the maximum range, and filling it too m n m much. Other tests you migh want to t ht perfor are filling the Tire by zero units, o filling it to exactly the m rm y or o maximum pressu These las two tests a called bord case tests and are imp ure. st are der portant as develo opers often ma logical erro on these fr ake ors ringes. Testin the deflat method is similar to sim ng te milar to testing inflate. Yo want oull to test deflating the Tire by a sm amount th results in so pressure b mall hat ome being left, deflat the Tire by more units of pressure th it contains and deflating it by zero ting han units. It was men ntioned before that salesforc e ce.com require at least 75% unit test es % code cover rage but what d does this mean In short you need at least 75% of n? ull your code (excluding uni tests) to be executed by co that is inv it ode voke from within a un test. For ex nit xample in the i inflate method there are thre lines of d ee code that could be execu c uted; the line t that throws the exception wi only be e ill run by a te method if th exact condi est he itions of the su urrounding if-statement are met. If the condition isnt met on 2 out of 3 lines will be executed f n nly when the method is calle giving a cod coverage rat of 66%. m ed de te

Now that y know wh you need t test, the ne step is to figure out how to test. you hat to ext w Be efore we discu the unit tes code its wo uss st orthwhile exam mining some of the best pra o actices1 in thi regard: is For a conditional logic you nee to execute all code bran all ed nches e.g. in t above the deflate method you need to execute both th if and the else branch of the y he e hes metho body od Execu both positive and neg ute gative tests2 i test your methods wit i.e. thin their thresh holds, but also force errors to occur o Dont just catch ex t xceptions, han ndle them prop perly i.e. send an email or log the d error Alway check the re ys esults of your c code execution using Syste n em.assert Each class method should have at least one unit test method t t Comm your tests in detail stati what youre testing and th expected ou ment ing e he utcome Cover as many lines of code as yo can, although its not nec r s ou cessarily best p practice to achiev 100% ve If a b is uncovered write a unit test specifica for that bu to ensure th it isnt bug t ally ug hat accide entally reintrod duced

1 2

write-good-unit-te w ests un nit-test-example Jeff Dou uglas & Wes Nol lte 183

Each unit test should have a neatly defined test cr t h riterion and sh hould only tes one st aspect of your code at a time Unit test should functio independen of each oth on ntly her O the last point you migh find that y On ht youve hardcoded some pie of ece i information - such as a URL - into your a s L application cod and this nee to de eds c change from environment to environmen In this case consider repl e o nt. e lacing t value a Cu this ustom Setting ( mentioned in chapter 2). (as

With these poi in mind weve created th unit tests th cover the important scen W ints w he hat i narios with re egards to the T class. Listi 4 - 43 cont Tire ing tains the unit te code. est Listing 4 - 43 L
@isTest @ private cla p ass TireTes { st static testMethod void post d tiveConstru uctorTest( ) { /* Pa ass in a va alid Intege for the pressure er par rameter and check pu ublic var */ ger pressur = 10; re Integ Tire tire = new Tire(pres w ssure); he assertEqual method outputs th value of ls he f // Th System.a // bo oth parms in the even of a failure i nt Syste em.assertEq quals(tire. .pressure, pressure); } static testMethod void nega d ativeConstr ructorTest( ) { ( /* press sure */ try{ 300); Tire tire = new Tire(3 ch verfilledEx xception o){ }catc (Tire.Ov Sy ystem.asser rtEquals(o.getMessage ), e( Exceeded maximum pr ressure.); ; }
184 Salesforce Handb book

I Initialise


tir re


m more




} 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); amount // Call the member method to deflate tire by argument tire.deflate(deflationAmount); // Check that the result is as expected System.assertEquals(tire.pressure, 0); } }

Weve 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.


Salesforce Handbook

A high rate of code coverage and thor e rough unit tes sting are not n necessarily the same th hing. Its quite easy to achie high code coverage rates since all e eve s you need to do is execute 75% of the a o e application cod However a thorough de. set of unit tests might ru over the sam code many times, testing granular un me y g aspects of the functio f onality in va arious ways. The distinction and combinatio of these fac is vital, an if your unit tests are thor on cets nd t rough it is likely that you will haven more than su y nt ufficient code coverage. Da Initializat ata tion for Unit Tests T The transla ation of the car parts analogy into applicatio code does well as an introd r on w duction to the initial conce e epts of unit te esting. To adva ance your abil to effectiv test code it is now lity vely im mportant to intr roduce the best practices whe testing meth t en hods that work with object record data. Consider th simple trigg in Listing 4 - 44. This af update trig he ger fter gger adds a Ta to an ask up pdated Accoun if the Indu nt ustry is Soft tware Develop pment. Listing 4 - 44
trigger AddTasks on Account (after upd o date) { c o e // Declare a constant so that you dont have to he oure looki ing for // hardcode th value yo S nt; final String SOFT_DEV = Software Developmen t rigger will create l // The tasks that the tr sks = new L List<Task>( ); ( List<Task> tas rough all t the updated accounts d // 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 == SOFT_DEV){ ry 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 Dou uglas & Wes Nol lte 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 youre 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 youre 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).


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<Account> accounts = new List<Account>( ); // 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; // Well need this set to find at the child tasks Set<String> accountIds = new Set<String>( ); // 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 the start e tTest metho as a precaution od Test.s startTest( ); // Thi should fire your t is f trigger update accounts; e ; Test.s stopTest( ); ) // Fin the asso nd ociated tas sks for(Ta ask WHERE E tId IN :acc countIds]){ { what // C Check that the task i the one youve cr is e reated Syst tem.assertE Equals(t.de escription Convert to Cloud. n, t .); } } } t : [SELECT accountId, a ion descripti FROM task

We are assertin the same re W ng equirement in this unit test, but instead of relying on ex f xisting data we have setup our own reco w ords initially. W Weve had to insert the reco ords first, and then d perfor an update a we are testin an after u rm as ng update trigge Weve also used 200 reco er. ords in this test to ensure th the trigger is bulk safe. I is not neces hat r It ssary to write another test fo the a or case of a single DM record as bulk safe co should w o ML s ode work for any number of re n ecords (includ zero). ding D Data created within the co w ontext of a un test is onl available fo the nit ly or l lifetime of tha test. It is als only availab to that spe at so ble ecific test. Yo can ou e even delete non-test data within the co ontext of a tes without affe st fecting t same data outside of the test i.e. it is n really delete that e not ed. It is often the c that a num I case mber of unit t tests share the same setup da and it ther ata, refore makes sense to mov the data ini s ve itialization int its own me to ethod(s). For example in the unit e e test ab bove we migh have create methods to initialize account recor as is show in ht ed o rds wn Listing 4 - 47. g Listing 4 - 47 L
public stat p tic List<Ac ccount> ini itAccounts(Integer num){ n // List of account that wil be creat ts ll ted count> acco ounts = new List<Acco w ount>( ); List<Acc // Popul late the ac ccounts lis with dum st mmy data
190 Salesforce Handb book

for(Integer i = 0; i< num; i++){ Account a = new Account(name = Test+i, Industry = Software Development); accounts.add(a); } return accounts; }

Any other unit tests for this trigger can quickly get access to a list of Account objects. Note that this method has to be static in order to be used within the test method. Further Examples In addition to the core testing principles explored in this section there are a number of technology specific examples in the Force.com documentation. We highly recommend that you bookmark the examples on testing Visualforce controllers and Apex callouts1, Virtual Callout testing2, SOSL testing3 and bulk testing4. Additional Considerations Governor Limits Governor Limits in the context of unit tests are typically much tighter than for code that executes in other contexts. It is therefore key that your test code is bulk aware, or if you are testing for limits then you must use the Force.com provided Limit class to interrogate limit values. Some Limitations You cannot send emails or make web service callouts from unit test code. There are therefore two considerations here: 1. 2. How do you test methods that make use of either of these technologies? How do you test the actual email or callout?

The answer to the first question is easy for sending emails; the sendEmail method will just be skipped. For web service call outs its considered best practice to reduce the method that contains the callout to as few a lines as possible. You would then skip the callout method but test as much of the rest of your code as possible.

intro-unit-tests virtual-callout-testing 3 sosl-testing 4 bulk-testing

1 2

Jeff Douglas & Wes Nolte


To answer the second question you would need to employ integration testing as opposed to unit testing. For email sending you might outline several scenarios that vary the content of the email and manufacture a process to achieve each email type. With a web service call you would typically use external tools or setup a test endpoint to receive the method calls, testing the call content and returning appropriate responses. Test Driven Development Test Driven Development (TDD) is a development process that works within very short cycles. The premise here is that you write your unit tests first knowing what functionality you expect to deliver with your application. For example if you are asked to write a method that returns the 10 most recently created Contact records before you write the method you know that the following might occur: No records are returned 10 records are returned Somewhere between 0 and 10 records are returned

You could write unit tests to examine each of these situations. Obviously the method doesnt yet exist so the tests will fail, but then you go about writing application code that forces the tests to pass. Once that is done the code is reviewed and optimized, and the tests are run again to ensure they still pass. This process is illustrated in Figure 4 - 6. Test Driven Development is an incredible advancement in software development. It ensures that tests arent created as an after thought, but that they form a type of documentation describing the application components that you are building. It also forces developers to think through the design process in greater detail saving much time (in the form of code refactoring) later on. Although TDD results in writing more tests, it has been found that the total development time is shorter since fewer defects are introduced during the development process.


Salesforce Handbook

Figure 4 - 6. Test Driven Devel lopment

Sc cheduling Ape ex In nearly an company th will be a situation wher a particular piece of code needs to ny here re e run at certain int n tervals over a specified perio This is typ od. pical when batc operations, or timed ch , data updates are required. Salesforce.com pro ovides two me ethods of sched duling Apex1. The first m method is simp but less flex ple xible and simp requires you to click the ply u Schedule Ap pex button on the screen sh n hown in Figur 4 - 7. You c navigate to this screen b clicking re can o by
Se etup -> Dev veloper -> Apex Class ses.

Figure 4 - 7. Apex Schedu uler


using-scheduled-ap pex Jeff Dou uglas & Wes Nol lte 193

Youll be presented with a simple interface that lets 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 youll 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 Developers 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 terminate the sched l e duled uestion // job in qu ystem.abort tJob(jobId); Sy } } em.schedule method acc cepts three pa arameters. The first parame is the e eter The Syste name or descrip ption of the job youre sched b duling. The sec cond is a Str ring value rep presenting the schedule tim and uses th following fo e ming he ormat: Seconds Minutes op ptional_yea ar Hours Day_of_mo onth Mon nth Day_o of_week

The third p parameter is th class youd like to execut Figure 4 - 8 shows how t use the he te. to combination of t two classes above to schedule an Apex job. the s x

Figure 4 - 8. E Executing a Sch hedule

The syntax used in the schedule p x parameter take some time to get used t so you es to 1 ark the docu umentation . N Note that w have wrap we pped the cal to the ll should bookma Sy ystem.sched dule method in our own st tatic method m making it acce essible from V Visualforce pages too. The stop method ab bove simply stops the job wi the passed job Id. ith j To see the status of a sch heduled job yo need to lo into your Or and click Se oull og rg etup -> Mo onitoring - Schedule Jobs. Fro here you ca also alter th schedule or delete the -> ed om an he job b. A few thing to be aware of when work with the A gs king Apex Schedule are: er

ap pex-scheduler Jeff Dou uglas & Wes Nol lte 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 youll 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<sObject>{ 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; }

batch-apex-intro Salesforce Handbook


global Database.QueryLocator start( Database.BatchableContext BC){ return Database.getQueryLocator(query); } global void execute(Database.BatchableContext BC, List<sObject> 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<String> {saleforcehandbook@gmail.com}); 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 youd like to work with. Notice that the method can return either of the following:
Jeff Douglas & Wes Nolte 197

Databas se.QueryLoc cator referen Use this w nce. when the scope of your batc is a e ch

simple SO OQL query. Note that your G Governor Lim here is 50 million records mit m

An Iter rable. Used if the scope of your job is c f complex, or if you want to d define your own process of it n terating throug the list item Normal Governor Limi are gh ms. G its enforced in this case

The start method, as well a T as the oth her two, each accept ts a Datab base.Batcha ableContext object as an argument; it i this object that is used to track t n is t

the pro ogress of the b batch processin ng. The execute method does the processin for each bat that it is passed. It accep as T ng tch p pts its par rameters the D Database.Ba atchable context object a mentioned previously and a list as p d of sObjects o parameter or rized types. If you h have chosen to work with Datab base.QueryL Locator then the list retur n rned by the sta method sho art ould be used a this as second parameter. d The finish meth as its nam implies, wil be used for a post proce T hod, me ll any essing activities such s as send emails. ding T allow callouts from your batch class y To r youll also need to implemen the d nt D Database.Al llowsCallou uts interface. If youd like to maintain state e i information across batc ches youll need to implement the D Database.St tateful interface. Once youve cr O reated your cla you need a way to execut the batch an for that youd use ass te nd the Da atabase.exe ecuteBatch method. Listin 4 - 50 show such an exam ng ws mple. Listing 4 - 50 L
// Query to fetch app / o propriate r records String quer = SELEC id, name industry FROM Acc S ry CT e, count WHERE in ndustry = \Informati \ ion Technol logy\; // Instanti / iate your batchable c b class UpdateSObje U ectField up pdateField = new Upd dateSObject tField( query, industry, IT); , // Invoke t / the batchin process ng Database.ex D xecuteBatch h(updateFie eld);

Some importan consideratio are: S nt ons Each batc is discrete in its executio i.e. if the d you subm is broken i ch on data mit into 2 batches a execution fails during ba and atch 2, all chan nges made in batch 1 will still be persisted.
Salesforce Handb book


As with Scheduled Apex its 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 youll 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 jobs 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 weve mentioned Governor Limits and best practices in avoiding some of them its time to step back and go into a bit more detail about why they exist and how they work. Weve explored some of the detail regarding why such limits exist noting that in a shared environment its key that each community member doesnt 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 of Governor Li f imit

Apex Entry Points The Apex entr point can be described as the application area where the code was first T ry b s e invoke For examp if a web ser ed. ple rvices method is called and t in turn cau a trigger t fire this uses to the Ap entry point is the web service context. Apex can be in pex t nvoked in the following way ys: Apex Trigg ger Apex stand dalone class Apex web s service Anonymou block us Visualforce page controll (or extensio e ler on) Unit Tests

The official documentation describes the lim based on entry point in detail1. T d mits n As an example consider a class that is call from a trig A e led gger as well as a Visualforce page s e contro oller. When inv voked by the controller the class can issue up to 100 SO c e OQL queries. I it is If called from a trigger however it can only issue 20 n 0. Its essential to know that any other code or triggers th run based on the entry point I o a e hat invoca ation will contr ribute to total consumer res sources i.e. if a web service is called and in turn i n fires a trigger as well as calling a method in a util class, all co and data ac l m lity ode ccessed throug the gh trigger and utility cla will contribute towards th Governor L r ass he Limit. Data Volume V Some Governor Limits scale with the am S mount of data being proce a essed. For exa ample the lim on DML rows when th entry poin is a trigger is 100. If you were to pas the mit he nt u ss trigger batches of 1 rows the limit becomes 1000; if your batches are 100 records in size r 10 r 1 n the lim is 10,000. Effectively th limit is the batch size m mit his e multiplied by th listed Gov he vernor Limit. W When reworking very large datasets - dur ring paginating for example - you g c often achie much faster results by u can eve using client-sid languages su as de uch F Flash or JavaS Script2 to per rform any ma anipulations. This has the a T added a advantage of sk kipping any co oncerned Gove ernor Limit im mpositions. Gover rnor Limit Ty ype Different limit types have dif D fferent values b the differen between th types isnt a but nce he always obviou to beginner For exampl the limit fo Total numb of SOQL queries issued for us rs. le, or ber d
1 2

govern nor-limits client-side-data-manipu ulation Salesforce Handb book


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. Weve also lightly discussed how this can be used to step around certain Governor Limits. Exploring this in a bit more detail, youd typically invoke code asynchronously when there is a large amount of processing to undertake and you dont 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 its own. By doing this you save the user time, and that thread starts its 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 havent covered yet is how to populate these logs with data that you think is important when debugging. Although weve 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
1 2










too-many-dml-rows system-log-console 3 howto-view-debug-logs 4 understanding-debug-logs 5 debug-log-filters Jeff Douglas & Wes Nolte 201

System.debu S ug(LoggingL Level.FINES ST); // Sample d / data initia alization List<Accoun L nt> accoun nts = [SEL LECT id, n name FROM Account LIMIT 10]; Map<Id,Acco M ount> accou untMap = ne Map<Id,Account>( ew [SELECT id, name FROM Accoun LIMIT 10 F nt 0]); // Output a DEBUG le / at evel System.debu S ug(List of accounts: + accounts); f : // Output a INFO lev / at vel System.debu S ug(Loggingl level.INFO , Map of accounts and Ids: + accountM Map);

The method w a single par T with rameter implic sets the lo citly ogging level to debug. Notice how e the log gging levels are correlated to the filter opti e o ions when deb bugging? Using logging levels, you g contro what outpu is seen when a certain log filter is a ol ut applied. Logging levels obe the ey follow hierarchy ( wing (from lowest to highest): ERROR WARN INFO DEBUG FINE FINER FINEST

That is, any deb messages set with a leve of ERROR will always app in the log but T bug el pear gs, messag set with a lo ges ogging level of FINEST are o output if t debug filter is set to Finest. f only the r W While calls to System.deb are not co S bug ounted for unit test code cov t verage t they do each count as a li against the Scripted Sta ine e atements Gov vernor L Limit.

The View V
With the Mod and Contr W del roller parts of MVC out o f the way its time to deta the f ail View. The View on the Force.co platform can be create in one of two ways; the page n om ed t layout seen in ch ts hapter 2 or highly custom h mizable Visua alforce pages. Visualforce is a e
202 Salesforce Handb book

component-bas ed framework for the For k rce.com platfo 1. It is us an XML t orm ses tag-based lan nguage to bu uild dynamic components and pages that are rendered as HT TML and Jav vaScript at run ntime. The langua includes a large, well-doc age l cumented com mponent library as well as the ability to y e cre eate your ow components. Standard and custom components include a nu wn umber of convenient func ctions familia in most fr ar front-end lang guages, as we as baked-i AJAX ell in fun nctionality. Ad dditionally you can include a amount of HTML and Ja u any avaScript in V Visualforce pages allowing f the creation of sophistic for cated, modern user interface These inter es. rfaces can als be context a so aware in that they render di t ifferently when viewed on different device such as n es sla computers or mobile devi ate ices. Th System Arc he chitecture Figure 4 - 9 shows the Visualforce syst architectu for develop while Figu 4 - 10 V tem ure pers ure demonstrates the same system for users. e

Fig gure 4 - 9. Visua alforce system ar rchitecture as ex xperienced by a developer

When deve eloping Visualforce pages th source code is sent to the application s he e server for e t compilation (on every save by default). Here it is checked for errors, and if none exist it passes e age he tore as well as to the page renderer. The renderer s e the compiled pa code to th metadata st parses the Visual lforce code ou utputting the re esulting HTML page. L

in ntro-visualforce Jeff Dou uglas & Wes Nol lte 203

Figure 4 - 10. Visualforce system architecture as exper rienced by an en user nd

End users woul skip the com E ld mpilation step n necessary with developers. In nstead a page re equest is issue to an applica ed ation server, wh is passed a hich along to the me etadata store. From here the s F stored page definition is passed to the page renderer, whic outputs the resultant HTM page. d e ch ML As mentioned previously the components of an MVC f A e framework are decoupled in their e n interde ependence but it is necessar to bind them together to achieve the desired function t ry m nality. The tie between view and model here is achiev through th controller, which also pro w ved he w ovides the cor application logic. These co re ontrollers take a number of f e forms namely: The standa object cont ard trollers (these a automatica generated) are ally Apex contr roller extension with object standard cont ns trollers Custom controllers writte in the Apex programming language en x g

Knowing when to use each is largely based on experience but the follo K n d owing rules go some way to owards assisting in the decisio on-making: g Standard controllers on objects funct n tionality such as data views, data creation data , n, modificat tion and data deletion. Since they are aut tomatically gen nerated you d not do need to w write any Ape code, creat any unit tests or underta any of the risk ex te ake associated with writing your own cod Use this co d de. ontroller type when your inte w ention is to displ and edit inf lay formation spec to an obje and any of its related obje cific ect ects Use contr roller extensio when your pages need to be object-sp ons r o pecific but there are additional features requ l uired that could be expose with standar controllers a dnt ed rd alone. Controlle extensions require a const er tructor that acc cepts as a para ameter the stan ndard controller that it is exten r nding.
Salesforce Handb book


Custom controllers will be required on pages that arent 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 its 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
<apex:page standardController=Account> <apex:form> <apex:pageBlock title=Edit Account for {!account.name}> <apex:pageBlockSection > <apex:inputField value={!account.name}/> <apex:inputField value={!account.industry}/> </apex:pageBlockSection> <apex:pageBlockButtons > <apex:commandButton value=Save action={!save}/> </apex:pageBlockButtons> </apex:pageBlock> </apex:form> </apex:page>

Visiting this page in a browser would render an HTML document as shown in Figure 4 - 11.

mvc-visualforce Jeff Douglas & Wes Nolte 205

Figu 4 - 11. MVC Working Toget ure ther

Notice how the model, view and controller c N e a come together to create a pag that allows y to ge you manipu ulate persisted information. From the code listing, the Ac F e ccount objects standard con s ntroller fulfills the controller role. The ab r bility to fetch o object field valu as well as th save action all fall ues he into th controllers domain. The Ac he ccount object it tself, along with the data it holds is the mod in h del this case, and the Visu ualforce marku (including co up omponents) for the view rms . W When starting out with Visualforce d g development it will be h highly a advantageous if you use the Development Mode Footer mentioned e i t r earlier. I using this environment a of your too (including reference mate In e all ols r erials) a in the sam convenient location, and youll have ac are me ccess to Visualforce c code completio as well as h on helpful functionality e.g. it will provide a hotlink w t create a con to ntroller extensi if you refe ion erence one that does not yet exist. t A Additionally ev very time you save the results of your coding effort are u ts p present in the same window giving you instant results. s When would you u Visualforc n use ce? Standard pages are good for creating, displaying and editing data sto S s r ored in standa or ard custom objects. You can quickly manipulate the field layouts with the layo editor, but there m u m e out will be times when y need an ad e you dditional field on the page t that doesnt ne to be associated eed


Salesforce Handb book

with an object. Or perhaps youd like to include, for instance, visually complex dashboards in your standard pages. These situations call for the use of Visualforce pages, although it isnt 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, youd 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 arent 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. Its intuitive for beginners and works well. When youre more comfortable with the Force.com platform youll 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


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
<!-- The page tag starts and ends the page definition --> <!-- Note the attribute that declares I will be using --> <!-- the Account object standardController --> <apex:page standardController=Account> <apex:sectionHeader title=Account Edit/> <apex:form > <!-- Retrieve the name for this Account --> <apex:pageBlock title=Edit Account for {!account.name}> <!-- Standard structural and styling component --> <!-- Controls data presentation -->

standard-controllers Salesforce Handbook


<apex:pageBl lockSection > n <!-- Inte elligent in nput component --> <apex:inp putField va alue={!account.name e}/> <apex:inp putField va alue={!account.indu ustry}/> BlockSectio on> </apex:pageB <!-- Standar structur rd ral and sty yling compo onent --> ppropriatel --> ly <!-- Groups buttons ap apex:pageBl lockButtons > s <a <!-- Butt ton used to call controller lo o ogic --> <apex:com mmandButton value=Save actio n on={!save}/> BlockButton ns> </apex:pageB x:pageBlock k> </apex </apex:f form> </apex:p page>

Note that a code betw any ween the <!-- --> symbo are commen and will be ignored ols nts (an in fact strip nd pped out) by th compiler. he rst t e g In the fir line of the code we are opening the page tag and setting the st tandardCont troller attri ibute equal to Account. T This is how yo associate an objects ou n sta andard control with a Vis ller sualforce page This means that you can now access any of the e. ob bjects available fields as well as any standar controller m e rd methods. Further on weve used {! n !account.name} to retrie and display the value of the name eve y fie for the obje record in qu eld ect uestion. Near the en of the code weve used a commandBut nd e tton compon nent that make a call to es a save function b using the sy s by yntax {!save . As the met e} thod name sug ggests this will save any l rec cord changes. Even though weve used the same com d mponent (inpu utField) for both the r Account na and indu ame ustry fields, w when the page loads the nam field is e me rendered as a text inpu while the in a ut ndustry field is rendered as a list of i s selections. This intelligen feature is a big time save but be awa that it nt er, are will only work with objec fields i.e. u w cts using a control property declared as ller a data typ that isnt a object will only ever result in the field being pe an rendered as a text input. This page can be used in two contex either reco editing or record creatio If the i xts, ord on. above page were named MyPage then you w e would request th page using the following U he URL:
https:// /[salesforc ce_domain]/ /apex/MyPag ge
Jeff Dou uglas & Wes Nol lte 209

All you would need to do is enter a value in the name f A field, click the Save button and a new Account record would be crea A d ated. In order to use this page for editing, the Id of a record needs to be specified as a URL I e r d parameter. You wou need to use uld e: Take note that the Id specified must refer to an object record type tha is the same a the T at as object standard con ntroller type specified in th page1 i.e. f MyPage above only a valid s he for Accou record Id w unt would result in a properly ren ndered page. W Weve used th syntax {!a he account.fie eld_name} to refer to Account o r record fields for both read and write ope f erations. This takes some g getting u used to but it results in conci intuitive co r ise, ode. You will have gathered by now the {![ac Y ction | object.field d_name]} syn ntax is used to refer to con t ntroller variabl and metho Not only can you use this syntax to work les ods. t with st tandard contro oller object fie elds, but you can also travers relationship quickly; for childse ps to-pare relationshi you can in ent ips nterrogate up to five childre deep e.g. a page that use the en es Contac object stand ct dard controller you can use {!contact.a r account.own ner.firstname} validly y. For par rent-to-child relationships you can traverse one level e.g. s n {!acc count.conta acts} would return a list of contacts asso f ociated with th Account tha is in he at contex xt. Standard List Cont trollers Standard List C S Controllers are used to creat Visualforce pages that disp and act on sets e te play of data Examples of standard pag that use list controllers ar list pages, related lists, and mass a. f ges t re d action pages. Stand dard List Con ntrollers can b used with most, but no all objects. The be ot follow objects are permissible: wing e

https://[sa h alesforce_d domain]/ape ex/MyPage?id=[Accoun Record i nt id]

Account Asset Campaign Case Contact Contract Idea Lead Opportunit ty

standa ard-controller-tut Salesforce Handb book


Order Product2 Solution User Custom objects

In order to specify that a page uses a list controller and the attribute recordSetVar is required in the page component declaration. Such a page is shown in Listing 4 - 54
<!-- The recordSetVar denotes that this page uses a standard -> <!-- list controller. The associated value is used to refer --> <!-- to the elements in the list --> <apex:page recordSetVar=accounts> <apex:form > <apex:pageBlock > <!-- Any error messages will be displayed using this --> <!-- component --> <apex:pageMessages /> <!-- This component will group the selection items. --> <!-- In this case a label and a select list --> <apex:pageBlock > <apex:panelGrid columns=2> <apex:outputLabel value=View:/> <!-- The list of view options --> <apex:selectList value={!filterId} size=1> <!-- This action support component will rerender the --> <!-- table of values is the selection changes --> <apex:actionSupport event=onchange rerender=acc_table/> <apex:selectOptions value={!listviewoptions}/>
Jeff Douglas & Wes Nolte 211


</apex:selectList> </apex:panelGrid> </apex:pageBlock> <!-- The action buttons for your page - a save button --> <apex:pageBlockButtons > <apex:commandButton value=Save action={!save}/> </apex:pageBlockButtons> -> <!-- Table element for the accounts that will be displayed <!-- Referred to the recordSetVar and will iterate --> <!-- over each item --> <apex:pageBlockTable value={!accounts} var=acc id=acc_table> <apex:column value={!acc.name}/> <apex:column headerValue=Account Number> <apex:inputField value={!acc.accountnumber}/> </apex:column> <apex:column headerValue=Industry> <apex:inputField value={!acc.industry}/> </apex:column> </apex:pageBlockTable> </apex:pageBlock> </apex:form> </apex:page>

The code is commented appropriately but notice how we have declared a iterate over each item in the list. Here you can see that its 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 weve 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.
recordSetVar in the page element and used this later in a pageBlockTable element to


Salesforce Handbook

Figure 4 - 12. The Render Standard Lis Controller Page red st

In addition to the two methods abo n ove, there are other action available to specific e ns o components wh hen using Sta andard List C Controllers1 t that control save-behavior and list nav vigation. Another notable component in this page is pa n s ageMessages. If any s standard or validation er o rrors occur on the page the will automa n ey atically be displayed in the position of this tag. This compon i n nent is availab for all ble controller types. t st viously quite s simple but you often wan to navigate to such a ull nt Creating lis pages is obv page from one o the standard object pages2. In this case a youll need to do is specif that the of d all fy custom button th is added to your standar page have a Display Ty of List Button, hat o rd ype and on your list p page use the {!selected} expression to access the rec o cord collection n. The follow considerat wing tions are impor rtant when wo orking with Sta andard Set Con ntrollers: Only 10,000 records can be return by a list co ned ontroller If no filter is specifi then the las used filter fo the object is used ied st or s Recor sort on the first column o data rds e of You can traverse relationships in the same w and to the same degree as with r n way Stand Controller dard rs Tabs can be overrid dden with Stan ndard List Con ntroller pages in the same wa as with i ay Stand Controller dard rs

Co ontroller Exte ensions There is a lot of overlap in the detail of Controller Extensions and Custom Controllers p alt though the for rmer serve as a neat introdu uction to the la ater. Each are implemented using the Ap programm pex ming language and have all of the langu uage features available to th a hem. The
1 2

st tandard-list-contr roller-actions cu ustom-list-button ns Jeff Dou uglas & Wes Nol lte 213

dividin line betwee the two is in the way eac is initialized and the situations that make ng en i ch each appropriate to u use. Controller Ext C tensions are used to augme the functi u ent ionality provid by Standa or ded ard Custom Controllers. Standard Con m . ntrollers have a number of v valuable featur so if your a is res aim to add a few small actions (such as a web serv call) to an otherwise si d vice n imple page you can create a Controller Extension and add it to th page. You might conside creating Cu he er ustom Contro extension when you have functional that you ne to reuse in a number of areas oller ns h lity eed n f and th functionalit can be neatly packaged int an extension hat ty y to n. I is of the utm importan that you remember that Custom Contr It most nce C rollers a Controller Extensions o and r operate in system mode i.e. they ignore pr rofileb based permission and field-level security. To force ad . dherence to a users p permissions an security wit nd thin these clas you must declare them using sses t with sha the aring keywor rds. Strictly speakin a Controlle Extension is any class that has at least one constructo that S ng, er s t o or accept ts a single argument of either ApexPages e s.Standard dController or r Custo omControlle erClass wh here CustomC ControllerClass is a class that y youve defined as a page con ntroller. D not define Controller Ex Do xtension metho with the sa name as a of ods ame any t Standard Controller act the tions e.g. save The page will not be ab to e. w ble d determine whic controller m ch method you wi to call (would you?). As o the ish of c current version it will favor t Standard C n the Controller meth hod. Listing 4 - 55 shows the cont L troller extensio and Visualfo page code on orce e. Listing 4 - 55 L
public with sharing class Contr p h c 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 record used in the Standard t Contro oller */ public C ControllerE Extension( ApexPa ages.Standa ardControll ler stdCont troller) { // get tRecord( ) returns an sObject s you need to cast n so d // the object ap e ppropriatel ly
214 Salesforce Handb book

contact = (Co ontact)stdC Controller. .getRecord( ); ( } /* get and set parts of gette s ers and set tters are i ignored The in ca alls from Visualforce pages. V e */ publi String getHelloWor ic g rld( ) { ret turn Hello + conta o act.firstna ame; } } age standar rdControlle er=Contact t <apex:pa exten nsions=Con ntrollerExt tension> <h1>{!he elloWorld}< </h1> <apex:fo orm> <apex x:pageBlock k> <apex:pageBl lockSection n> <apex:inpu utField value={!con ntact.first tname}/> <apex:inpu utField value={!con ntact.lastn name}/> <apex:comm mandButton value=Sa ave action n={!save} /> BlockSectio on> </apex:pageB ex:pageBloc ck> </ape </apex:f form> </apex:p page>

The extens sion source co demonstr ode rates how to retrieve the object record from the o controller object Your extens t. sion then has access to the object that the standard con ntroller is wo orking with. Lo ooking at the code for the p page you can s that its possible to refer to all the see fun nctionality of t Standard Controller as w as that of th Controller Extension. the C well he Controller Extensions can only reference object fields that are used in the page. E n e t n For examp if the ab ple, bove Controlle Extension tried to refer er rence the createdD Date field of th Contact o he object record we would receiv an error w ve message sa aying SObject row was retrieved via SOQL without t querying the reque g ested field Contact.CreatedDat . To use d: te object field in Controlle Extensions t ds er that arent in your page you need to y ll
Jeff Dou uglas & Wes Nol lte 215

fetch them with an SOQL query, or include them in an inputHidden component in your Visualforce page. It is possible to add more than 1 controller extension to a page. This is achieved by comma-separating the list of extensions like so, extensions=Ext1, Ext2. If two or more extensions have methods that share the same name, preference is given to the first extension in the list. Be aware of the following considerations when building Controller Extensions (and Custom Controllers): DML is not allowed in getters (any method whose name starts with get), setters (any method whose name starts with set) or class constructors The future annotation is not allow in getters, setters or class constructors Primitive Apex data types are passed by value. Lists and non-primitive data types are passed by reference1 You cannot predict the order in which methods and variables are processed in Custom Controllers or Controller Extensions. If a method relies on the execution of other code be sure to include it in the constructor or call it directly from your method

Custom List Controllers This type of controller has much in common with both Standard List Controllers and Controller Extensions, most of which has already been covered2. To use Custom List Controllers as Custom Controllers ensure that at least one method that works with the ApexPages.StandardSetController object. You can tailor this object to iterate over custom sets. If youd like to integrate a Custom List Controller with a Standard Controller youll need to include it in your page as an extension. To use it as a Custom List Extension your class needs to accept an ApexPages.StandardSetController argument in its constructor instead of the ApexPages.StandardController. Custom Controllers When business requirements demand a high level of complexity you should consider using Custom Controllers3. These controllers are used to completely implement business logic, integration and data activities required in Visualforce pages. They are the most flexible of all the controllers, but are often (necessarily) involved and require you to consider testing and security in their designs.

by-value-or-by-reference custom-list-controller 3 custom-controller-tutorial

1 2


Salesforce Handbook

To designate an Apex class as a Custom Controller it is necessary that it have at least 1 constructor that has zero arguments1. Listing 4 - 56 outlines the source code of a simple Custom Controller. Listing 4 - 56
/* Using the with sharing keywords guarantees that profile permission and field level security will be honored in this class */ public with sharing class CustomController { // This denotes a public property which is // a type of shorthand for getters/setters public Account account{get;set;} public CustomController( ) { // Get the object Id from the page parameters String id = ApexPages.currentPage( ).getParameters( ).get(id); if(id<>null){ // Fetch the account record account = [select id, name from Account where id = :id]; }else{ // Instantiate a new account account = new Account( ); } } // Save the account record public PageReference save( ) { // completed upsert account; PageReference pr = System.Page.ControllerExtension; return pr;











custom-controllers Jeff Douglas & Wes Nolte 217

} }

The if-statemen in the zero-argument con T nt nstructor chec for a reque parameter called cks est Id. If it finds a val it fetches th record with that Id from the database. If the paramete has I lue he h I er no value it instantiat a new Acco tes ount object. In this way we have created a controller tha can n at be use to either edi or create new Account rec ed it w cords. The pag that uses th controller c be ge his can seen in Listing 4 - 57 n 7. Listing 4 - 57 L
<apex:page controller < r=CustomCo ontroller tabStyle= =Account> > <apex:form> < > <apex:pag geBlock title=Detai ils for {!a account.nam me}> <apex:pageBlockS Section > ield value= ={!account t.name}/> <apex:inputFi ield value= ={!account t.industry}/> <apex:inputFi dButton act tion={!sav ve} value= =save/> <apex:command x:pageBlock kSection> </apex </apex:pa ageBlock> </apex:form < m> </apex:page < e>

The notable p of this pa T part age is the pa componen controll age nts ler attribute. This . instruc the page to use the specif Custom Controller. cts fied F Force.com pro ojects do not have namespace so it is nece es essary to use na aming c conventions to organize your code effectiv o r vely. In our ow projects we often wn u use [name_of_pr roject] [class s_description] [Controlle er|Ext]. .cls to orga anise our classes. So if we were w working on an Answers pro n oject and we c created a cont troller class us to sed e edit and save Answer A re ecords we ed name it A AnswersEdit tController r.cls. It is worth not that the co I ting onsiderations l listed previous for Controller Extension also sly ns hold tr for Custom Controllers. rue m Controller Methods Controller and extension me C ethods that are directly acces e ssible in Visual lforce pages ca fall an into th following ca he ategories:


Salesforce Handb book

Getter Setter Apex Property Action

Getters and setters expose and relay data between a page and controller whilst action methods are use to encapsulate and execute business logic as well as control navigation on page events1. Properties are similar to getter and setter methods although their syntax is quite different. Getters & Setters Getters are methods that pass controller values to Visualforce pages. For any controller value to be used in a page, even if it isnt display, a getter method is required. Methods of this type are required to have a name that starts with get, and must have a return type. When calling a getter within a Visualforce page it is necessary to omit the get part of the method name. For example a method declared with the name getName would be referenced in the page as {!name}. Setter methods perform nearly the opposite function of getters. They pass user-specified or calculated values from the Visualforce page to the controller. It is guaranteed that setter methods will be called before action methods are executed. It is not required that you supply a setter methods for each getter listed in your controller. For those getters that do have an partnered setter method i.e. the setter method for getName would be called setName, the {!name} syntax will call the getter on page load (or AJAX refresh), and it will call the setter on form submission. Note that setter method names must start with set. Apex Properties Properties are conceptually somewhere between variables and getter/setter methods2. In Listing 4 - 56 for example weve denoted a property with a get and set accessor on the account variable. Here the property serves as shorthand for both the getter and setter and a Visualforce page can work with the variable using the same {!account.field_name} notation. Action Methods These method types are the event handlers for buttons, JavaScript events, page loads etc. Their return type is either void or a PageReference object with the former resulting in a page refresh. Thus action methods often result in navigation to a page, even if its the page the event is initiated from. In Listing 4 - 58 weve defined an action attribute for the commandButton component. The value of this attribute is set to {!save}; this means that when the button is clicked a method called save will be invoked in the pages Custom Controller.
1 2

controller-methods apex-properties Jeff Douglas & Wes Nolte 219

The following components support the action attribute:

commandButton - creates a button that calls an action commandLink - creates a link that calls an action actionPoller - periodically calls an action actionSupport - makes an event (such as onclick or onmouseover) on another named component call an action actionFunction - defines a new JavaScript function that calls an action page - calls an action when the page is loaded

Salesforce.com has also simplified the use of AJAX for partial pages refreshes. To demonstrate this weve modified the source code from previous code listing as shown in Listing 4 - 58. Listing 4 - 58
<apex:page controller=CustomController tabStyle=Account> <apex:form> <apex:pageBlock title=Details for {!account.name} id=TheBlock> <apex:pageBlockSection > <apex:inputField value={!account.name}/> <apex:inputField value={!account.industry}/> <apex:commandButton action={!save} value=save rerender=TheBlock/> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>

Weve made two small changes: The pageBlock component now has an Id attribute The commandButton component includes a rerender attribute whose value is the Id of the pageBlock

Clicking on the button now would not redirect the user but would instead just refresh the pageBlock. The return type of the action method is thus ignored and the new changes are loaded more quickly.
220 Salesforce Handbook

Testing Custom Controllers & Controller Extensions Both Custom Controllers and Controller Extensions are comprised of Apex code and its therefore necessary that they their public methods are unit tested1. Much of the testing practices covered earlier are applicable here too, but unit test initialization works a little differently. An important difference is that controllers often expect request parameters and so to test them requires that unit tests be programmatically set with dummy values. To this end you can initialize a PageReference object setting parameter values and then assign this object to the Test.setCurrentPageReference. Doing this tricks your application code into thinking that its running under real world conditions allowing you to test appropriately. Listing 4 - 59 illustrates a contrived unit test for the Custom Controller shown previously. Listing 4 - 59
static testMethod void customControllerTest1( ){ // Initiate the PageReference object PageReference pr = System.Page.CustomController; // Initiate the test data Account a = new Account(name=Test); insert a; // Assign the page parameter pr.getParameters( ).put(id,a.id); Test.setCurrentPageReference(pr); // Instantiate the custom controller. This // mimics the page load CustomController cc = new CustomController( ); // Check the result System.assertEquals(a.name, cc.account.name); }

Visualforce Page Syntax As mentioned previously Visualforce markup is standards compliant XML compiled and rendered using Force.com technologies. Having detailed the various types of controllers and how the constituents of this MVC framework work together it is now appropriate to learn more about Visualforce page syntax. Visualforce pages can include any bespoke HTML and JavaScript you wish to include. You can mix these with the Standard Component library or you can define your own set of

custom-controller-tests Jeff Douglas & Wes Nolte 221

Custom Components, which themselves can include HTML, JavaScript or Standard Components. Standard Component Library The standard component library consists of XML components that accept a number of required or optional attributes. These provide the component with additional instructions on how to behave and/or look. Components can be used for input, output, organization or to execute actions. Although the library is well documented1 it is valuable to highlight some of the more common elements. As a requirement each Visualforce page must include the page tag, which as youve seen is written like so: <apex:page> </apex:page>. Weve also demonstrated some of the attributes that this component accepts such as standardController, extensions, controller, action etc. Output Components Components in this grouping are used to present read-only information to end-users. Many of them also provide automatic. The detail component outputs the entire detail page as defined by the page layout for a particular object
outputField, outputLabel, outputLink and outputText are used to display data, labels or links on a page. Nesting outputField components in pageBlockSection components equates to nesting a pageBlockSection item in a pageBlockSection message and messages are used to output any information such as error details in

a page. The former is used to target a specific component and the latter is a catch-all

pageMessage and pageMessages are similar to the previous components but have additional attributes to control when and how error messages are displayed. They both use standard salesforce.com styling for display

that is the subject of the Visualforce page. For each related object you can specify one of these components
actionStatus components can be referenced from action components and

relatedList components output the records that are related to the parent record

provide the user with feedback during an AJAX activity. For example, if a user clicks a button the actionStatus component can output the message Working while the action is being executed. Input Components These components allow users to enter data, which you then capture through the use of a page controller.

standard-component-library Salesforce Handbook


inputText and inputTextArea are useful when getting text input from a user. The latter is typically used when you expect long string inputs. The inputTextArea is also capable of rendering as a WYSIWYG editor by setting richtext=true

Use inputSecret to mask what the user is entering, as with password fields when action methods are executed. As an example you might use this component when passing state data to the controller
inputHidden is not displayed on the page but is used to submit data with forms

inputField is an intelligent input component in that when it is bound to an

object field it is will determine the field type and render appropriately Use inputFile when you want to allow users to upload files

inputCheckbox will render as a checkbox on a Visualforce page. selectRadio

will display radio buttons

The selectList and selectOption/selectOptions components can be used to render combo boxes (called picklists on the Force.com platform)
param components are usually nested in other components such as commandLinks. They can be used to assign values to controller setters (or

properties) explicitly or they can be referenced by their name attribute value through the PageReference object Organizational Components

The page component is the ultimate organizational component and is the root tag of any Visualforce page
pageBlock, pageBlockSection and pageBlockSectionItem are usually

nested in the order listed. The first two are used to break pages into logical groupings with optional titles and subtitles. pageBlockSectionItem is used to group labels and output (or input) components such as outputText (or inputText).
dataTable and pageBlockTable are used to iterate over datasets and can be

used to create tables of output or input items. Use the former when you want a greater degree of control over the table styling. pageBlockTable can be nested in pageBlock or pageBlockSection components where they will inherit automatic styling in the chosen manner. Both input and output components can be nested in their bodies
panelGroup is nested in panelGrid to organize information into table rows and dataList and repeat iterate of sets of data and can be used to display each record


Jeff Douglas & Wes Nolte


outputPanel is used to group page items either within HTML span tags (default) or in div elements by setting layout=block. This component is often used to wrap page areas that will be the target of a rerender

Any components that call action methods, together with input components that youd like to submit on the action invocation, must be contained within a form tag. Best practice dictates that you should only use one form per Visualforce page. If you need more than one form in a page you can split the form into sub-forms using the actionRegion component1.

Action Components As mentioned earlier these components allow the user to do things like save, edit or navigate.
commandButton - creates a button that calls an action commandLink - creates a link that calls an action actionPoller - periodically calls an action actionSupport - makes an event (such as onclick or onmouseover) on another named component call an action actionFunction - defines a new JavaScript function that calls an action page - calls an action when the page is loaded

Custom Components Standard components encapsulate functionality in such a way that theyre reusable in any Visualforce page you create. If you find that you commonly require a chunk of Visualforce markup in multiple areas of your application you might consider breaking it out into a custom component. For example your application might use a specifically styled banner in many application areas. Since the core Visualforce code is repeated and only the message changes you could create a custom component that encapsulates the core code, and instead make a 1 line call to the component instead2. Listing 4 - 60 shows the source code for such a component. Listing 4 - 60
<apex:component> <apex:attribute name=icon type=String description=The URL to the banner icon image /> <apex:attribute name=title type=String description=The banner title text required=true />

1 2

multiple-forms-single-page define-custom-component Salesforce Handbook


<apex x:outputPan nel layout= =block> --> <!-- Only di isplay the icon if t the attrib bute is pop pulated icon} rend dered={!LE EN(icon) > 0} <apex:image value={!i loat:left; padding:0 3px /> style=fl float: left t>{!title}</h2> <h2 style=f ex:outputPa anel> </ape </apex:c component>

The comp ponent markup is very sim p milar to Visua alforce page markup1. The obvious m e dif fference is th instead of using the page compon hat f nent the root element of a custom co omponent is the component tag. Readin the docum ng mentation for this compone 2 youll ent no otice that comp ponents, like pages, can have controller an extensions3. The use of ob p e nd bjects and the methods in components is identical in V eir n i Visualforce pag and Custom Components. ges If youre attempting to perform D o DML within a Custom Co omponent controller but are getting a DML not allowed erro youll need to set the b g t or allowDML attribute of c L component to true. In the exam mple weve als included th option attri so he ibute compone - of which you can ent h hav any numbe The attribu componen is used to pass informat ve er. ute nt tion to the co omponent ma arkup, contro oller or extension. The markup can reference attributes u n using the {!attribute_ _name} notat tion while the attributes can pass their as n ssigned values to Apex s 4 code using the a assignTo={!setter_m method} attr ribute . Each attribute requ uires three tag viz. name, t gs type and description. All that is required to use this comp u ponent is to in nclude <c:Ba anner title e=Some Te ext /> in yo page. Noti that its onl mandatory t pass the com our ice ly to mponent a valu for the ue titl attribute as it has been ma le arked as required. In Figure 4 - 13 shows a Visualforce page that has included the component in its source cod n de.

cu ustom-componen nt-markup cu ustom-componen nt-root 3 cu ustom-componen nt-controllers 4 cu ustom-componen nt-attributes

1 2

Jeff Dou uglas & Wes Nol lte


Figure 4 - 13 Custom Comp 3. ponent in Visua alforce Page

Interestingly cu I ustom compon nents are self-d documenting t thanks to the tag-requiremen of nts attribu utes. If you exa amine the com mponent refere ence in an Org where you ha declared cu g ave ustom compo onents you wil find their de ll escriptions alon ngside the stan ndard compon nent document tation. Figure 4 - 14 shows the documentation that was generated for the Banner component. e c

Figure 4 - 14 Documentation for Banner C 4. Component

There are a nu T umber of custo componen examples in the documen om nt n ntation but som of me the best educational resources are custom component libraries that have bee made availab of s en ble the Fo orce.com Code Share and Wi sites1. e iki

custom m-component-exa amples Salesforce Handb book


Vi isualforce Tem mplates When buil lding websites youd norm s mally expect e each page to share some common ele ements such as a header, footer and navig gation menu. T same can be said of V The n Visualforce pages where you wish to build the look and feel from scra u d atch. Salesforc ce.com, anticip pating this req quirement, has created a han s ndful of comp ponents so that you define te t emplates for th overall he page layouts, cus stomizing the contents of eac c ch. Custom co omponents can be viewed as a type of coo cutter too but the n s okie ol templates referred to he are entire V r ere Visualforce pa ages. Note tha custom at componen can and sho be used in Visualforce te nts ould n emplates. To use su templates requires two things, the V uch Visualforce pa that serve as the age es tem mplate and the Visualforce page that provi e p ides the conten nt. Th Template he The templa page can include any m ate i markup that a normal page might use; it can also e t inc clude controlle and/or extensions. To d ers define a Visua alforce page as a template, all that is req quired is that it contains on or more in ne nsert compo onents. In List ting 4 - 61 we define a e Visualforce temp plate that inclu udes two calls t the custom component we created earlie as well to w er, as two insert components. Each compone is required to have a uniq (to that pa name E ent d que age) att tribute value; th will be refe his erenced in the content Visualforce page. Listing 4 - 61
<apex:pa age > <c:Ban nner title= =Section A icon=h A http://bit.ly/bKvtL2 /> <br/> :insert nam me=section nA/> <apex: <c:Ban nner title= =Section B icon=h B http://bit.ly/bKvtL2 /> <br/> :insert nam me=section nA/> <apex: </apex:p page>

The name attribute value is case-sensi itive i.e. if you content pag tried to ur ge reference sectiona instead of section the templ would not render as nA late expected. Th Content he The Visual lforce page tha delivers the content can a include an Visualforce markup, at e also ny e controllers and extensions. However, in or H rder to referen a Visualfo nce orce template the page
Jeff Dou uglas & Wes Nol lte 227

must use the compo u osition and define com mponents. The first type registers your inte ention to use a template and refers to a te d emplate by nam (the Visualforce page nam of the temp me me plate). The define component may ap d ppear in the page once for each insert component i the t in templa page. Any m ate markup wrapp by this com ped mponent will d be inserted into the tem duly mplate. Listing 4 - 62 detail the source code of the pa that uses the above tem g ls c age mplate; the tem mplate page has been saved with the name Template. h e Listing 4 - 62 L
<apex:page> < > <apex:compo < osition tem mplate=Tem mplate> <apex:de efine name= =sectionA > <p>kn ned. `and gothe to t the soccal af: `ther mand on, aforay r yould eas low w.</p> d, </apex:d define> <apex:de efine name= =sectionB > <p>kn ned. `and gothe to t the soccal af: ` `ther mand on, aforay y yould d</p> </apex:d define> </apex:comp < position> </apex:page < e>

The Visualforc page rendere as a result o this source c T ce ed of code is shown in Figure 4 - 1 15.

Figure 4 - 15. Visualforce Page Using a T Template 228 Salesforce Handb book

Be aware t that any mark that is wr kup rapped by the compositio tag that is inside on snt wr rapped by a de efine compon nent will not b rendered in the resulting page. be p If you are exposing Visu ualforce pages using Force.co Sites and y om your page resources (such as images) are caching unexpectedly, you will need to set the ( cache attr ribute on both the template a content pa to false. h and ages e ualforce is obviously a ti imesaver as y you can easil reuse page layouts, ly e Using Visu componentry an navigation. Not only this but when a change to the template is m nd s e made it is sea amlessly availa throughou all pages that implement sa template. able ut t aid Us sing Visualfor to create PDF files rce P
<a apex:page r renderAs=p pdf> your p page will be ou utput as a PDF file1. The val in this F lue

Visualforce pages render as HTML by default but by declaring the page comp e r y t ponent as

sim mple ability is obvious whe you conside that you ca dynamically generate pro en er an y ofessional loo oking invoices or other docu uments very qu uickly. Using t Force.com platform you can store the the in your app ese plication and even add them as attachment in emails. e ts You should also include showHeader d r=false in your page co n omponent declaration Setting this attribute thu n. usly ensures that the salesf t force.com header and side panel are not shown in your output PDF. d e n P

The only sk youll need to create a simple PDF file are Visualfor and some b kills rce basic CSS kn nowledge. To c create files tha are a bit mo flamboyant youll need to brush up on some of at ore t o n the more advanc CSS topics2. PDF genera e ced s ation is quite fl lexible and sale esforce.com ha made it as eas to include n sy niceties such as page number and pagina s ring ation in the gen nerated files. Although it is unsupport it is also possible to rend Visualforce pages as i ted, der e 3 Microsoft Word and E Excel docume ents by spec cifying the ap ppropriate MIME type in the conte entType attri ibute for the page compone p ent. Sta Resource in Visualforce Pages atic e As with an web-based user interface is necessary t include stat files such a images, ny to tic as Jav vaScript, Flash or CSS in you Visualforce pages. These files are called static resourc on the h ur d ces Fo orce.com platf form and can be uploaded and managed using the salesforce.com browser d s m int terface. You can ac ccess the static resource man c nagement page clicking Set es tup -> Deve elop -> St tatic Resou urces. There youll see a lis of all curren files (which you can edit or delete) st nt
page-component pr rofessional-pdf-fr from-visualforce 3 vi isualforce-word-e excel
1 2

Jeff Dou uglas & Wes Nol lte


and an option to create a new resource. The new resource window resembles a typical fileupload; be aware that the name of the static resource is what youll use to reference it later in your code. Static resources can be uploaded individually or as archived bundles (using JAR or ZIP files). We suggest grouping resources into archives as it makes maintenance simpler, and in some situations it is required. An example of when it might be required is when you have CSS that refers to image files in background-image properties. If you upload the images and CSS as separate resources you would have to hardcode the URL of the former in the latter; this is the antithesis of best practice in code. To use static resources in Visualforce pages or components requires you to use the {!$Resource.Static_Resource_Name} syntax for individual files1. An image that you might have uploaded with a name of MyImage could be referenced as <apex:image url= {!$Resource.MyImage} />. Referencing resource inside of archives is somewhat different and frustrates many beginner developers. Resource access in this case requires the use of the URLFOR function which follows the syntax {!URLFOR($Resource.Static_Resource_Name, [path_to_resource]}. Consider for example a CSS file called styles.css that includes the property background-image: url(/images/logo.jpg). If the CSS file exists at the root folder then youd expect a folder structure of:
/styles.css /images/logo.jpg

Archiving these files into the same bundle and uploading then as a static resource called MyCss, you would then include the CSS in your page using <apex:stylesheet value={!URLFOR($Resource.MyCss,styles.css)}/>. Your style sheet will automatically be able to see the image. You can reference the image directly using {!URLFOR($Resource.MyCss,/ images/logo.jpg)}.

Visualforce & the Web

Since Visualforce is consumed over the web its important that it be able to use other prominent Internet technologies. Since Visualforce renders as HTML this is thankfully quite easy to do so youll find it easy to create elegantly styled pages using CSS and JavaScript. There are, however, as few nuggets that will help you in integrating these technologies. CSS Although CSS files can be uploaded as static resources it can take a lot of time going through the code-upload-refresh cycle. There are two alternatives both with their advantages: If you upload a style sheet file as plaintext and ensure the metadata is included in your Force.com project you can edit the style properties directly in Eclipse. Unfortunately you will not be able to reference images (unless you use external URLs) in the CSS

delivering-static-resources Salesforce Handbook


You can create a Visualforce page component with contentType=text/css and code any styles between style tags in that page1. Since your CSS is contained in a Visualforce page you can refer to any images and you can use Visualforce or Apex to dynamically determine styles

If youre not looking to recreate styles but instead wish to apply the salesforce.com styles in your own page you can either use the standard components, or - using firebug to interrogate the class names - you can add the style class names to your page components2. JavaScript JavaScript libraries can be uploaded as static resources, included from URLs or dumped into Visualforce pages similarly to CSS. Including libraries is simple but there are some lessons to be learnt in integrating JavaScript with Visualforce. If youd like to reference Visualforce component in your JavaScript youll typically need the component Id3. Although you can assign Ids to components, salesforce.com generates different Ids when the page is rendered as HTML to ensure Ids are unique. The rule here is that the Force.com platform will generate HTML Ids by concatenating all parent Visualforce Ids with the current Visualforce element into a colon-separated string value4. Even dastardlier if you dont explicitly assign Visualforce Ids to components they will have Ids generated for them. Knowing this, there are two common ways to retrieve Visualforce component Ids. The first approach requires that you assign Ids to all components in the required tree. Consider the example in List 3 - 63. Listing 4 - 63
<apex:page id=thePage> <apex:pageBlock id=theBlock> <apex:outputText id=theText /> </apex:pageBlock> </apex:page>

If you had an in-page script which needed to fetch the HTML id for the outputText component you would have to declare the variable as var id = {!$Component.the Page.theBlock.theText}. This is a bit dangerous because when your page structure changes youll need to update any JavaScript that might be affected. The second approach calls for you to declare a JavaScript variable at the same point in the page component tree as the component that it references. Doing this allows you to refer to the component directly using {!$Component.theText}. Although this disrupts the flow of

dynamic-css salesforce-css-in-visualforce 3 referencing-js-visualforce 4 component-id-best-practices

1 2

Jeff Douglas & Wes Nolte


the source code it is more maintenance friendly, as structural page changes are less likely to affect your JavaScript code. List 3 - 64 demonstrates such an approach. Listing 4 - 64
<apex:page id=thePage> <apex:pageBlock id=theBlock> <apex:outputText id=theText /> <script> var id = {!$Component.theText}; </script> </apex:pageBlock> </apex:page>

Visualforce Email Templates Email templates and mail merging are an important part of most enterprise applications. Salesforce.com has made this simple on the Force.com platform with Visualforce email templates1. These offer total customization with the (now familiar) Visualforce syntax providing simple integration with your salesforce.com data2. Creating Visualforce email templates is done through the salesforce.com interface. You can easily style your email using CSS and have the option of adding attachments. When setting up the email template you specify the object you wish to include in the template as well as any of its related objects. If you wish to have a greater degree of freedom in which objects you use and how you use them, you can include custom components in your Visualforce Email Templates3. Mobile Visualforce Pages Early on salesforce.com realized that mobile access to platform data is essential. To fill this gap they created Salesforce Mobile4, which currently runs on BlackBerry, iPhone and Windows Mobile devices. The application interacts with the platform servers over the mobile networks and stores a configurable subset of the data in a database local to the users phone. A separate license is required for users that want to use Salesforce Mobile; DE and Unlimited Orgs get 1 free mobile license and other Org types need to purchase them separately. Mobile Lite is a free version of the mobile application but does have additional restrictions5. The application is a composite native (to the phone) client application and web browser. Each of these communicates with salesforce.com through the API and Internet respectively.
intro-visualforce-email-templates visualforce-email-template-sample 3 component-in-visualforce-template 4 salesforce-mobile 5 salesforce-lite
1 2


Salesforce Handbook

Although some restrictions apply, the following are more or less available to mobile users: Some standard and all custom objects Permissions, record types and page layouts Related lists Dashboards and reports Custom list views Visualforce tabs and web tabs

Note that even though Visualforce is available for the mobile application, page designs that work in a computer browser are often not suited for mobile interfaces1. Security Visualforce renders as HTML and can be vulnerable to the same types of attacks as traditional web sites. In general there are three attack types that you should be aware of when coding: Unescaped output and formulas in Visualforce pages2. If youve used components with their escape attribute set to false then there is a chance that users can enter malicious code that can gain access to user or application information. You should encode and potentially insecure strings appropriately Cross-site scripting (XSS) can be thought of as a range of techniques used to inject malicious code into your application pages3. The platform includes some protection against these attacks but you can add additional security by encoding certain inputs appropriately With cross-site request forgery (CSRF) attackers often take advantage of lingering sessions4. They might include a URL in their page that attempts to execute an action in one of your application pages; if you were previously logged into salesforce.com and your session had not timed out then the forgery might succeed. The Force.com platform includes protection when using standard controller and methods in your pages, but it is largely up to you to secure other custom areas.

In chapter 3 we mentioned the Force.com Security Source Code Scanner, which will highlight non-secure areas of your application and suggest appropriate actions. On the Force.com security site there are also a number of educational, analytic and best practice articles to guide you in your quest to build secure applications5.
developing-pages-for-mobile security-unescaped-output 3 security-xss 4 security-csfr 5 force.com-security
1 2

Jeff Douglas & Wes Nolte


Order of Execution r n When a Visua W alforce page lo oads it initializ the contro zes oller, extensions and component contro ollers. This all happens in a particular sequ uence and can thus affect th way you de n he evelop these classes and wh the user might see on th page. To pr c hat m he rovide a deepe understandi to er ing the ord of this execution it is nec der cessary to exam the life cy of a Visua mine ycle alforce page. This lifecycle is dependent on two facts, th content of th page as wel as how the p T s n he he ll page is reques sted. There are two ways that a Visualforce page can be r e t e requested: Get reque are made when a user en ests w nters a URL in the browser or clicks a butt or n o ton 1 link that n navigates to a different page d Postback requests are made when a action is fi an ired that requi ires a page up pdate. These req quests occur when parts of y w your page are rerendered or a redirect is i r issued to a page that uses the same controll and a proper subset of co ler ontroller exten nsions of the init page2 tial

Visual lforce View S State Any Visualforc page that co A ce ontains a form will additional have an enc lly crypted hidden field n 3 that maintains a reco of the cont m ord tents and state of the page . Inefficient pro e ogramming can lead n to larg or brittle vie states so it worthwhile knowing why view states ex and how t use ge ew ts y xist to them efficiently. e W Winter 1 salesforce.c With 11, com released th View State Inspector, wh is he hich a browser-base tool that h ed helps you view debug, and optimize the view w, d e s state in order to improve pag performance. t ge Since HTTP i a stateless protocol, info S is p ormation abou groups of actions need to be ut a mainta ained elsewher If, for exam re. mple, a user e enters the wro type of data into a vali ong idated form field and then clicks the submit button an error message will be displa f e ayed to them. From the use perspectiv a change has occurred in t page based on a previous state but to d this ers ve s the s do salesfo orce.com has h to maintain a state with a temporary sto the view state. had n ore, s To ensure that your pages loa quickly and work well it is important that you: T ad d s Mark any Apex variable that arent n y es necessary to th view state as Transient. This he s is especial true of variables of type B lly Blob, which ca be enormou an us Only us one form per Visua se m alforce page and demark sub-forms with k actionR Region components Create wi izards with as few pages as possible f

visualf force-get-requests s visualf force-get-requests s 3 intro-v view-state

1 2


Salesforce Handb book

Use outputLink components instead of commandLink or commandButton components where possible as they dont need to be nested in a form Fetch only the bare minimum of required fields via SOQL

Development Best Practices

Now that weve detailed the different aspects of developing on the Force.com platform, lets take a look at some of the things you should and should not do when developing. These best practices will not only help you write better, more scalable code but will also make your life easier down the road in terms of maintenance. You may have to dig into the salesforce.com documentation for more information on some of these bullet points as they are beyond the scope of this book. Apex Triggers There should only be one trigger for each object. Avoid complex logic in triggers. To simplify testing and resuse, triggers should delegate to Apex classes which contain the actual execution logic. See Mike Leachs excellent trigger template for more info1. Since Apex is case insensitive you can write it however youd like. However, to increase readability, follow Java capitalization rules. Use Asychronous Apex (@future annotation) for logic that does not need to be executed synchronous. Asychronous Apex should be bulkified. Apex code must provide proper exception handling. Prevent SOQL and SOSL injection attacks by using static queries, binding variables or the escapeSingleQuotes method. When querying large data sets, use a SOQL for loop Use Apex Limits Methods to avoid hitting governor exceptions. No SOQL or SOSL queries inside loops No DML statements inside loops No asynchronous methods (@future) inside loops Do not use hardcoded IDs

trigger Jeff Douglas & Wes Nolte 235

Bulkify any helper classes and/or methods. Triggers should be bulkified and be able to process up to 200 records for each call. Execute DML statements using collections instead of individual records per DML statement. Use Collections in SOQL WHERE clauses to retrieve all records back in a single query Use a consistent naming convention including the object name (e.g., AccountTrigger)

Visualforce Do not hardcode picklist values in Visualforce pages; include them in the controller instead. JavaScript and CSS should be included as Static Resources allowing the browser to cache them. Reference CSS at the top and JavaScript a the bottom of Visualforce pages as this provides for faster page loads. Mark controller variables as transient if they are not needed between server calls. This will make your page load faster as it reduces the size of the View State. Use <apex:repeat> to iterate over large collections. Use the cache attribute with the <apex:page> component to take advantage of salesforce.com CDN caching when appropriate.

Unit Testing Use a consistent naming convention including Test and the name of the class being tested (e.g., Test_AccountTrigger). Test classes should use the @isTest annotation. Test methods should create all data needed for the method and not rely on data currently in the Org. Use System.assert liberally to prove that code behaves as expected. Test each branch of conditional logic. Write test methods that both pass and fail for certain conditions and test for boundary conditions. Test triggers to process 200 records make sure your code is bulkified for 200 records and doesnt throw the dreaded Too many SOQL queries: 21 exception.


Salesforce Handbook

When testing for go n overnor limits, use Test.start , tTest and Test t.stopTest and the Limit class i instead of hard d-coding gover rnor limits. Use S System.runAs( ) to execute c code as a speci user to tes for sharing rules (but ific st not C CRUD or FLS permissions). p Execu tests with the Force.com IDE and no the salesforce.com UI. W ute m ot Weve seen mislea ading code cov verage results w when running from the sales sforce.com UI. Run the Force.com Security Source Scanner to test your Org for a nu m umber of ity q Site rol securi and code quality issues (e.g., Cross S Scripting, Access Contr Issues, Frame Spoofing) e For all secu urity resources including the Force.com Security Source Scanner, s e e visit http:// /wiki.developerfo orce.com/index.ph hp/Security.

Miscellanea M
Besides the mentioned major features of Visualforce there are a number of uti e m n ilities that youll often need to reference. d Gl lobal Variable es Developers often need a way to a s access inform mation about the current user and en nvironment an a lot of th information is convenien available from global v nd his n ntly variables1. Av vailable using the {!$Glob bal_Variabl le.variable e_name} synt you have access to tax inf formation abo field labels page URL p out s, parameters, user details, stat resources a much tic and mo ore. Fu unctions & Operators To facilitat common fun te nctions and op perations, salesforce.com ha exposed a n as number of too available di ols irectly in Visua alforce2. These include math e hematical and logical operato as well l ors as date, time, tex logical, infor xt, rmational and encoding func ctions.

1 2

vi isualforce-global-variables vi isualforce-functio ons-and-operators Jeff Dou uglas & Wes Nol lte 237

In ntegration with th Cloud he

ntegration be etween platfor rms has been a valuable a n advantage sinc the creatio of the ce on Internet. It is often the flexibility and ease of thes integrations that determi f se s ines how suc ccessful an app plication or pla atform becom Salesforce.com foresaw that delivering software, mes. t inf frastructure an developmen as a service in the real w nd nt e world would require them t expose r to the CRM and development platform via t eir technologies su as SOAP- and REST-b uch based web ser rvices, ERP co onnectors, em and syndic mail cation feeds. H Having created these channe theyve d els helped developer on other pla rs atforms leverag the inheren value they ar providing. ge nt re Some exam mples of librar ry-assisted integrations inclu Amazon, Facebook, W ude Wordpress, Jav Microsoft O va, Outlook, SAP, Twitter, Adobe Flex, .Net, Mac OSX and Google. This list gives , d s you an idea of t range of po the otential integrations but it is far from exh s haustive. As lo as the ong application youd like to inte egrate with is web services capable it ca be plugged into the an d Fo orce.com Platfo orm. The type of integration youll require is largely based on two things: f The g of your int goal tegration e.g. e export data fro the platform om m The p platform or lan nguage that yo oure integratin with, althou the couplin here is ng ugh ng quite loose

Fi igure 5 - 1. Typic Enterprise L cal Landscape

As part of the Force.com Platform offering salesforce.com advertises the 5 paths to integration success. Which of these 5 paths you use is dependent upon the software you currently use and in some cases the available budget. In this chapter well examine each type of integration so that when the time comes youll know which channel best suites you.

Path 1: AppExchange
The AppExchange is a marketplace with nearly 1000 applications built on the Force.com platform. Here you can buy or sell business applications and services, usually with the option to test-drive applications that youre performing due-diligence upon. Applications are grouped according to the following categories: Key Attributes - how much does it cost and rating e.g. whether the application is free or paid; is it a top-rated application Edition - which editions will it work on e.g. Group or Professional Type of App - what role or platform does the application work in e.g. whether it is a full-blown application or an add-on Industry Solutions - which industry is the application categorized under e.g. Communications, Health Care, or Retail Function - what business area does the application best cater for e.g. Analytics, Marketing, Sales

Of equal importance are the nearly 300 services offered on the AppExchange. These are grouped by: Key Attributes - a subset of those mentioned above Industry Specializations - largely the same as Industry Solutions above Type of Service - Business Consulting, Custom App Development, System Integration, and training

Publishing to the AppExchange In order to publish applications to the AppExchange its necessary to work through a few key steps with salesforce.com. These steps protect you as the publisher but also ensure that that the products that consumers acquire through the marketplace are secure and of high quality. These requirements are: 1. Join the Salesforce.com Partner Program1. Once considered a partner youll be given access to a number of resources only available through this program e.g. previews of upcoming functionality and access to marketing channels.

salesforce-partner-program Salesforce Handbook



Build your application on the Force.com Platform and bundle it into a Managed Package for distribution. The Force.com discussion forums will form a large part of your support in this phase. Capture the details of your software within the publishing wizard1 e.g. the title, description, features and requirements. Then submit your application to salesforce.com for review. Once it passes the review you are free to publish it to the AppExchange.


As part of the publishers framework youll also have the ability to present screenshots, read-only test drives, as well as fully functional trial versions2 of your applications to prospective clients. Although your company will do the bulk of the heavy lifting, salesforce.com will provide comprehensive assistance every step of the way. The AppExchange from a Consumers Perspective Marketplaces are just as much for those buying products as selling them, and AppExchange makes it as easy as selecting a potential product and clicking the Get It Now button. Of course youll want to do some investigation before purchasing an application and to this end youll typically have access to application demos, screenshots and/or trial versions. Be sure to check the Spec tab to make sure that the application supports your purchased edition. Besides the paid applications youll find there are a number of free applications on the AppExchange3. One of the most prolific and popular free application publishers is Force.com Labs. All applications under this publisher are created by salesforce.com employees and include everything from common utilities to save you time to Chatter plug-ins to enhance your salesforce.com experience (and theyre all free!). Indispensible Applications As you work with the Force.com Platform youll discover applications from the AppExchange that are useful to your business. Some of these will be quite specific to what your company does whilst others provide a more general utility. To save you some time well mention some that weve found useful. Adoption Dashboards By Force.com Labs This app consists of three Adoption Dashboards, and their associated reports. Downloading this app will create an Adoption Dashboards - AppExchange Dashboard folder along with a Reports folder called Dashboard Reports - Adoption.

package-publisher-home appexchange-howto-create-trial 3 appexchange-popular-free-apps

1 2

Jeff Douglas & Wes Nolte


Appirio Cloud Storage By Appirio Economically store unlimited numbers of files of all sizes directly through the salesforce.com interface. Appirio Professional Services Enterprise By Appirio Manage your people, customers, projects and transactions with an end-to-end services management application, built on Force.com. With Chatter enabled, PS Enterprise brings realtime collaboration with full business context to your services organization. SalesView FREE: Drive Sales Productivity with Integrated Sales Intelligence By InsideView SalesView, the #1 rated app on AppExchange, finds sales opportunities across both traditional and Web 2.0 sources like Capital IQ, Reuters, Jigsaw, NetProspex, LinkedIn, Twitter and Facebook. Deliver integrated sales intelligence directly in Salesforce. Draggin Role By DrivEnable Manage your role hierarchy with ease! Now you can drag and drop your way through any hierarchy modifications. Draggin Role is a free application that allows you to view and manipulate users AND roles from a single Custom Tab. Intacct Financial Management By Intacct Corporation Intacct is the Preferred Provider of Financial Applications for AICPA business solutions and is seamlessly integrated with Salesforce. Intacct cloud financials completes Lead-to-Order, Order-to-Cash and provides 360 real-time business visibility. DBAmp/Pro By ForceAmp.com DBAmp/Pro for AppExchange connects Salesforce.com with Microsoft SQL Server. With DBAmp, you can easily access your Salesforce.com objects using SQL Select, Update, Insert and Delete statements. DBAmp can also replicate those objects as local SQL tables. Appirio Contact Sync for Salesforce & Google Apps By Appirio Appirio Contact Sync for Salesforce & Google Apps is a simple tool to select and sync contacts between your Google and Salesforce address books. (Unsupported)


Salesforce Handbook

Action Plans By Force.com Labs Action Plans encapsulates best practices into reusable task templates. An Action Plan can be created for an Account, Opportunity, Contact or Lead. Template tasks can be pre-assigned to a specific individual or assigned to the running user. Ribbit for Salesforce By Ribbit Ribbit for Salesforce is the only sales productivity tool that unifies mobile voice and SMS communications, Salesforce CRM, email, and voice-to-text transcriptions. Built-in automation helps you work less and sell more. SnapShot Change And Release Management By DreamFactory Software Snapshot is the ultimate tool for change management, change reporting and compliance documentation for Salesforce Orgs. With SnapShots rich interactive GUI, admins can compare and diff Orgs, monitor changes to Orgs, and push customizations between Orgs. Conga Composer By AppExtremes One click to proposals, account plans, contracts and more from multiple objects and related lists. Easily customize Spring 10 Quotes with line item sort. Output to Word, Excel, PPT or PDF to print/attach/email in single or batch operations. See Reviews! VerticalResponse for AppExchange By Vertical Response Send marketing emails & postcards from Salesforce in minutes. Use opted-in contacts & leads for lists, build professional campaigns & track statistics. Share instantly on Facebook & Twitter. Geopointe - Force.com with Google Maps and MapQuest By ArrowPointe Corp Geopointe is the premier Force.com geo/mapping solution providing numerous ways for end-users, administrators and developers to take advantage of geo data and maps. DemandTools 2.0 By CRMFusion Inc DemandTools is an admin toolkit for a variety of data quality needs including merging duplicate records (dupes), backup, batch normalization, ETL, batch deletion, duplicate prevention, comparing external data to data in Salesforce, Lead to Contact etc.

Jeff Douglas & Wes Nolte


Active eRecruiter Bu usiness Editio on By Job bPartners ActiveRecruiter Business Edition is a comprehensive solution for streamlining your A E e r corpor rate recruitme activities. Easy-to-use a ent and fully dep ployed in as little as 48 h hours, Active eRecruiter Busi iness Edition automates you end-to-end r a ur recruiting proc cess. Addre Validation & Auto-com ess n mplete from P Postcode Anyw where By Postcode Anywh here Look up and auto-complete worldwide a L e address info. Z code and postcode loo Zip d okups return clean, correct international address. Essen address va a ntial alidation for in trading. ntl Salesf force Integrat tion - Informa atica Cloud Services By Inf formatica Corp p Designed for n D non-technical users. Easily in u ntegrate Salesfo with on-p orce premise & ERP and P back-o office apps (SA JDE, Orac databases, files, spreadsh AP, cle), heets. Load, migrate, extract, sync, m , and replicate data on demand. n

Path 2: Build Yo Own our

In our world o APIs and we services the Force.com in I of eb e ntegration optio discussed i this ons in chapte give you a mu er ultitude of inte egration options. Salesforce.co and some community mem om c mbers have al created libra and tools to make said in lso aries ntegrations quic and less er prone. cker rror SOAP Based Web Services P SOAP is a me S eta-protocol fo defining the exchange in or e nformation usi web servic It ing ces. uses XML to define its request an response for X nd rmat and is typ pically transmi itted over HTT or TP RPC. Several areas of the Force e.com platform have define their integr m ed ration points using SOAP providing W P WSDL files tha enable you t automatical generate cl at to lly lient libraries i the in langua of your cho age oice. Data Integration w the Web Services API I with S The Force.com Web Service API, often just called A T m es API, is a data services API that a expose all standard and custom objects allow es d m wing you to c create, retrieve update or d e, delete 1 record using web service calls . Other func ds ctionality such as password maintenance and h d e search are also av hing vailable2. E Each new sale esforce.com re elease will incl lude an updat to the API. API te v versions are supported acr ross releases and are bac ckward compa atible. S Salesforce.com does reserve the right to stop supporting API version that m g ns a 3 or more years old. are y
1 2

api-qu uickstart web-se ervice-api-cheatsh heet Salesforce Handb book


There are two web services each with their own Web Service Definition Language (WSDL) file for API access. These are called the Enterprise and Partner WSDL files and each have their own strengths and weaknesses1. Partner WSDL The Partner WSDL is analogous to dynamic Apex. It doesnt recognize specific object types such as Contact or MyCustomObject__c; instead it understands the concept of a generic SObject. These variables of the SObject type can be recognized as Contact or MyCustomObject__c by examining that SObject describe information. This means that with the Partner WSDL you could develop a single version of an external application or library that works across multiple salesforce.com Orgs. Listing 5 - 1 shows how you can insert a Contact record using Java and libraries generated from the Partner WSDL. Listing 5 - 1
// Saves operate on lists of SObjects SObject[ ] contacts = new SObject[1]; // Use an SObject to hold the contact information SObject contact = new SObject( ); // Assign field values MessageElement[] fields = new MessageElement[2]; try { fields[0] = newMessageElement(FirstName,Zack); fields[1] = newMessageElement(LastName,de la Rocha); } catch (Exception e) { e.printStackTrace( ); } // Set the SObject type contact.setType(Contact); // Set the field values contact.set_any(fields); contacts[0] = contact; SaveResult[] sr = null; try { // Insert/Create the contact record

partner-enterprise-wsdl Jeff Douglas & Wes Nolte 245

sr = bin nding.creat te(contacts s); } catch (Ex xception ex { x) System.o out.println n(An unexp pected error has occ curred. + ex.get tMessage( )); ) }

Since this represents a loose typed versio of the Force.com data model the gene S ely on m erated library is a bit more difficult to wo with. The m advantag is that you have the freedo to y ork main ge h om modify your metada without th necessity of regenerating the WSDL and the conse y ata he f g a equent librarie each time yo salesforce.com data mod changes. es our del I is strongly advised that i It integrations w third parti use this W with ies WSDL t type. It provid you with the freedom to modify yo Orgs met des our tadata w without worryi about the i ing impacts on run nning integratio ons. For a comprehensive sample application that uses the Partner WS F e SDL check ou the ut 1 Force.com develope site . er Enterp prise WSDL The Enterprise WSDL, on the other han is more sta (or strong T e t nd, atic gly-typed) in n nature. After generating you language-lib g ur braries from th WSDL you notice that youll have c his ull t classes (or oth structures) that directly define your o her ) y objects. Listin 5 - 2 show how to use code ng ws genera from the E ated Enterprise WS SDL to achieve the same resu as Listing 5 - 1. e ult Listing 5 - 2 L
SObject[] c S contacts = new Contac ct[1]; // A Contac type is available from the / ct // Enterpri / ise WSDL Contact c = new Conta C act( ); c.setFirstN c Name(Zack ); c.setLastNa c ame(de la Rocha); // Assign t / the contact to the li t ist contacts[0] = c; c SaveResult[] sr = nul S ll; try { t t/Create th contact record he // Insert

partne er-api-java-code-s sample Salesforce Handb book


sr = bi inding.create(contac cts); } catch (Exception ex) { n .out.println(An une expected er rror has oc ccurred. System. + ex.ge etMessage( )); }

can ccessing a Con ntact object record and fie elds is simple a more and Here you c see that ac int tuitive making integrations quicker and less error prone t q s than with the Partner WSDL P L. The major disadvantage here is that if yo add a new f h ou field to the Acc count object, or altered its metadata in some other way you wou probably need to regen uld nerate the W WSDL and consequent librar Be sure to have a look at the sample pr ries. o t roject available on the develo site1. e oper Re eplication AP PI This API is a subset of the Web Servi t ices API and p provides a mec chanism to sim mplify the on ne-way push of data from the Force.com pl f e latform to ano other data store e. There are just two calls for data replica f ation namely g getUpdated and getDeleted. The a first simply fetc ches all record that have b ds been updated on the speci ified object d during the ind dicated time sp The getD pan. Deleted calls removes reco ords in a similar fashion. r The typical order of event when fetchin records usin the Replicati API calls m ts ng ng ion might be: 1. 2. 3.
getU Updated is cal lled and return a list of reco Ids ns ord

Exter rnal application makes a re etrieve call us sing the list of Ids and fetches the o appro opriate object fields f Objec data is then written to a lo (or externa application) data store ct ocal al

The proces for the delet call is nearly identical. ss te y Typically th very first getUpdated call establishe a data basel he g es line and then its up to you to pass the a appropriate tim span in subsequent calls. me These calls save you the trouble of w s e writing framewo orks that reco ognize when a record is up pdated or delet or even worse, perform ted; w ming a full expo of your Fo ort orce.com objec records ct for every data replication. r e belongs to a fo ormula field, th record hat If the only changed value on a record b will not be recognized as being update This is be ed. ecause formula fields are a only calcula on the fly and are not considered to be true data. ated y b A few poin to note whe using the re nts en eplication calls are: The c facilitate replication i.e. d copying f calls data from a source to target (as op t pposed to two-w copying) way

en nterprise-api-code-sample Jeff Dou uglas & Wes Nol lte 247

The calls can only see objects and records that the API user has access to
DateTime values will have their seconds portion truncated

You should not poll the API more often than once every 5 minutes Outbound messaging can be used to trigger replication calls The API checks for data changes in your Org. To check for changes to object structures you would have to use the Metadata API.

Outbound Messaging Salesforce.com offers outbound messaging so that even non-developers can expose their Orgs data for integration with external platforms1. The technology is a feature of workflow rules with a typical setup requiring you to specify the conditions under which the workflow will begin, the object record fields that you wish to transmit and the endpoint that will receive the data. To create an outbound message click Setup -> Create -> Workflow & Approvals -> Outbound Messages. From here you can create, view and track outbound messages. Clicking on any available outbound message name will give you the details for that record. Once youve defined your outbound message youll need to download the WSDL document that defines the target web service and use that to generate the platform client libraries that will receive and parse the message contents. The service uses the notification call to send SOAP-based messages over HTTP(S).

outbound-messaging Salesforce Handbook


Fig gure 5 - 2. Outbo ound Messaging Data Flow g

Some helpf baked-in fe ful eatures of outb bound messagin are: ng Up to 100 notificati o ions can be inc cluded in a sing SOAP mes gle ssage If an object change after a mess es sage is sent, b before it is delivered, the updated but s e inform mation will be delivered Messa ages are queu ued, and if th delivery fai sending will be retried until the he ils, w messa is 24 hours old age s

The officia salesforce.co documenta al om ation has a nu umber of exam mples showing how to 1 bu listener ser uild rvices from an Outbound Me essaging WSDL . Outbound messaging is a quick and s simple alternative to buildin your own o ng outbound we service calls You wont be able to use it for more complex integ eb s. e grations but w when only sim services a involved, it saves time bo in terms of implementatio and mainte mple are t oth f on enance. Ap Web Serv pex vices The Partne and Enterpr WSDL exp er rise pose a rich set of common functionality th might t hat be required with integrations However the will be tim when you require specific business hin s. ere mes r c fun nctionality to be available for integratio ons. The For rce.com platfo orm makes it easy for

bu uilding-outbound d-messaging-listen ner Jeff Dou uglas & Wes Nol lte 249

develo opers to mark Apex classes and methods as web servic a WSDL file is automa ces; atically made available for an classes defin this way. a ny ned Apex classes t A that contain web services n w need to be de eclared using the global a t access modifi This mean that all Apex code can acc this class. Web service methods require the ier. ns x cess m webse ervice and s static keywo ords in their sig gnature. Listin 5 - 3 details the definition of an ng Apex web service method. w Listing 5 - 3 L
global clas MyWebSer g ss rvices { webServic static List<Id> g ce getContactI Ids(Id acco ountId) { List<Id> contactId = new Li ds ist<Id>( ); ; act c: [SELECT id FR ROM Contact WHERE t for(Conta account tId = :accountId]){ contact tIds.add(c.id); } ontactIds; return co } }

simple web ser s rvice will return a list of Con n ntact Ids give a specific Account id. T use en A To this web service from your chosen platform you need to ge m n ull enerate code from the WSD for fr DL this Apex class. Clic Setup -> Develop - Apex Cl ck > -> lasses to vie all of your Apex ew classes Next click W s. WSDL next to th class in to be used. Figur 5 - 3 shows the class listin for he re ng the My yWebService class. es

Figure 5 - 3. Apex Web Se ervice WSDL Ge eneration

It is also possi I ible to define custom types to be used by your web se ervices e.g. yo can ou define global inner classes that can be used as return typ or parameters of Apex web d pes x service To make a variable wi es. any ithin a globa class access al sible via a web service it mu be b ust declare with the we ed ebservice ke eyword. Some points to note when us the webse S o sing ervice keyword: The keyw word can only be used to defi top-level m b fine methods and variables of top v p-level or inner c classes. It cann be used on the class itself or anywhere in an interface not f i e Methods defined with the keyword m also be sta t must atic Member v variables mark with webse ked ervice cannot be declared as static


Salesforce Handb book

There arent SOA equivalents for all Ape structures. This means that the e AP s ex follow wing cannot be used as par b rameters or re eturn types of web service methods: f Maps, Sets, Excepti Objects, Pa ion attern Objects, Matcher Objects

Ge enerating SOA Based We Service Lib AP eb braries Whether ge enerating the API or Apex w services t A web there are a num mber of comm steps mon and approaches1. First of all youll need to generate the WSDL file. W o e Weve mention how to do this for ned o Ap web servic already, fo Enterprise a Partner W pex ces or and WSDL files you need to na ull avigate to Se etup -> Dev velop -> AP and click th appropriate link. PI he The next s step will be to import the W o WSDL file into the develop pment platfor youve rm chosen e.g. Eclip or Micros Visual Stu pse soft udio. There are tools to help you do this for most e p po opular language platforms. The result of th import is ty e T his ypically a set of classes that f form your sal lesforce.com li ibrary. Using these classes or li ibraries youll be able to log into the For g rce.com platfo orm. This log step will gi your applic gin ive cation access to a session Id and server UR which are u o RL, used in all sub bsequent calls to ensure secu communica ure ations. Libraries generated from Apex web s g m service WSDL files will no contain L ot the functi ionality requir red to log in the Force.com platfor nto rm. It is therefore necessary to u the Partne Enterprise or OAuth lib n use er, braries to obtain a session Id an server UR before usi s nd RL ing Apex web service b functionali ity. Ap Callouts pex While all th integration options discus he ssed so far exp pose data and functionality to services f o ou utside of the Fo orce.com Platf form, it is possible to consu umed SOAP-ba ased web servi using ices Ap code. pex Force.com provides a se ervice used to translate WSD documents into Apex co called DL s ode WSDL2Apex. T This process is similar to generating external langua libraries from the age afo orementioned WSDL files. To begin the generation pr rocess, navigate through Se etup -> De eveloper -> Apex Cla > asses and the click on Ge en enerate fro WSDL butt at the om ton top of the page. Figure 5 - 4 sh p hows where to find this featu ure.

Figure 5 - 4. G Generate from W WSDL

ap pi-quick-start-step ps Jeff Dou uglas & Wes Nol lte 251

The results of a successful generation will include Apex versions of the types represented by the third party WSDL document. These client stubs can be used to do all the dirty work of serializing and de-serializing the SOAP packets between your underlying Apex code and the third party platform. Consider these guidelines when using Apex Callouts: You cannot use WSDL2Apex with WSDL files that are more than 1MB in size It is required that you white list any external sites that you wish to access through the Force.com platform. This can be done by clicking Setup -> Security Controls -> Remote Site Settings and creating a New Remote Site The generated Apex code cannot be more than 100,000 lines in length. Whether the generated code exceeds this limit or not the resultant Apex code will be displayed to you. If it exceed 100,000 lines you will not be able to save the code, but can manually copy and paste the code into smaller portions that can be later saved If an Apex reserved words are contained in the WSDL document, the generated Apex code will be suffixed with _x

RESTful Web Services Representational State Transfer (REST) is an architectural style for building communication systems within computer networks. It is not a framework but instead a style that you might adopt in building your web services. The World Wide Web is the most commonly cited REST example and in a similar way you can use HTTP technologies to build your own RESTful web services. When building applications that will consume or create REST-based web services you will find the following classes useful:
Http - Used to initiate HTTP requests and responses HttpRequest - Used to programmatically create GET, POST, PUT and DELETE

HTTP requests

HttpResponse - Handles the HTTP response returned by HTTP XmlStreamWriter and XmlStreamReader - Simplify the reading and writing of

XML strings

and parsing XML documents number of formats

Document and XmlNode - Document Object Model (DOM) utilities for creating EncodingUtil - Utility capable of encoding and decoding String variables into a Crypto - Enables encryption and decryption using a number of popular algorithms


Salesforce Handbook

A simple HTTP callout using a POST request is detailed in Listing 5 - 41. Listing 5 - 4
@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://third-party.com/context); 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( )); } }

Its not required that you annotate your callout methods as @future but be aware that if you dont, your application will effectively wait for the external system to respond before allowing the user or process to proceed. REST-based web services are generally more flexible than their SOAP-based counterparts, and the communication overhead tends to be smaller. However SOAP-based web services are quicker to build on the Force.com platform primarily because of the tools supplied. Managing Data with the Bulk API A common task in contemporary development projects is the loading of very large data sets, especially where system integrations are concerned. The standard Force.com Web Services API facilitates this type of integration but can be burdensome for large datasets as youre required to implement complex processes to upload data in bite-sized chunks, monitor results and retry failed records. The Force.com Bulk API was designed specifically to offload the complex and time consuming process of importing large data sets from your client application to the Force.com

restful-web-service-sample Jeff Douglas & Wes Nolte 253

platfor The Bulk API and supp rm. porting web in nterface allows you to upload and create im d mport jobs, monitor and manage these jobs throug an easy to use web interface, and re m e gh eceive notific cations when th jobs comple he ete. The REST-ba T ased Bulk AP was develo PI oped specifica to simpli the proce of ally ify ess upload large amo ding ounts of data. It is optimized for inserting, updating, ups I d , serting, and de eleting large numbers of re n ecords asynchr ronously by su ubmitting them in batches to Force.com, to be m proces ssed in the bac ckground. Processing Uploaded records are stream to Force.co to create a new job. As the data rolls in for U med om the job it is stored i temporary storage and th sliced up in user-defin batches (m of b in s hen nto ned max 10,000 records). Eve while your data is still be sent to th server, the Force.com platform 0 en eing he F submit the batches for processing ts g.

Figure 5 - 5. Processin with the Bulk API e ng k

Some compelli reasons to use the Bulk A are: S ing API


Fast proces ssing speed Less client-side programm logic ming GUI for m monitoring job Status S Automatica retry failed records ally d Support for parallel and serial processin r s ng Fewer API calls Fewer drop pped connectio ons Easily mod batch size dify
Salesforce Handb book

Monitoring Monitoring Bulk API jo can be do by going to Setup -> Administ g obs one trative Se etup -> Mon nitoring -> Bulk Dat Load Job . Options he include the ability to > ta bs ere e ma anage running jobs, view com mpleted jobs a view your p and processing quo ota.

Figure 5 - 6. Mo F onitoring Bulk A Jobs API

In ntegration Since the B Bulk API is REST-based it is possible t integrate it with any dev R t to velopment pla atform capable of work with HTTP. The b API is ca e h bulk apable of work with both CSV and king XM files using GET or PO HTTP me ML g OST ethods. As wit the other APIs and inbo th A ound web ser rvices youll ne a valid UR endpoint an session. As w Apex web services the Bulk API eed RI nd with b can nnot authentic your appli cate ication so you need to use the Web Serv ull e vices API or O OAuth to est tablish a Force e.com session. Once authe enticated you can execute sp c pecific operatio by polling function-speci URIs. ons ific As an example consider the following: s Cr reate a Job To create a job you would need to issue a POST requ to the UR below. e uest RI https://insta ance_nameapi i.salesforce.com/s services/async/A APIversion/job Ge the Status o a Job et of Retrieving the status of a job would req quire a GET re equest the follo owing URI. https://insta ance_nameapi i.salesforce.com/s services/async/A APIversion/job/j jobId Cl lose a Job To close a job and prev vent more batches from be eing added yo could send a POST ou d req quest to the be elow URI. https://insta ance_nameapi i.salesforce.com/s services/async/A APIversion/job/j jobId Note that for the last tw examples y can specif which job the request sh wo you fy t hould deal with using the jo obId value.
Jeff Dou uglas & Wes Nol lte 255

For those operations initiated with a POST request a valid XML packet is required in the request body. These documents specify information such as the operation type and object type. All response bodies will contain XML that contains information such as the job Id and the job status. Details of these document structures can be found in the Bulk API documentation. Common Best Practices In order to effectively architect your bulk solutions it is important to bear the following restrictions in mind: Records are processed in batches of 200. It is therefore important that your triggers are bulk safe Any imports that you perform using the Web Service API should continue to work with the Bulk API as it uses the same save logic The timeout on batches is 10 minutes so you may have to experiment with batch sizes in order to remain within this limit. It is recommended that you use as large a batch as possible while avoiding these timeouts Batch API jobs send the same success or response CSV file as the Web Services API Null values are processed differently, so instead of sending a blank value in the CSV file, you need to use #N/A instead There is no field truncation header option Binary files such as images or Zip-archives cannot be processed using the Bulk API Be sure to bookmark the Bulk API limits1 Always test in a Sandbox until you are happy with the processing results Parallel processing is quicker than the serial alternative but test thoroughly to make sure your operations do not create record lock errors

Deployment and Modifying the Model with the Metadata API This API is quite distinguishable as instead of working with your salesforce.com data its used to customize your application e.g. it can be used to manage your application customizations programmatically as well as export and migrate meta data. In earlier chapters youve seen that the deployment tools built into Eclipse, as well as the Force.com Migration Tool both use the Meta Data API to retrieve and modify your Orgs structure. Salesforce.com has made this asynchronous API available to you so that you can build your own client applications on top of it. To use this API youll need to download the WSDL document by clicking through Setup -> Develop -> API -> Download Metadata WSDL.

bulk-api-limits Salesforce Handbook


The Metad API suppo two methods of develop data orts pment namely file-based and CRUDy d based. Fil le-Based Met tadata API Ca alls The file-ba ased (or declar rative) Metada API deplo and retrieve calls are used to ata oy mo metadata b ove between a salesforce.com Or and a local f system. rg file It does so by transferrin a zip-file th contains a set of folders and compon ng hat s nents that rep present some o all of your Orgs metadata Within the z or O a. zip-file is a pro oject manifest file called pa ackage.xml that determines which m metadata comp ponents will be considered by the d op peration. An ex xample of a pa ackage.xml file is shown in Listing 5 - 5. n . Listing 5 - 5
<?xml ve ersion=1.0 encoding 0 g=UTF-8?> > <Package xmlns=ht e ttp://soap. .sforce.com m/2006/04/m metadata> <types s> <mem mbers>*</me embers> <nam me>ApexClas ss</name> </type es> <versi ion>16.0</v version> </Packag ge>

In this exa ample the XM markup d ML defines a man nifest that says Fetch or d s deploy all components that are Apex cla asses. The full markup synta can be foun in the Meta l ax nd adata API De evelopers Gui along with all the metada types that can be specified in the manife file. ide ata d est If a source code file is re e emoved from the local file system it is no definite s ot that the de estructive chan will be dep nge ployed to the Force.com serv F vers. You can guaran the remov of applicatio component by creating and using ntee val on ts a manifest file called des structiveCh hanges.xml. Two exam mples applicatio that use these API cal are the Fo ons lls orce.com IDE and the E Fo orce.com Migra ation Tool. CR RUD-Based M Metadata API Calls I The creat , update and delete calls typified by this area of the API w te work with Me etadata in muc the same way that the W Services A operates on your Force.c ch w Web API n com data. Yo can think of these calls mimicking t browser in ou s the nterface when managing ap n pplication me etadata. Although C CRUD means Create, Read, Update and D Delete there is an explicit read-call snt t ava ailable for this Metadata AP call set. Inst s PI tead youll hav to use the retrieve cal that is a ve r ll part of the declar rative Metadat API call set. ta
Jeff Dou uglas & Wes Nol lte 257

The Metadata A doesnt in T API nclude calls to authenticate a session so yo need to us the oull se Web Services API o OAuth to ge a session Id. All subseque calls need to be directed at the S or et ent t URL specified in the metadataS s e ServerUrl va ariable of the L LoginResult. All CRUDt -based calls ar asynchronous and you can use the checkStatus AP call to inter re n PI rrogate the pro ogress of other calls. Note t all respon are of type AsyncResul . that nses e lt An example of call ordering with the CRUD A f w D-based calls i is: 1. 1 2. 2 3. 3 Logged in service call makes a create c to Metadata API n m call An Asyn ncResult object is returne with status information. Operations can be ed queued to completed, or in an error st o o tate Call chec ckStatus in a loop until an end state is re n eached C Check the Metadata API ref ference to see the types tha you can read and e at w write. For exa ample you cou build a Ja application on this API that uld ava n I b builds zip-arch hives and deploys them as static resources on the Force s e.com s servers. Force.com Web Se ervice Connec (WSC) ctor The WSC is a high performi web servic client stack that makes it much easier t use T ing ce to the Fo orce.com API1 from Java. It can be use to generate libraries from the Partne and I ed e er Enterp prise WSDL; t resulting library is simp to use tha those gener the l pler an rated using Ax or xis similar web stack too 2. r ols The connecto also includ a library to integrate the Force.co platform with T or des om applica ations running on Google Ap Engine. g pp Tolera ado This framewor forms a set of web service client wrappe over the Metadata, Enter T rk e ers M rprise, Partne and Apex W er WSDL APIs3. The primary aim of this projects are to: T ms OAuth h Open Authori O ization (OAut is a popu th) ular open-stan ndard that all lows you to share resour between si without ea site having to expose you credentials; instead trusted sites rces ites ach g ur d pass to okens back and forth as a sec d curity measure e.
sfdc-w wsc axis-vs s-wsc 3 tolerad do-web-service-cl lient-wrappers
1 2

Increase fau tolerance ult Cache sessi informatio ion on Provide we service utilit to simply A usage eb ties API Simply mig gration between web stacks n


Salesforce Handb book

OAuth has been widely adopted as a mechanism to integrate sites and web services. Salesforce.com have thus provided the ability to use a baked-in service as an OAuth provider1, and Apex is rich enough to support Force.com applications that are required to be OAuth consumers2.

Path 3: Native ERP & Desktop Connectors

Many companies have SAP and/or Oracle system deeply embedded in their architecture. Connecting these system to the Force.com platform is essential3 for coherence of data and is highly adventitious with regards to data mining. You wont find much about these connectors on the Internet so either contact salesforce.com through your product manager or log a case to learn more. Salesforce.com has also created tools to allow you to connect your salesforce.com Org to Lotus Notes4 and some of the products in the Microsoft Office Suite5. These add the convenience of quickly synchronizing your desktop application data, such as calendar information or data in a spreadsheet, to the Force.com platform.

Path 4: Middleware Connectors

Applications in this category can largely be considered adapters from one system to another. Most of these can be found on the AppExchange and can be used to integrate SQL databases, Google Contacts, Google AdWords, Jigsaw, QuickBooks, payment gateways, file storage and much more.

Path 5: Toolkits
Software in this category is aimed at assisting you to quickly connect a technology platform or application suite to the salesforce.com cloud. A large number of these target integration specifically with the SOAP-based Force.com Web Services API. Salesforce.com has created many of these toolkits but third parties as well as independent developers have also made many noteworthy contributions. PHP Toolkit The PHP toolkit provides an easy way to make Force.com Web service API method calls from within PHP6. It supports both the Enterprise and Partner WSDL but only works with version 13 thus limiting functionality. Rumor has it that it should be updated soon to support later versions.

salesforce-oauth-provider salesforce-oauth-consumer 3 erp-connectors 4 lotus-notes-connector 5 connect-outlook, excel-connector 6 php-toolkit

1 2

Jeff Douglas & Wes Nolte


Self-Service Portal Toolkit for PHP 5 Simplifies the task of embedding a Salesforce Self-Service Portal within a PHP application1. Requires an older version of the PHP Toolkit. Standalone PHP Bulk API Client Although this client toolkit forms a part of Workbench it is also available as a standalone download2. It provides a library to help PHP developers easily work with the Bulk API. AJAX Toolkit The AJAX Toolkit is a powerful and widely used JavaScript wrapper around the Web Services API3. You can use it to execute any call from the API, and access any API objects that you normally have access to. It functions asynchronously with callback functions to handle returned results. It is based upon the partner WSDL since there is no type checking in JavaScript. Adobe Flash Builder for Force.com The Adobe Flash Builder for Force.com allows developers to create powerful, engaging offline and web-based applications running on the Force.com platform. The product, codename Stratus, is a jointly developed Eclipse-based IDE that combines the Force.com IDE, Flex 4 Builder, Flash 4 and LiveCycle Data Services and is tightly integrated with Force.com Connect Offline. It also includes a SQLite database embedded within the Adobe AIR runtime that provides the offline data cache of Salesforce.com data. The framework includes: Login functionality including a UI and error messages. An API for making multiple, asynchronous, web service requests to the Force.com cloud to retrieve, save, or delete records. UI components and data classes for displaying, editing, and managing local data changes. The automatic creation and management of a local data store of salesforce.com data for offline support. When importing the Salesforce.com Enterprise WSDL, Stratus generates ActionScript classes for your objects on the Force.com platform. An API for saving changes to both the local store and the Force.com cloud. Automatic periodic synchronization of data between the local data store and the Force.com cloud. Online and offline data synchronization and management. Support for select * SOQL queries.

1 2

self-service-portal-php-toolkit php-bulk-api-client 3 ajax-toolkit 260 Salesforce Handbook

Salesforce Python Toolkit There are two Python adapters, Beatbox1 and one that uses Suds2, for handling SOAP messaging with the API in Python. Force.com Toolkit for Google Data APIs The Google Data APIs toolkit allows you to access Google authentication and multiple APIs (Contacts, Documents, Spreadsheets, Calendar, Blogger) natively from Apex3. Each API within the Google Data APIs is thoroughly documented for this toolkit. Force.com Office Toolkit The Office toolkit provides a Component Object Model (COM) interface for developers who want to write client applications for Microsoft Office products that use COM technology to access salesforce.com data4. The toolkit acts as an intermediary between COM clients and the API, handling certain tasks implicitly so that client applications are simpler to code. Force.com for Google App Engine The App Engine toolkit (Java and Python) allows developers to access the API from Google App Engine5. The Java Toolkit fully supports the Partner API whereas the Python Toolkit is only capable of making the core API calls. iOS Toolkit for Force.com A creation of Simon Fell, this Objective-C and Cocoa toolkit allows developers to build native OSX (Mac) and iOS (iPhone) applications for the Force.com platform6. Force.com for Amazon web services The toolkit enables access to Amazon S3 and EC2 for building Force.com applications that integrate with Amazon Web Services7. The toolkit provides a framework for authentication, native access to the AWS Simple Storage System for data manipulation and prebuilt Amazon Machine Images. Force.com for Facebook The new Force.com for Facebook provides developers with direct access to the Facebook APIs from Apex code8. It provides support for the Graph API, OAuth2 for authorization, JSON data exchange, social plugins, extended permissions and more.
beatbox-python-toolkit suds-python-toolkit 3 toolkit-google-data-apis 4 toolkit-office 5 toolkit-google-app-engine 6 zkSforce 7 toolkit-amazon-web-services 8 toolkit-facebook
1 2

Jeff Douglas & Wes Nolte


ActiveSalesforce ActiveSalesforce is a Ruby on Rails framework connection adapter that provides direct access to Force.com data via the Web Services API and Rails Active Record model layer1. Perl Toolkit A Perl class that provides a simple abstraction layer between SOAP::Lite and Force.com2. Force.com for PayPal X Payments Platform The toolkit allows you to extend your Force.com applications to easily handle payments, preapprovals for payments, refunds, and the use of foreign exchange currency conversion rates. The toolkit provides direct access through native Apex code to the Adaptive Payments and Adaptive Accounts APIs SalesforceCFC - A ColdFusion Toolkit for Force.com An Adobe ColdFusion CFC that allows you to connect and work with Force.com by generating SOAP requests and parsing their responses3.

toolkit-ruby-on-rails toolkit-perl 3 toolkit-coldfusion

1 2


Salesforce Handbook

Advanced Develop A pment Ex xamples

hrough the course of our journey with salesforce.com and the For r m rce.com Platfo weve orm discovered a number of common patterns and b f best practices in the prog grammatic dev velopment are Having mo ena. olded these co ookie-cutter solutions and no oticed their ove erlap with common questio around th community weve posted a number of these on vario blogs ons he ous and forums. In this chap weve coll pter lated many of our most usef articles into a single area f you to ful o for use as training exercises or reference mat e r terial when en ncountering a complex dev velopment pro oblem.

Using Extern ID Field nal ds

Salesforce.c com has bake in some ed magical featu ures into its platform. Tw of our wo fav vorites are the upsert co e ommand and the use of External IDs. If you are ne to the I ew pla atform, youve probably seen the option o making a fie an Extern ID during the new e n of eld nal g fie creation pro eld ocess.

Figu 6 - 1. Setting a field as an E ure gs External ID.

The Extern ID field al nal llows you to store unique r record IDs fro an externa system, om al typ pically for inte egration purposes. So if you have a bespok marketing system running on SQL ke s g Server, it is may be easier to lo update and reference the external re oad, d ese ecords in salesf force.com usi unique IDs from SQL Se ing erver. Salesforce.c com allows yo mark up to 3 fields as E ou o External IDs an these fields must be nd s tex number or email field typ Values in these External ID fields must also be un xt, pes. n m nique and you can also det termine whether or not valu are case sen ues nsitive. There are three ways that you s typ pically use Ext ternal ID fields s.

Loading Data from External Systems When you load data from external systems you may want to track the record from the external system for reference or if you want to make updates back into the external system. Simply mark a field as an External ID and the Force.com platform will ensure that each value is unique and that you dont load duplicate records from the external system. Making Fields Searchable When searching for custom object records from the sidebar the following fields are searchable: Name All custom auto number fields

You can make fields searchable by marking them as an External ID. Some people cheat and mark fields that do not necessarily contain external record IDs so that they are searchable. For the advanced search, the following fields are searchable: All custom fields of type text Text area Email Phone

So if you have a numeric field that is an External ID it will not be searchable via the advanced search. You could create a text External ID field and then write a workflow that updates this field from the numeric External ID field. This way your external ID is searchable. Data Integration This is where the External ID field really earns its keep. When using the upsert command during data loading, you can reference the External ID field instead of the salesforce.com ID. This is a huge advantage because you typically dont want to maintain the salesforce.com ID in your external system. When uploading data with the Import Wizard, Data Loader or (most) ETL tools like Boomi or Informatica, there is a setting to specify that a field is an External ID.


Salesforce Handbook

Sa alesforce.com Import Wiza ard

F Figure 6 - 2. Usin External IDs with the salesfo ng orce.com Impor Wizard. rt

Da Loader ata

Figure 6 - 3. Using Exte ernal IDs with th Data Loader. he

Jeff Dou uglas & Wes Nol lte


Boom Atomsphere mi e

Figu 6 - 4. Using External IDs with the third-part integration to ure E ty ools.

If you are load data from an external sy I ding ystem, Externa IDs will defi al finitely become your e best fr riends.

Visua alforce Com mponent Ids & JavaScr s ript

Salesforce.com used in conju S m unction with Ja avaScript and A can be ve impressive One Ajax ery e. simple frustration weve come acro is that of r e oss retrieving elem ments by Id. Sal lesforce.com h an has intellig gent scheme in place, which ensures that HTML eleme n h ents dont hav duplicate Id and ve ds therefo conform to W3C standar Consider t following V ore o rds. the Visualforce co in Listing 6 - 1. ode Listing 6 - 1. A Simple Visu L ualforce Page e
<apex:page id=thePag < ge> geBlock id= =theBlock > <apex:pag <apex:o outputText id=theTex xt /> </apex:pa ageBlock> </apex:page < e>

Id for the outp putText field would be f thePa age:theBloc ck:theText and not sim mply theTex . In terms of web-stan xt s ndard confor rmity this is gr reat, but for the beginner com e mbining JavaSc cript and Visua alforce this can be a n nightm mare. Imagine you have an outputText field nested ten levels dee within the page. t ep Were you to hardco the Id of this element within your JavaScript you have to bea the ode f t u ar follow in mind: wing Salesforce e.com give ele ements random Id values if you dont ass m sign them expl licitly. To preven this you hav to assign an Id to each par element. nt ve n rent If you cha ange the page tree structure that precedes said element, you have to ch hange the Id ref ferenced in you JavaScript. ur

The T

generat ted

element t

Not the most fun youve ha and a lot o hard work if you ask me Luckily ther is a N ad, of e. re simple solution, and its easily ma e d aintained as well as flexible. All you have to do is assig the gn
266 Salesforce Handb book

element value to a JavaScript variable just after it appears in the page (or at the same level within the DOM tree). The code would become: Listing 6 - 2. JavaScript Variable Bound to Visualforce Component
<apex:page id=thePage> <apex:pageBlock id=theBlock> <apex:outputText id=theText /> <script> var theText = document.getElementById({!$Component.theText}); </script> </apex:pageBlock> </apex:page>

Now you can reference the JavaScript variable theText from within you JavaScript code without worrying about changes to the DOM or assigning Ids to all parent elements.

Passing JavaScript Values to Apex

Quite often weve needed to manipulate variable values in-page (Visualforce) with JavaScript, and then pass these modified values to Apex or a Standard Controller. The proposition is that you should be able the grab the input elements in a Visualforce page and then, using JavaScript, modify or add values to a form just before its submitted. An example is shown in Listing 6 - 3. Listing 6 - 3. Assigning JavaScript Values to Visualforce Components
<apex:page standardController=experiment__c> <script> var v = Hello World; </script> <apex:form> <! This can be any input-type field > <apex:inputHidden id=theField /> value={!experiment__c.string__c}

<! This is a method to get an element (or its Id) without hardcoding values > <script> var theField = document.getElementById({!$Component.theField}); </script> <! Grab the value of the Javascript variable and write it to the database > <apex:commandButton onclick=theField.value=v;
Jeff Douglas & Wes Nolte 267

action={!save} value=save/> </apex:form> </apex:page>

If you were to click the button youd save Hello World as a field value for that Experiment__c record. The great Dave Carroll has documented another neat approach to this solution on the Force.com Blog1.

ActionSupport with Facets and JavaScript

You can make your UI much easier on your users by giving them clues on what is taking place when they click buttons, enter text or choose items in a picklist. This example shows how you can notify a user that something is taking place in the background when you are performing actions asynchronously. For the sake of example, it uses both facets and JavaScript. In this example the user simply enters their name in the text box. In Listing 6 - 4 below weve added an actionSupport component to the inputText component. This allows us to invoke a method (specified in the action attribute) in the controller as the result of a JavaScript event. The attributes for the actionSupport component indicate:
action the method to be invoked in the controller event the JavaScript event that invokes the method reRender the IDs of the components that are redrawn as a result of the AJAX update request returned from the controller status the ID of the component that displays the status of the AJAX update


So when the user enters their name and removes focus from the text box, the JavaScript event fires and invokes the method in the controller. The status component is also invoked to display the messages to the user. In this case the start attribute calls the JavaScript start( ) method, which dynamically modifies HTML elements on the page. When the AJAX call returns from the controller, the actionStatus component specifies that the stop facet should be displayed as well as the stop( ) JavaScript method. This modifies HTML elements and displays messages to the user. The actionSupport component invokes a reRender of the pageMessage and thankyou outputPanel components so that our new messages from the controller display properly. Listing 6 - 4. Providing Feedback to Users in Visualforce
<apex:page controller=ActionSupportExampleController> <script type=text/javascript>

passing-javascript-values-to-apex Salesforce Handbook


function start( ) { document.getElementById(processingStatus). innerHTML = Process started...; document.getElementById(thankyouDiv).innerHTML = ; } function stop( ) { document.getElementById(processingStatus).innerHTML ; document.getElementById(thankyouDiv). innerHTML = Processing complete; } </script> <apex:outputPanel id=pageMessage> <PageMessages /> </apex:outputPanel> <apex:actionStatus id=status onStart=start( ); onStop=stop,stop( );> <apex:facet name=stop> <h1>Idle... waiting...</h1> </apex:facet> </apex:actionStatus> <div id=processingStatus></div> <apex:form > Please enter your name and click off of the text box: <apex:inputText value={!yourName} > <apex:actionSupport action={!processName} event=onblur reRender=pageMessage,thankyou status=status/> </apex:inputText> </apex:form> <div id=thankyouDiv></div> =

Jeff Douglas & Wes Nolte


<apex:outputPanel id=thankyou> <apex:outputText value={!thankYouMsg}/> </apex:outputPanel> </apex:page>

The controller for this example is fairly simple as seen in Listing 6 - 5. The constructor simply initializes the value of counter to 0 when initially loaded. Each time that the user removes focus from the textbox, the processName( ) method is called. This method increments the counter and passes text to the addThankYou and addPageMessage methods. These methods construct the text for the messages displayed to the user. Listing 6 - 5. The Controller for the page in Listing 6 - 4
public class with sharing ActionSupportExampleController { public String thankYouMsg {get;set;} public String yourName {get;set;} private Integer counter {get;set;} public ActionSupportExampleController( ) { counter = 0; } public PageReference processName( ) { counter += 1; addThankYou(yourName); addPageMessage(Your name is: + yourName); return null; } private void addPageMessage(String t) { ApexPages.addMessage(new ApexPages.Message( ApexPages.Severity.INFO, t)); } private void addThankYou(String t) { thankYouMsg = Thanks + t + . You are a peach. You have loaded this page + counter + times.; }
270 Salesforce Handbook

Not every Visualforce component supports partial page refreshes. If you are using one that is not supported, you can wrap it in an outputPanel component in order to action a reRender.

Passing Parameters with a CommandLink

Listing 6 - 6 is a small example of how you can pass a value to another method via a
commandLink. When the link is clicked, the setter fires for the public member nickName. The button click then calls the processLinkClick( ) method where you can do something

like process the variable further with DML statement or running a SOQL query with the value. Listing 6 - 6. Commandlink Passing Parameter Values to a Controller
<apex:page standardController=Contact extensions=CommandLinkParamController> <apex:form > <apex:commandLink value=Process Nickname action={!processLinkClick}> <apex:param name=nickName value={!contact.firstname} assignTo={!nickName}/> </apex:commandLink> </apex:form> </apex:page>

The processLinkClick( ) method in Listing 6 - 7 is called after the setters fire, performs some processing and returns a null PageReference allowing the Visualforce page to refresh. Listing 6 - 7. The Controller Extension
public with sharing class CommandLinkParamController { // an instance varaible for the standard controller private ApexPages.StandardController controller {get; set;} // the object being referenced via url private Contact contact {get;set;} // the variable being set from the commandlink public String nickName {get; set;} // initialize the controller
Jeff Douglas & Wes Nolte 271

public CommandLinkParamController( ApexPages.StandardController controller) { //initialize the stanrdard controller this.controller = controller; // load the current record this.contact = (Contact)controller.getRecord( ); } // handle the action of the commandlink public PageReference processLinkClick( ) { System.debug(nickName: +nickName); // now process the variable by doing something... return null; } }

Passing Parameters with a CommandButton

In theory you should just be able to switch out the CommandLink component with a CommandButton component and be golden. However there seem to still be a bug with the CommandButton component. Listing 6 - 8 is a Visualforce page with the CommandButton instead of the CommandLink. Listing 6 - 8. Visualforce Page with CommandButton and Param
<apex:page standardController=Contact ensions=CommandButtonParamController> <apex:form> <apex:commandButton value=Process Nickname action={!processButtonClick}> <apex:param name=nickName value={!contact.firstname} assignTo={!nickName}/> </apex:commandButton> </apex:form> </apex:page>


Salesforce Handbook

As with the CommandLink, when the user clicks the button the setters should fire and then call the processButtonClick( ) method to allow further publishing. However, the setter for nickName is never called! Listing 6 - 9. Controller Extension for the page in Listing 6 - 8
public with sharing class CommandButtonParamController { // an instance varaible for the standard controller private ApexPages.StandardController controller {get; set;} // the object being referenced via url private Contact contact {get;set;} // the variable being set from the commandbutton public String nickName { get; // *** setter is NOT being called *** set { nickName = value; System.debug(value: +value); } } // initialize the controller public CommandButtonParamController( ApexPages.StandardController controller) { //initialize the stanrdard controller this.controller = controller; // load the current record this.contact = (Contact)controller.getRecord( ); } // handle the action of the commandButton public PageReference processButtonClick( ) { System.debug(nickName: +nickName); // now process the variable by doing something... return null; }
Jeff Douglas & Wes Nolte 273

You can make the Comman Y e ndButton function as adv vertised if you use a reRender u attribu and hidden pageBlock component. I you run the Visualforce pa in Listing 6 - 10 ute n If age with th modificat hese tions the setter will actually fi and set the value of nick r fire kName correct tly. Listing 6 - 10. CommandBu L utton with Pa arams Hack
<apex:page standardCo < ontroller= Contact ons=Comman ndButtonPar ramControll ler> extensio <apex:form> < > <apex:co ommandButto value=P on Process Nic ckname action n={!proces ssButtonCli ick} rerender=hidd denBlock> <apex: :param name e=nickName e valu ue={!conta act.firstna ame} assi ignTo={!ni ickName}/> > </apex:c commandButt ton> <apex:pa ageBlock id d=hiddenBl lock rend dered=fals se/> </apex:form < m> </apex:page < e>

Using Anonymo Code Bl g ous locks

As Anonymous bl A locks provide the ability to e t execute a sectio of Apex code on the fly. A an on examp imagine th you need to clean your sa ple, hat o alesforce.com data. Either youve changed your d logic and that data is affecting func a s ctionality, or p perhaps you ne to remove data en masse This eed e. is simp with Anon ple nymous Blocks just write up a short scrip that will res s; p pt store your data to a a cleaned state and sa it for futu use. Any t ave ure time things ge messy just run your scrip the et r pt baselin will be reestablished. The scripts would be written in Apex code without the nee for ne e d n w ed the enclosing class st tructure (altho ough feel free t declare class within your scripts). to ses r O danger wi code execu One ith uted in Anonym mous Blocks is that the ease with i e w which the scri ipts can be inv voked makes it tempting to run code wi o ithout f testing it. Rather spend 2 minutes tes first R 20 sting scripts in a sandbox tha run an t them immedia ately in produc ction; and then working for several days to fix n r c corrupt data. You can execut code in this fashion from 3 separate area Y te as: 1. The in-brow System Log 1 wser L


Salesforce Handb book

F Figure 6 - 5. Lin for the System Log at the top of the browser window. nk m p

2. The Fo orce.com IDE

Figure 6 - 6. Execute Anon 6 nymous tab in th Force.com ID he DE

3. The exe ecuteAnonymo Force.com Web Services API call ous m

ExecuteA AnonymousRe esult execu uteAnonymou us(String code) c

Co onsiderations s There are a number of considerations when workin with Anony c ng ymous Blocks, the only , on we encount often bein that you ca ne ter ng annot reference variables before their declaration b within the code i if a variabl is declared a line 40, a me i.e. le at ethod declared before this lin cannot d ne ref ference said va ariable.

Use an Inline Visualforc Page with Standard Page Layou e ce h uts

Using stand dard page layo is easy; th outs hrow some fie on the pag arrange som related eld ge, me list and then es ts ssentially forge about the p et page. However if you really need to custo r, omize the use experience you are almo always forc to write a custom Visu er ost ced ualforce page that may req quire maintena ance in the futu But what if you just wan to tweak the page layout a give it ure. nt e and a li Visualforc oomph? Per ittle ce rhaps a custom related list fr m rom multiple objects, a Flick mashup o kr or a Google map of your conta p acts current lo ocation? You can ad Visualforce pages to stand page layou in the same way you cou with Sdd dard uts e uld Co ontrols. The us case is that you have accounts with hundreds of oppo se y ortunities each and users
Jeff Dou uglas & Wes Nol lte 275

are get tting tired of scrolling throug pages and p gh pages of record to find the ones that they need. ds o In this example you develop a Visualforce pag and controller extension that provides them s ull V ge with an opportunity search interfa on the acco n ace ount details pa Figure 6 - 7 shows what were age. lookin to build. ng

Figur 6 - 7. Visualforce Search Page Embedded in the Standard La re e ayout

First we need t create the Visualforce pag and controll extension as detailed in L F to V ge ler a Listing 6 - 11. Your Visualfo page mus use the stand . force st dard account c controller (as shown in Listin 6 s ng 12) or it will not sho up on the li of available Visualforce pa on the page layout. ow ist ages Listing 6 - 11. The Search Page Controll Extension L P ler n
public clas with sha p ss aring Oppor rtunitySearchControl ller { //added an instanc varaible for the s ce e standard controller .StandardCo ontroller c controller {get; set t;} private ApexPages. actual acco ount // the a private Account a; ; results fro the sear om rch. do not init the results o t or // the r //a blan rows sho up initi nk ow ially on pa age load public L List<opport tunity> sea archResults {get;set;} s // the t text in the search bo e ox public s string sear rchText { get { he box for eas of use se // prefill th serach b
276 Salesforce Handb book

if (searchText == null) searchText = Acme; return searchText; } set; } public OpportunitySearchController( ApexPages.StandardController controller) { //initialize the stanrdard controller this.controller = controller; this.a = (Account)controller.getRecord( ); } // fired when the search button is clicked public PageReference search( ) { if (searchResults == null) { // init the list if it is null searchResults = new List<opportunity>( ); } else { // clear out the current results if they exist searchResults.clear( ); } // Note: you could have achieved the same results as above // by using: searchResults = new List<categoryWrapper>( ); // use dynamic soql to find the related opportunities by name String o.CloseDate, qry = Select o.Id, o.Name, o.StageName,

o.Amount from Opportunity o Where AccountId = \+a.Id+\ And o.Name \%+String.escapeSingleQuotes(searchText)+ %\ Order By o.Name; searchResults = Database.query(qry); return null; } }
Jeff Douglas & Wes Nolte 277


Listing 6 - 12. The Visualforce Search Page

<apex:page standardController=Account extensions=OpportunitySearchController> <style type=text/css> body {background: #F3F3EC; padding-top: 15px} </style> <apex:form > <apex:pageBlock title=Search for Opportunities by Keyword id=block mode=edit> <apex:pageMessages /> <apex:pageBlockSection > <apex:pageBlockSectionItem > <apex:outputLabel for=searchText> Keyword </apex:outputLabel> <apex:panelGroup > <apex:inputText value={!searchText}/> id=searchText

<apex:commandButton value=Search action={!search} rerender=resultsBlock status=status/> </apex:panelGroup> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:actionStatus id=status startText=Searching... /> <apex:pageBlockSection id=resultsBlock columns=1> <apex:pageBlockTable value={!searchResults} var=o rendered={!NOT(ISNULL(searchResults))}> <apex:column headerValue=Name> <apex:outputLink value=/{!o.Id}> {!o.Name} </apex:outputLink> </apex:column>
278 Salesforce Handbook

<apex:col lumn value= ={!o.Stage eName}/> <apex:col lumn value= ={!o.Amoun nt}/> <apex:col lumn value= ={!o.Close eDate}/> </ /apex:pageB BlockTable> > </ape ex:pageBloc ckSection> </apex:p pageBlock> </apex:f form> </apex:p page>

Now all yo simply have to do is add this new Visu ou e ualforce page to your page la t ayout and the job is done. e

F Figure 6 - 8. Add the Visualforce page to new se d e ection of the pag layout. ge

Ap Search with Check pex kbox Result using a W ts Wrapper Cla ass
This demo is a single Ap custom controller, two V pex Visualforce pag and a wrap ges pper class allo owing the user to search an object by keyw r word (via Dyn namic SOQL) and return the results in a a pageBlockTa p able with corresponding checkboxes. Se electing one or more checkb r boxes and clicking the See Results bu utton displays t list of the s the selected items. .
Jeff Dou uglas & Wes Nol lte 279

This is a very common fun T nction, as you typically want to search fo records and then t or d proces the selected subset. ss Y You can run this sample at http://jeff n e ffdouglas-developer-edition.na5.forc ce.com/ e examples/category ry_search Listing 6 - 13. Custom Con L ntroller for Sea arching Categ gories
public clas with sha p ss aring Categ gorySearchController { r // the r results fro the sear om rch. do not init the results e //or a b blank rows show up in nitially on page loa ad public L List<catego oryWrapper> searchResults {get > t;set;} // the c categories that were checked/selected. public L List<catego oryWrapper> selected > dCategories { s get { Categories == null) if (selectedC s selectedCat tegories = new List<c categoryWrapper>( ); ret turn select tedCategori ies; } set; } text in the search bo e ox // the t public s string sear rchText { get { he box for eas of use se // prefill th serach b xt ) xt gory; if (searchTex == null) searchTex = Categ turn search hText; ret } set; } public Cate p egorySearch hController ) {} r( // fired when the search but d tton is clicked public Page p eReference search( ) {


Salesforce Handb book

if (searchResults == null) { // init the list if it is null searchResults = new List<categoryWrapper>( ); } else { // clear out the current results if they exist searchResults.clear( ); } // Note: you could have achieved the same results as above // by using: searchResults = new List<categoryWrapper>( ); // dynamic soql for fun String c.Name LIKE \%+String.escapeSingleQuotes(searchText)+%\ Order By c.Name; // may need to modify for governor limits?? for(Cat3__c c : Database.query(qry)) { // constructor create a new wrapper pass category to the qry = Select c.Name, c.Id From Cat3__c c Where

CategoryWrapper cw = new CategoryWrapper(c); // add the wrapper to the results searchResults.add(cw); } return null; } public PageReference next( ) { // clear out the currently selected categories selectedCategories.clear( ); // add the selected categories to a new List for (CategoryWrapper cw : searchResults) { if (cw.checked) selectedCategories.add(new CategoryWrapper(cw.cat)); }
Jeff Douglas & Wes Nolte 281

// ensure they selected at least one category if (selectedCategories.size( ) > 0) { return Page.Category_Results; } else { ApexPages.addMessage(new ApexPages.message(ApexPages.severity.ERROR, Please select at least one Category.)); return null; } } // fired when the back button is clicked public PageReference back( ) { return Page.Category_Search; } }

Listing 6 - 14. The Visualforce Search Page

<apex:page controller=CategorySearchController> <apex:form > <apex:pageBlock mode=edit id=block> <apex:pageBlockButtons> <apex:commandButton Results disabled={!ISNULL(searchResults)}/> </apex:pageBlockButtons> <apex:pageMessages /> <apex:pageBlockSection > <apex:pageBlockSectionItem > <apex:outputLabel for=searchText> Search for Categories </apex:outputLabel> <apex:panelGroup > action={!next} value=See


Salesforce Handbook

<apex:inputText value={!searchText}/> ->


<!-- We could have rerendered just the resultsBlock <!-- below but we want the See Results button --> <!-- to update also so that it is clickable. --> <apex:commandButton value=Search action={!search} rerender=block status=status/> </apex:panelGroup> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:actionStatus id=status startText=Searching... <apex:pageBlockSection title=Search Results id=resultsBlock columns=1> <apex:pageBlockTable value={!searchResults} var=c rendered={!NOT(ISNULL(searchResults))}> <apex:column width=25px> <apex:inputCheckbox value={!c.checked}/> </apex:column> <apex:column headerValue=Name/> </apex:pageBlockTable> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> value={!c.cat.Name}

Listing 6 - 15. Visualforce Results Page

<apex:page controller=CategorySearchController> <apex:form > <apex:pageBlock > <apex:pageBlockButtons > <apex:commandButton action={!back} value=Back/>

Jeff Douglas & Wes Nolte


</apex:pageBlockButtons> <apex:pageMessages /> <apex:pageBlockSection title=You Selected columns=1> <apex:pageBlockTable var=c> <apex:column value={!c.cat.Name}/> </apex:pageBlockTable> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> value={!selectedCategories}

Listing 6 - 16. The SObject Wrapper Class

public class CategoryWrapper { public Boolean checked{ get; set; } public Cat3__c cat { get; set;} public CategoryWrapper( ){ cat = new Cat3__c( ); checked = false; } public CategoryWrapper(Cat3__c c){ cat = c; checked = false; } public static testMethod void testMe( ) { CategoryWrapper cw = new CategoryWrapper( ); System.assertEquals(cw.checked,false); CategoryWrapper cw2 = new CategoryWrapper(new Cat3__c(name=Test1)); System.assertEquals(cw2.cat.name,Test1); System.assertEquals(cw2.checked,false); } }
284 Salesforce Handbook

Dependent M Multi-level Pick Lists P

This demo details how to create a Vi o t isualforce page with 3 pickl e lists which ope erate in a hie erarchy i.e. the values availab in the secon picklist are dependent on what has been selected e ble nd n n in the first, and the values in the third pickl are similarl dependent on the value selected in t list ly o the second pickli In this exam the pickl e ist. mple lists span 3 sep parate custom objects. o

Figure 6 - 9. Visualforce P Page Showing Dependent Pickli ists

Listing 6 - 17. Visualfor Page Containing Pickl rce lists

<apex:pa age standar rdControlle er=Opportu unity exten nsions=Mul ltiSelectCo ontroller> > <apex:se ectionHeade title=O er Opportunity y subtitle={!opp portunity.n name}/> orm > <apex:fo <apex:pa ageBlock ti itle=Oppor rtunity mo ode=edit> > <apex x:outputTex value={!opportuni xt ity.Cat1__c c} ren ndered=fal lse/> <apex x:outputTex value={!opportuni xt ity.Cat2__c c} ren ndered=fal lse/> <apex x:outputTex value={!opportuni xt ity.Cat3__c c} ren ndered=fal lse/> <apex x:pageBlock kButtons lo ocation=bo oth> <ap pex:command dButton val lue=Save action={! !save} /> <ap pex:command dButton val lue=Cancel action= l {!cancel} /> </ape ex:pageBloc ckButtons> <apex x:pageMessa ages />
Jeff Dou uglas & Wes Nol lte 285

<apex:pageBlockSection columns=1>



<apex:pageBlockSectionItem > <apex:outputLabel value=Category 1 for=cbxlevel1/> <apex:outputPanel styleClass=requiredInput layout=block> <apex:outputPanel styleClass=requiredBlock layout=block/> <apex:selectList value={!selectedLevel1} id=cbxlevel1 size=1 required=true> <apex:selectOptions value={!level1items}/> <apex:actionSupport event=onchange rerender=cbxlevel2/> </apex:selectList> </apex:outputPanel> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value=Category 2 for=cbxlevel2/> <apex:selectList value={!selectedLevel2} id=cbxlevel2 size=1> <apex:selectOptions value={!level2items}/> <apex:actionSupport event=onchange rerender=cbxlevel3/> </apex:selectList> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value=Category 3 for=cbxlevel3/> <apex:selectList value={!selectedLevel3} id=cbxlevel3 size=1> <apex:selectOptions value={!level3items}/> </apex:selectList> </apex:pageBlockSectionItem>
286 Salesforce Handbook

</apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>

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<selectOption> level1Items { get { List<selectOption> options = new List<selectOption>( ); 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<selectOption> level2Items { get { List<selectOption> options = new List<selectOption>( ); if (selectedLevel1 != NULL) {

Jeff Douglas & Wes Nolte


options.add(new ));



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<selectOption> level3Items { get { List<selectOption> options = new List<selectOption>( ); 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 the sele et ected value to the r es 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 exPages.Sta andardContr roller(opp) )).view( ); ; retur (new Ape } }

Up ploading a Document using Visu ualforce

The salesfo orce.com docu umentation fo the inputF or File Visualfo orce componen has an nt exa ample of uplo oading a docum ment using the Standard Co ontroller. Here is a quick ex e xample of usi a Custom Controller in case you w ing m n want to make the upload pr rocess part of a larger f tra ansaction.

Figure 6 - 10. Visualforce Form for Up e ploading a File

Jeff Dou uglas & Wes Nol lte


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 documents 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, youll 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

<apex:page controller=FileUploadController> <apex:sectionHeader title=Visualforce Example subtitle=File Upload Example/> <apex:form enctype=multipart/form-data> <apex:pageMessages /> <apex:pageBlock title=Upload a File> <apex:pageBlockButtons > <apex:commandButton action={!upload} value=Save/> </apex:pageBlockButtons> <apex:pageBlockSection showHeader=false columns=2 id=block1> <apex:pageBlockSectionItem > <apex:outputLabel value=File Name for=fileName/> <apex:inputText value={!document.name} id=fileName/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value=File for=file/> <apex:inputFile value={!document.body} filename={!document.name} id=file/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value=Description for=description/> <apex:inputTextarea value={!document.description} id=description/>
290 Salesforce Handbook

</apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value=Keywords for=keywords/> <apex:inputText value={!document.keywords} id=keywords/> </apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page>

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 users 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 tate document.bod = null; -- clears the viewst n nt( ); document = new Documen } Message(new ApexPages w s.message( ApexPages.addM everity.INF FO,File up ploaded suc ccessfully )); ApexPages.se return null; } }

Uploading an Attachment using Visua u alforce

This demo bu T uilds upon th previous o he one, showing an example for uploadin an g ng attachm ment for a co ontact. The Visualforce pa and Contr V age roller is very similar with a few except tions.

Fig gure 6 - 11. Visua alforce Form for Uploading a co r ontact Attachme ent

Attachments a different than Docume A are t ents and are only available for the follo e owing objects:

Account Asset Campaign Case Contact

Salesforce Handb book

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
<apex:page controller=AttachmentUploadController> <apex:sectionHeader title=Visualforce Example subtitle=Attachment Upload Example/> <apex:form enctype=multipart/form-data> <apex:pageMessages /> <apex:pageBlock title=Upload a Attachment> <apex:pageBlockButtons > <apex:commandButton action={!upload} value=Save/> </apex:pageBlockButtons> <apex:pageBlockSection showHeader=false columns=2 id=block1> <apex:pageBlockSectionItem > <apex:outputLabel value=File Name for=fileName/> <apex:inputText id=fileName/> value={!attachment.name}

Jeff Douglas & Wes Nolte


</apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel value=File for=file/> <apex:inputFile value={!attachment.body} filename={!attachment.name} id=file/> </apex:pageBlockSectionItem> <apex:pageBlockSectionItem > <apex:outputLabel for=description/> id=description/> </apex:pageBlockSectionItem> </apex:pageBlockSection> </apex:pageBlock> </apex:form> </apex:page> value=Description

<apex:inputTextarea value={!attachment.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)); return null; } finally { attachment = new Attachment( ); } ApexPages.addMessage(new ApexPages.message( ApexPages.severity.INFO,Attachment uploaded successfully)); return null; } } uploading

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. 2. Create a stylesheet with however many styles. At this point (unless youve used an external editor) you have no way of quick-viewing the result. 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. Upload the zip file as a static resource. Create references to the stylesheet in appropriate pages. View page.

3. 4. 5.

If at this point you need to adjust your coded CSS youll 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


Visual lforce Pages a Stylesheet Documents as The Visualforc page com T ce mponent has an attribute ca n alled content tType. Setting this g attribu to text/c will instru the page to render as a C document You can the use ute css uct o CSS t. en the st tylesheet co omponent to in nclude this C page in th pages you wish to style. CSS he w Pros Cons Not efficien as cant be minified or com nt m mpressed You lose th neat organiz he zation of the tr raditional arran ngement of file and folders es Quick pro ototyping of st tylesheets as th can be edit in the Forc hey ted ce.com IDEs Can include calls to controller method and global va ds ariables so valu can be dyna ues amic Can inclu static resou ude urces as images s

Plaint text Static Resources as Sty ylesheet Documents Here youll nee to upload an empty text file or an exis H ed a sting stylesheet - in their pla t aintext form - as a static resource. Next yo need to su oull ubscribe to the metadata for that static res e r source in an Eclipse project Double click on the file in the IDE w open it in plaintext in its own E t. king e will p s tab and (voila!) youl be able to ed the contents directly. d ll dit s To include th styleshe T he eet in a pag all youll n ge need is the standard style esheet compo onent, and then refer to the static resource by name. n s e Pros Cons Cant refe erence any reso ource outside o the file of Not effici as theyre not minified o compressed ient or You lose the neat orga anization of th traditional arrangement of files and fo he o olders, and will p probably end up with a prolif u feration of CSS static resourc files S ce Quick pro ototyping of st tylesheets as th can be edit in the Forc hey ted ce.com IDEs

In reality we te to use one of the above approaches until our CSS reaches a rela I end e atively compl state with regards to ou project goa Once we a done we bundle the CSS and lete ur als. are b images into a well-o s organized folder structure w which we then compress and upload as a static d resour Of course then youll nee to update an pages that r rce. ed ny referenced the old static reso ource. C you gues how to mi Can ss inimize risk h here? What ab bout wrappin the ng r reference to th stylesheet in a component and using tha in all your p he n t at pages? O perhaps us Or sing a Visualfo orce page as a site template and only incl luding s stylesheets ther Either way you only need to make chan in one plac re? y d nge ce.
296 Salesforce Handb book

Redirecting Users to Different Visualforce Pages

If your Org has a large number of records types, page layouts and Visualforce pages youll 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 well 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. Youll 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
<apex:page standardController=Contact extensions=DispatcherContactEditController action={!nullValue(redir.url, urlFor($Action.Contact.Edit, contact.id, null, true))}> </apex:page>

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
<apex:page standardController=Contact extensions=DispatcherContactEditController action={!nullValue(redir.url, urlFor($Action.Contact.Edit, contact.id, null, true))}> </apex:page>

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;


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

<apex:page standardController=Contact extensions=DispatcherContactNewController action={!nullValue(redir.url, urlFor($Action.Contact.New, null, null, true))}> </apex:page>

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) == 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, 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. Its difficult to find information on which areas are case-sensitive so weve compiled this list of what weve 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
<apex:page id=MyTemplate> <apex:sectionHeader title=The Heading/> <apex:insert name=Content/> </apex:page>

Listing 6 - 32. A Visualforce Content Page that Implements the Template Page
<apex:page> <apex:composition template=MyTemplate> <apex:define name=Content> <apex:outputText value=Custom Content/> </apex:define> </apex:composition> </apex: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 isnt 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<String> mySet = new Set<String> {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).


Salesforce Handbook

Co omponent Ids & ReRende s er Visualforce component Ids are case-se e I ensitive when used in a reRender attrib bute. Our gu uess is that thi area is caseis -sensitive beca ause JavaScrip (a case-sensi pt itive language) is being ) use behind the scenes. ed Sa alesforce.com 15 character Ids 15 characte IDs are case er e-sensitive, bu 18-character IDs are caseut r -insensitive. Th is an here alg gorithm for changing betwee the two, but the easiest wa to do this are en t ays a Use the FIXID( ) formula in the Excel Connec e f ctor Use Jef Douglas Force.com Utility Belt for sales ff y sforce.com Assign an Id containe String-value variable to an Id-value variable in Apex ed e n

Most String me ethods This area o case-sensitiv is quite lo of vity ogical since the methods are tasked with working ese a h specifically on te More info ext. ormation on S String methods can be found in the salesf s d force.com Do ocumentation.

Ca alling a REST Web Ser rvice (XML L)

This is an e example of cal lling a REST w service wi Apex. You enter your ad web ith ddress and the Apex code f e fetches the geo coordinates f o from Yahoo! M Maps. The ser rvice returns th data as he XM ML. If you want to run this de t emo in your ow Org, you w need to do the following: wn will : Add a Remote Site (Setup - Security Controls -> Remot Site e -> y s te Setting) with the URL: http:// U /local.yahooapis.com m You can run this sam mple at https://jeffdouglas-deve eloper-edition.na5 5.force.com/ examples/R RestDemo

The Visual lforce page in Listing 6 - 3 presents th user with address fields that they n 34 he a sub bmit to the c controller. The controller ca the REST web service and then dis e alls T splays the res sulting geo coo ordinates to th user. he Listing 6 - 34. Visualfor Address S rce Search Using Yahoo! Maps s
<apex:pa age control ller=RestD DemoControl ller tabSt tyle=Contact> <apex:se ectionHeade title=Y er Yahoo Maps Geocoding subti itle=REST Demo/> <apex:fo orm >
Jeff Dou uglas & Wes Nol lte 303

<apex:pageBlock > <apex:pageBlockButtons > <apex:commandButton action={!submit} value=Submit rerender=resultsPanel status=status/> </apex:pageBlockButtons> <apex:pageMessages /> This example calls Yahoo! Map geocoding REST service with the address you provide below.<p/> <apex:pageBlockSection> <apex:pageBlockSectionItem> <apex:outputLabel for=address>Address</apex:outputLabel> <apex:inputText id=address value={!address}/> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockSection > <apex:pageBlockSectionItem > <apex:outputLabel for=city>City</apex:outputLabel> <apex:inputText id=city value={!city}/> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockSection > <apex:pageBlockSectionItem > <apex:outputLabel for=state>State</apex:outputLabel> <apex:inputText id=state value={!state}/> </apex:pageBlockSectionItem> </apex:pageBlockSection><br/> <apex:actionStatus id=status startText=Fetching map.../> <apex:outputPanel id=resultsPanel> <apex:outputText value={!geoAddress}/> </apex:outputPanel>


Salesforce Handbook

</apex:pageBlock> </apex:form> </apex:page>

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. Weve 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 pages submit button public PageReference submit( ) { List<GeoResult> results = getMap(address,city,state); geoAddress = results[0].toDisplayString( ); return null; } // call the REST service with the address info public List<GeoResult> getMap(String street, String city, String state) { HttpRequest req = new HttpRequest( ); Http http = new Http( ); List<GeoResult> results = new List<GeoResult>( ); // set the request method req.setMethod(GET); // set the yahoo maps url with address
Jeff Douglas & Wes Nolte 305

String url = d= http://local.yahooapis.com/MapsService/V1/geocode?appi + 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 // inner class 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 + ]; } } }

Ca alling a REST Web Ser rvice (JSON N)

Using JSON RESTful Web Services w salesforce.c N W with com opens up your Org to a number p of third-party in ntegration oppo ortunities (Go oogle, Yahoo!, Flickr, bespok etc.). JSON support ke, N isn baked into the Force.com platform but Ron Hess at salesforce.com has ported t JSON nt m t m the parser that will d the heavy lif do fting for you. Weve put together a sma demo where you enter your address and the Apex cod fetches all e d de the address and coordinates from the Goog Maps. The service retur the data as a JSON e f gle e rns s ob bject. You can run this sam mple at https://jeffdouglas-deve eloper-edition.na5 5.force.com/ examples/R RestDemoJson

Jeff Dou uglas & Wes Nol lte


To get started, youll 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. Youll 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 weve had to check each one.


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 pages 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<string> 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
<apex:page controller=RestDemoJsonController tabStyle=Contact>
312 Salesforce Handbook

<apex:sectionHeader title=Google Maps Geocoding subtitle=REST Demo (JSON)/> <apex:form > <apex:pageBlock > <apex:pageBlockButtons > <apex:commandButton action={!submit} value=Submit rerender=resultsPanel status=status/> </apex:pageBlockButtons> <apex:pageMessages /> This example calls the Google Map geocoding REST service (JSON) with the address provide below.<p/> 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.<p/> <apex:pageBlockSection > <apex:pageBlockSectionItem > <apex:outputLabel for=address>Address</apex:outputLabel> <apex:inputText id=address value={!address}/> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockSection > <apex:pageBlockSectionItem > <apex:outputLabel for=city>City</apex:outputLabel> <apex:inputText id=city value={!city}/> </apex:pageBlockSectionItem> </apex:pageBlockSection> <apex:pageBlockSection > <apex:pageBlockSectionItem >
Jeff Douglas & Wes Nolte 313

<apex:outputLabel for=state>State</apex:outputLabel> <apex:inputText id=state value={!state}/> </apex:pageBlockSectionItem> </apex:pageBlockSection><br/> <apex:pageBlockSection > <apex:pageBlockSectionItem > <apex:outputLabel for=useGoogle> Use hard-coded Google JSON response? </apex:outputLabel> <apex:inputCheckbox value={!useGoogle}/> </apex:pageBlockSectionItem> </apex:pageBlockSection><br/> <apex:actionStatus id=status startText=Fetching map.../> <apex:outputPanel id=resultsPanel> <apex:outputText value={!geoAddress}/><br/> </apex:outputPanel> </apex:pageBlock> </apex:form> </apex:page> 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<opportunity> 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 cant confirm but weve 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 opportunitys 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 doesnt 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<ProcessInstance> 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; } } } }


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 weve 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 youll then need to assign this template to the mail youre 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 theres no need to specify the to-addresses, the subject, or the email body; theyre 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 theyre 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 cant be used in bulk emails.

Jeff Douglas & Wes Nolte


After youve 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 wont 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 persons 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:
testemailservice@8q8zrtgg1w37vpomrhpqftj25.in.sandbox.salesforc 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. Email Detail from an Inboun Service 1 l nd

The code in Listing 6 - 44 wil give virtually 100% code coverage for th previous class. T ll y he Listing 6 - 44. Unit Test for Inbound Em Handler L mail r
static test s tMethod voi testMe( ) { id // create a new em mail and en nvelope obj ject ng.InboundE Email email = new Me l essaging.In nboundEmail ) l( Messagin ; Messagin ng.InboundE Envelope en = nv new Me essaging.In nboundEnvel lope( ); // setup the data for the em p mail email.su ubject = T Test Job Ap pplicant; email.fr romname = FirstName LastName; ; env.from mAddress = someaddre ess@email.c com; // add a attachme an ent Messagin ng.InboundE Email.Binar ryAttachmen attachm nt ment = new Me essaging.In nboundEmail l.BinaryAtt tachment( );
322 Salesforce Handb book

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,someaddress@email.com); // 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 cant 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 well 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<Account> accounts{get;set;} public void aMethod( ){ // Debug should System.debug(accounts:+accounts); for(Account a: accounts){ // Insert logic here } } public void anotherMethod( ){ for(Account a: [SELECT id FROM Account WHERE condition = true]){ // Insert logic here } } } go here:

If youre 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 youre going wrong. Exceptions The last and trickiest case well cover is exception handlers. The reason theyre 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; }


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<Account> 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 doesnt exist in my real dataset; mc.aMethod( ); List<Account> 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 wed 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 wed recommend only testing your public methods Read through the Force.com IDE code coverage report. It will tell you which lines of code havent 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 isnt counted against your Org. It also makes maintenance (especially in teams) much easier

These samples are relatively simple, but youll 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. Weve 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<ContactShare> List<ContactShare>( ); 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<ContactShare> sharesToCreate = new List<ContactShare>( ); List<ID> shareIdsToDelete = new List<ID>( ); 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<ID> ids = new Set<ID>( ); List<Contact> contacts = new List<Contact>( ); for (Integer i=0;i<50;i++) contacts.add(new Contact(FirstName=First , LastName=Name +i, Email=email+i+@email.com,Make_Public__c=true));


Salesforce Handbook

insert contacts; // get a set of all new created ids for (Contact c : contacts) ids.add(c.id); // assert that 50 shares were created List<ContactShare> where ContactId IN :ids and RowCause = Manual]; System.assertEquals(shares.size( ),50); } // insert records // switch them from public = true to public = false static testMethod void testUpdateContacts( ) { Set<ID> ids = new Set<ID>( ); List<Contact> contacts = new List<Contact>( ); for (Integer i=0;i<50;i++) contacts.add(new Contact(FirstName=First , LastName=Name +i, Email=email+i+@email.com,Make_Public__c=false)); insert contacts; for (Contact c : contacts) ids.add(c.id); update contacts; // assert that 0 shares exist List<ContactShare> where ContactId IN :ids and RowCause = Manual]; System.assertEquals(shares.size( ),0); for (Contact c : contacts) c.Make_Public__c = true;
Jeff Douglas & Wes Nolte 331











update contacts; // assert that 50 shares were created shares = [select id from ContactShare where ContactId IN :ids and RowCause = Manual]; System.assertEquals(shares.size( ),50); for (Contact c : contacts) c.Make_Public__c = false; update contacts; // assert that 0 shares exist shares = [select id from ContactShare where ContactId IN :ids and RowCause = Manual]; System.assertEquals(shares.size( ),0); } }

Something to remember when transferring accounts and their related data is that all existing sharing rules will be removed. Any relevant sharing rules are then applied to the records based upon the new owners. You may need to manually share these accounts and opportunities to grant access to certain users and/or groups.

Rolling Back Transactions with Database Savepoints

Transaction control is an important part of any system that interacts with a database and salesforce.com has neat ways of implementing said control. Anyone thats worked with SQL databases will be familiar with savepoints and rolling back, and salesforce.com has implemented similar constructs. For those who havent heard of these terms Wikipedia describes them thus: A savepoint is a way of implementing subtransactions (also known as nested transactions) within a relational database management system by indicating a point within a transaction that can be rolled back to without affecting any work done in the transaction before the savepoint was created. A rollback is an operation, which returns the database to some previous state. Listing 6 - 53 demonstrates a single method that inserts two object records, which are related by a master-detail relationship. Listing 6 - 53. Code to Insert Related Records
public void myMethod( ){ Child__c child;


Salesforce Handbook

try{ child = new Child__c( ); insert child; } catch (System.DmlException e){ System.debug(e); } /** Do Some processing **/ try { Parent__c parent = new Parent__c( ); parent.child__c = child.id; insert parent; } catch (System.Dmlexception e){ System.debug(e); } }

If the DML operation on the Parent__c object record fails, the Child__c object record will have been inserted but not attached to any master record. Depending on your data model this can lead to an erroneous data states and/or unnecessary storage usage. Luckily savepoints and rollbacks are a very easy to implement and solves this issue robustly. The revised code is shown in Listing 6 - 54. Listing 6 - 54. Related Record Inserts Using Savepoints
public void myMethod( ){ // Any DML performed after this savepoint will be // undone should a rollback occur Savepoint sp = Database.setSavepoint( ); Child__c child; try{ child = new Child__c( ); insert child; } catch (System.DmlException e){ System.debug(e);
Jeff Douglas & Wes Nolte 333

} /** Do Some processing **/ try { Parent__c parent = new Parent__c( ); parent.child__c = child.id; insert parent; } catch (System.Dmlexception e){ System.debug(e); // Rollback the database to the state held at the // time of defining the savepoint Database.rollback(sp); } }

Some points to consider when using savepoints and rollbacks are: You can continue processing after a rollback but note that only database DML will be undone, variable values will not be rolled back. You cannot rollback across triggers. You can only set five savepoints across all contexts. For this reason we find its usually a good idea to have at least a one-to-one ratio between class and test methods

Enforcing Security With Sharing Keywords

Security is a major foundation of the Force.com platform. Not only is security available declaratively but it is also baked into the Apex language itself. Most Apex scripts run in system context without respect to the current users permissions, sharing rules and field level security. This ensures that triggers and web services have access to all records in the Org, which is usually a good thing. However, to ensure that you dont expose sensitive data to unauthorized users, you can specify that an Apex script does enforce the running users profile-based permissions, field-level security, and Org-wide defaults by using the with sharing keywords when declaring your class. This can affect SOQL and SOSL queries as well as DML operations. Listing 6 - 55. Class Implemented With Sharing
public with sharing class MyClass { // class implementation }
334 Salesforce Handbook

You can also use the without sharing keywords to ensure that Apex scripts do not enforce the sharing rules of the running user. Listing 6 - 56. Class Implemented Without Sharing
public without sharing class MyClass { // class implementation }

Its best practice to use these keywords when declaring new classes because if they are not used the current sharing rules remain in effect. For example, if a class calls another class with no sharing-keywords specified then the sharing is enforced by the first class. You can also declare inner classes and outer classes as with sharing as well. The sharing setting applies to all code contained in the class including initialization code, constructors, and methods but inner classes do not inherit the sharing setting from their container class. One exception is executeAnonymous, which always executes using the full permissions of the current user.

Working with Person Accounts

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. You dont hear a lot of talk about it but salesforce.com can be tweaked for this scenario using person accounts. By default, person accounts are not enabled. Youll 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 would recommend you enable a Developer Edition 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? The salesforce.com Help has a lot of good info on person accounts but we wanted to dig in and really see what was happening in the background. 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. So when person accounts are enabled youll see a new set of menu items under Setup -> App Setup -> Customize -> Accounts. You can configure person account page layout like you would any other type of page layout. Youll need to go and assign the new record type to each of the profiles that need access to it.

Jeff Douglas & Wes Nolte


e Items Figure 6 - 13. Person account Menu I

Once youve d O done they you will be able to create acco u ounts for Bus siness and Per rsonal record types. When you click the New Account b d N button youll r receive a pickli asking you w ist which type to create. o


Salesforce Handb book

Figu 6 - 14. Creati person acco ure ing ount records

So what h happens when you create a new person account? A person acco n n ount is a combination of both an accou and conta record. Wh person acc unt act hen counts are ena abled, the fol llowing fields a added to th account obj are he ject: 1. FirstN Name 2. LastN Name 3. IsPes sonAccount 4. Lang guages_pc 5. Leve el_pc 6. Perso onAssistantNa ame 7. Perso onAssistantPh hone 8. Perso onBirthdate 9. Perso onContactId 10. Perso onDepartment t
Jeff Dou uglas & Wes Nol lte 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.


Salesforce Handbook

Figure 6 - 15. A person accoun page nt

When you create new person account r records, salesf force.com crea not only an account ates n rec cord but also a contact rec cord in the ba ackground. Yo cannot access the accou record ou unt dir rectly (it alway relocates yo back to the person acco ys ou e ount record) but it is neede for the b ed fun nctionality tha requires a contact (emails customer po at c s, ortal, etc.). Fig gure 6 - 16 an 6 - 17 nd show what the re ecords look lik from SOQL ke L.

Figure 6 - 16. The accou record for a person account unt t

Jeff Dou uglas & Wes Nol lte


7. Record for a pers account son Figure 6 - 17 The contact R

Some other thi S ings to take int consideratio for person a to on accounts includ de: Person ac ccounts can be associated w activities u e with using either th Name or Related he To fields. Person ac ccounts can be invited to gro events and requested me e oup d eetings. Person ac ccounts can be added to Ca e ampaigns and have a Campa aign History related list. For cases person acco s, ounts can be e entered in the account Nam field, the co me ontact Name fiel or both. ld, You can add person ac ccounts to the contact Role related list on cases, cont e es o tracts, and oppo ortunities. Custom o objects with relationships to either accou o unts or contac can be add as cts ded related lists on person accounts. a Person ac ccounts can be enabled as users for your Customer and Self-service por e S rtals. Person a accounts are currently supp c ported in Connect Offline and Connec for e ct Outlook version 3.2 an later. They are not curr nd y rently support in Connec for ted ct Lotus No otes. You can s send individua emails and m emails to p al mass person accoun nts. For field history, acco ount fields fo person acco or ounts can be tracked usin the ng account f field history se ettings, but con ntact fields for person accounts are confi igured on the contact field hist tory settings pa age. Person a accounts have a unique im e mport wizard so make su you check the ure k salesforce e.com Help for more info. r Leads wit a blank Co th ompany field a converted to person acc are counts. The d default person ac ccount record type for your p t profile is applie to the new person accoun ed nt. You cann add a conta formula fie that referen the accou object to p not act eld nces unt person accounts page layouts.


Salesforce Handb book

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



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 weve 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.