salesforce: Winter ’13 Force.com Apex Code Developer's Guide Last updated: December 7 2012 © Copyright 2000–2012 salesforce.com, inc. All rights reserved. Salesforce.com is a registered trademark of salesforce.com, inc., as are other names and marks. Other marks appearing herein may be trademarks of their respective owners. Table of Contents Table of Contents Chapter 1: Introducing Apex...............................................................................................................11 What is Apex?.........................................................................................................................................................................12 How Does Apex Work?..............................................................................................................................................13 What is the Apex Development Process?....................................................................................................................14 Using a Developer or Sandbox Organization...................................................................................................14 Learning Apex.................................................................................................................................................17 Writing Apex...................................................................................................................................................18 Writing Tests...................................................................................................................................................19 Deploying Apex to a Sandbox Organization...................................................................................................19 Deploying Apex to a Salesforce Production Organization...............................................................................20 Adding Apex Code to a Force.com AppExchange App..................................................................................20 When Should I Use Apex?..........................................................................................................................................21 What are the Limitations of Apex?.............................................................................................................................21 What's New?...........................................................................................................................................................................22 Apex Quick Start.....................................................................................................................................................................22 Documentation Typographical Conventions...............................................................................................................22 Understanding Apex Core Concepts...........................................................................................................................23 Writing Your First Apex Class and Trigger................................................................................................................28 Creating a Custom Object...............................................................................................................................28 Adding an Apex Class.....................................................................................................................................29 Adding an Apex Trigger..................................................................................................................................30 Adding a Test Class.........................................................................................................................................31 Deploying Components to Production............................................................................................................33 Chapter 2: Language Constructs.........................................................................................................35 Data Types..............................................................................................................................................................................36 Primitive Data Types...................................................................................................................................................36 sObject Types..............................................................................................................................................................39 Accessing sObject Fields..................................................................................................................................40 Accessing sObject Fields Through Relationships............................................................................................41 Validating sObjects and Fields .......................................................................................................................42 Collections...................................................................................................................................................................43 Lists.................................................................................................................................................................43 Sets..................................................................................................................................................................48 Maps................................................................................................................................................................50 Parameterized Typing......................................................................................................................................51 Using Custom Types in Map Keys and Sets....................................................................................................51 Iterating Collections........................................................................................................................................54 Enums.........................................................................................................................................................................54 Understanding Rules of Conversion............................................................................................................................56 Variables..................................................................................................................................................................................57 i Table of Contents Case Sensitivity............................................................................................................................................................58 Constants.....................................................................................................................................................................58 Expressions..............................................................................................................................................................................59 Understanding Expressions.........................................................................................................................................59 Understanding Expression Operators..........................................................................................................................60 Understanding Operator Precedence...........................................................................................................................66 Extending sObject and List Expressions.....................................................................................................................66 Using Comments.........................................................................................................................................................67 Assignment Statements...........................................................................................................................................................67 Conditional (If-Else) Statements............................................................................................................................................68 Loops.......................................................................................................................................................................................69 Do-While Loops.........................................................................................................................................................69 While Loops................................................................................................................................................................70 For Loops....................................................................................................................................................................70 Traditional For Loops.....................................................................................................................................71 List or Set Iteration For Loops........................................................................................................................71 SOQL For Loops............................................................................................................................................72 SOQL and SOSL Queries......................................................................................................................................................73 Working with SOQL and SOSL Query Results.........................................................................................................75 Working with SOQL Aggregate Functions................................................................................................................76 Working with Very Large SOQL Queries..................................................................................................................76 Using SOQL Queries That Return One Record........................................................................................................79 Improving Performance by Not Searching on Null Values.........................................................................................79 Understanding Foreign Key and Parent-Child Relationship SOQL Queries.............................................................80 Working with Polymorphic Relationships in SOQL Queries.....................................................................................80 Using Apex Variables in SOQL and SOSL Queries...................................................................................................81 Querying All Records with a SOQL Statement..........................................................................................................83 Locking Statements.................................................................................................................................................................83 Locking in a SOQL For Loop....................................................................................................................................83 Avoiding Deadlocks....................................................................................................................................................84 Transaction Control................................................................................................................................................................84 Exception Statements..............................................................................................................................................................85 Throw Statements.......................................................................................................................................................85 Try-Catch-Finally Statements.....................................................................................................................................85 Chapter 3: Invoking Apex...................................................................................................................87 Triggers...................................................................................................................................................................................88 Bulk Triggers...............................................................................................................................................................89 Trigger Syntax.............................................................................................................................................................89 Trigger Context Variables...........................................................................................................................................90 Context Variable Considerations.................................................................................................................................92 Common Bulk Trigger Idioms....................................................................................................................................93 Using Maps and Sets in Bulk Triggers............................................................................................................93 Correlating Records with Query Results in Bulk Triggers..............................................................................94 Using Triggers to Insert or Update Records with Unique Fields.....................................................................94 ii Table of Contents Defining Triggers........................................................................................................................................................94 Triggers and Merge Statements..................................................................................................................................96 Triggers and Recovered Records.................................................................................................................................97 Triggers and Order of Execution.................................................................................................................................97 Operations that Don't Invoke Triggers.......................................................................................................................99 Entity and Field Limitations in Triggers...................................................................................................................101 Trigger Exceptions....................................................................................................................................................101 Trigger and Bulk Request Best Practices...................................................................................................................102 Apex Scheduler......................................................................................................................................................................103 Anonymous Blocks................................................................................................................................................................108 Apex in AJAX.......................................................................................................................................................................109 Chapter 4: Classes, Objects, and Interfaces........................................................................................111 Understanding Classes..........................................................................................................................................................112 Defining Apex Classes...............................................................................................................................................112 Extended Class Example...........................................................................................................................................113 Declaring Class Variables..........................................................................................................................................116 Defining Class Methods............................................................................................................................................117 Using Constructors....................................................................................................................................................119 Access Modifiers........................................................................................................................................................121 Static and Instance.....................................................................................................................................................122 Using Static Methods and Variables..............................................................................................................122 Using Instance Methods and Variables..........................................................................................................123 Using Initialization Code...............................................................................................................................124 Apex Properties.........................................................................................................................................................125 Interfaces and Extending Classes..........................................................................................................................................127 Custom Iterators........................................................................................................................................................128 Keywords...............................................................................................................................................................................130 Using the final Keyword............................................................................................................................................131 Using the instanceof Keyword...................................................................................................................................131 Using the super Keyword...........................................................................................................................................131 Using the this Keyword.............................................................................................................................................132 Using the transient Keyword.....................................................................................................................................133 Using the with sharing or without sharing Keywords................................................................................................134 Annotations...........................................................................................................................................................................136 Deprecated Annotation.............................................................................................................................................137 Future Annotation.....................................................................................................................................................137 IsTest Annotation.....................................................................................................................................................138 ReadOnly Annotation...............................................................................................................................................141 RemoteAction Annotation........................................................................................................................................142 Apex REST Annotations..........................................................................................................................................142 RestResource Annotation..............................................................................................................................143 HttpDelete Annotation.................................................................................................................................143 HttpGet Annotation......................................................................................................................................144 HttpPatch Annotation...................................................................................................................................144 iii Table of Contents HttpPost Annotation.....................................................................................................................................144 HttpPut Annotation......................................................................................................................................144 Classes and Casting...............................................................................................................................................................144 Classes and Collections.............................................................................................................................................146 Collection Casting.....................................................................................................................................................146 Differences Between Apex Classes and Java Classes.............................................................................................................146 Class Definition Creation......................................................................................................................................................147 Naming Conventions.................................................................................................................................................149 Name Shadowing......................................................................................................................................................149 Class Security........................................................................................................................................................................149 Enforcing Object and Field Permissions...............................................................................................................................150 Namespace Prefix..................................................................................................................................................................151 Using Namespaces When Invoking Methods...........................................................................................................152 Namespace, Class, and Variable Name Precedence...................................................................................................152 Type Resolution and System Namespace for Types..................................................................................................153 Version Settings....................................................................................................................................................................153 Setting the Salesforce API Version for Classes and Triggers....................................................................................154 Setting Package Versions for Apex Classes and Triggers..........................................................................................155 Chapter 5: Testing Apex...................................................................................................................156 Understanding Testing in Apex............................................................................................................................................157 Why Test Apex?........................................................................................................................................................157 What to Test in Apex................................................................................................................................................157 Unit Testing Apex.................................................................................................................................................................158 Isolation of Test Data from Organization Data in Unit Tests..................................................................................159 Using the runAs Method...........................................................................................................................................160 Using Limits, startTest, and stopTest.......................................................................................................................161 Adding SOSL Queries to Unit Tests........................................................................................................................162 Running Unit Test Methods.................................................................................................................................................163 Testing Best Practices...........................................................................................................................................................167 Testing Example...................................................................................................................................................................168 Chapter 6: Dynamic Apex.................................................................................................................173 Understanding Apex Describe Information..........................................................................................................................174 Dynamic SOQL....................................................................................................................................................................183 Dynamic SOSL.....................................................................................................................................................................183 Dynamic DML.....................................................................................................................................................................184 Chapter 7: Batch Apex......................................................................................................................187 Using Batch Apex..................................................................................................................................................................188 Understanding Apex Managed Sharing................................................................................................................................197 Understanding Sharing..............................................................................................................................................197 Sharing a Record Using Apex....................................................................................................................................199 Recalculating Apex Managed Sharing.......................................................................................................................204 Chapter 8: Debugging Apex..............................................................................................................209 iv Table of Contents Understanding the Debug Log..............................................................................................................................................210 Working with Logs in the Developer Console..........................................................................................................214 Debugging Apex API Calls.......................................................................................................................................223 Handling Uncaught Exceptions............................................................................................................................................224 Understanding Execution Governors and Limits..................................................................................................................225 Using Governor Limit Email Warnings...............................................................................................................................230 Chapter 9: Developing Apex in Managed Packages............................................................................231 Package Versions...................................................................................................................................................................232 Deprecating Apex..................................................................................................................................................................232 Behavior in Package Versions................................................................................................................................................233 Versioning Apex Code Behavior...............................................................................................................................233 Apex Code Items that Are Not Versioned................................................................................................................234 Testing Behavior in Package Versions.......................................................................................................................235 Chapter 10: Exposing Apex Methods as SOAP Web Services..............................................................237 WebService Methods............................................................................................................................................................238 Exposing Data with WebService Methods................................................................................................................238 Considerations for Using the WebService Keyword..................................................................................................238 Overloading Web Service Methods...........................................................................................................................240 Chapter 11: Exposing Apex Classes as REST Web Services................................................................241 Introduction to Apex REST..................................................................................................................................................242 Apex REST Annotations......................................................................................................................................................242 Apex REST Methods............................................................................................................................................................242 Exposing Data with Apex REST Web Service Methods......................................................................................................247 Apex REST Code Samples...................................................................................................................................................248 Apex REST Basic Code Sample...............................................................................................................................248 Apex REST Code Sample Using RestRequest.........................................................................................................249 Chapter 12: Invoking Callouts Using Apex........................................................................................251 Adding Remote Site Settings................................................................................................................................................252 SOAP Services: Defining a Class from a WSDL Document...............................................................................................252 Invoking an External Service.....................................................................................................................................253 HTTP Header Support.............................................................................................................................................253 Supported WSDL Features.......................................................................................................................................254 Understanding the Generated Code..........................................................................................................................257 Testing Web Service Callouts...................................................................................................................................259 Considerations Using WSDLs..................................................................................................................................261 Mapping Headers..........................................................................................................................................261 Understanding Runtime Events.....................................................................................................................262 Understanding Unsupported Characters in Variable Names.........................................................................262 Debugging Classes Generated from WSDL Files.........................................................................................262 Invoking HTTP Callouts......................................................................................................................................................262 Using Certificates..................................................................................................................................................................263 Generating Certificates..............................................................................................................................................263 v Table of Contents Using Certificates with SOAP Services.....................................................................................................................264 Using Certificates with HTTP Requests...................................................................................................................265 Callout Limits and Limitations.............................................................................................................................................265 Chapter 13: Reference.......................................................................................................................267 Apex Data Manipulation Language (DML) Operations......................................................................................................268 ConvertLead Operation............................................................................................................................................269 Delete Operation.......................................................................................................................................................272 Insert Operation........................................................................................................................................................274 Merge Statement.......................................................................................................................................................277 Undelete Operation...................................................................................................................................................278 Update Operation......................................................................................................................................................280 Upsert Operation.......................................................................................................................................................282 sObjects That Do Not Support DML Operations....................................................................................................286 sObjects That Cannot Be Used Together in DML Operations................................................................................287 Bulk DML Exception Handling...............................................................................................................................289 Apex Standard Classes and Methods....................................................................................................................................289 Apex Primitive Methods...........................................................................................................................................290 Blob Methods................................................................................................................................................290 Boolean Methods...........................................................................................................................................291 Date Methods................................................................................................................................................291 Datetime Methods.........................................................................................................................................294 Decimal Methods..........................................................................................................................................299 Double Methods............................................................................................................................................304 ID Methods...................................................................................................................................................306 Integer Methods............................................................................................................................................307 Long Methods...............................................................................................................................................308 String Methods..............................................................................................................................................308 Time Methods...............................................................................................................................................332 Apex Collection Methods..........................................................................................................................................333 List Methods.................................................................................................................................................333 Map Methods................................................................................................................................................340 Set Methods...................................................................................................................................................344 Enum Methods.........................................................................................................................................................347 Apex sObject Methods..............................................................................................................................................348 Schema Methods...........................................................................................................................................348 sObject Methods............................................................................................................................................352 sObject Describe Result Methods.................................................................................................................357 Describe Field Result Methods.....................................................................................................................361 Schema.FieldSet Methods.............................................................................................................................369 Custom Settings Methods.............................................................................................................................372 Apex System Methods...............................................................................................................................................380 ApexPages Methods......................................................................................................................................380 Approval Methods.........................................................................................................................................381 Database Methods.........................................................................................................................................382 vi Table of Contents JSON Support...............................................................................................................................................396 Limits Methods.............................................................................................................................................413 Math Methods...............................................................................................................................................416 MultiStaticResourceCalloutMock Methods..................................................................................................421 Apex REST...................................................................................................................................................421 Search Methods.............................................................................................................................................427 StaticResourceCalloutMock Methods...........................................................................................................427 System Methods............................................................................................................................................428 Test Methods.................................................................................................................................................439 Type Methods...............................................................................................................................................444 URL Methods...............................................................................................................................................448 UserInfo Methods..........................................................................................................................................451 Version Methods...........................................................................................................................................452 Using Exception Methods.........................................................................................................................................454 Apex Classes..........................................................................................................................................................................457 Apex Email Classes...................................................................................................................................................457 Outbound Email............................................................................................................................................457 Inbound Email...............................................................................................................................................469 Exception Class.........................................................................................................................................................474 Constructing an Exception............................................................................................................................475 Using Exception Variables.............................................................................................................................476 Visualforce Classes.....................................................................................................................................................476 Action Class...................................................................................................................................................477 Dynamic Component Methods and Properties.............................................................................................478 IdeaStandardController Class........................................................................................................................479 IdeaStandardSetController Class...................................................................................................................482 KnowledgeArticleVersionStandardController Class......................................................................................486 Message Class................................................................................................................................................489 PageReference Class......................................................................................................................................490 SelectOption Class.........................................................................................................................................496 StandardController Class...............................................................................................................................498 StandardSetController Class..........................................................................................................................500 Flow.Interview Class.................................................................................................................................................503 Pattern and Matcher Classes.....................................................................................................................................504 Using Patterns and Matchers.........................................................................................................................504 Using Regions................................................................................................................................................505 Using Match Operations...............................................................................................................................505 Using Bounds................................................................................................................................................506 Understanding Capturing Groups.................................................................................................................506 Pattern and Matcher Example.......................................................................................................................506 Pattern Methods............................................................................................................................................507 Matcher Methods..........................................................................................................................................509 HTTP (RESTful) Services Classes...........................................................................................................................514 HTTP Classes...............................................................................................................................................515 Crypto Class..................................................................................................................................................525 vii Table of Contents EncodingUtil Class........................................................................................................................................531 XML Classes.............................................................................................................................................................532 XmlStream Classes........................................................................................................................................532 DOM Classes................................................................................................................................................539 Apex Approval Processing Classes............................................................................................................................545 Apex Approval Processing Example..............................................................................................................545 ProcessRequest Class.....................................................................................................................................546 ProcessResult Class........................................................................................................................................547 ProcessSubmitRequest Class.........................................................................................................................547 ProcessWorkitemRequest Class....................................................................................................................548 BusinessHours Class..................................................................................................................................................549 Apex Community Classes..........................................................................................................................................551 Answers Class................................................................................................................................................551 Ideas Class.....................................................................................................................................................552 Knowledge Management Publishing Service Class...................................................................................................555 Site Class...................................................................................................................................................................559 Cookie Class..............................................................................................................................................................565 Network Class...........................................................................................................................................................567 Apex Interfaces......................................................................................................................................................................567 Auth.RegistrationHandler Interface..........................................................................................................................569 Comparable Interface................................................................................................................................................572 HttpCalloutMock Interface.......................................................................................................................................574 InstallHandler Interface.............................................................................................................................................574 Support.EmailTemplateSelector Interface................................................................................................................576 Site.UrlRewriter Interface..........................................................................................................................................577 Using the Process.Plugin Interface............................................................................................................................584 Process.Plugin Interface.................................................................................................................................585 Process.PluginRequest Class..........................................................................................................................586 Process.PluginResult Class............................................................................................................................587 Process.PluginDescribeResult Class..............................................................................................................587 Process.Plugin Data Type Conversions.........................................................................................................590 Sample Process.Plugin Implementation for Lead Conversion.......................................................................590 UninstallHandler Interface........................................................................................................................................596 WebServiceMock Interface.......................................................................................................................................598 Chapter 14: Deploying Apex.............................................................................................................599 Using Change Sets To Deploy Apex.....................................................................................................................................600 Using the Force.com IDE to Deploy Apex...........................................................................................................................600 Using the Force.com Migration Tool....................................................................................................................................601 Understanding deploy................................................................................................................................................602 Understanding retrieveCode......................................................................................................................................604 Understanding runTests()..........................................................................................................................................605 Using SOAP API to Deploy Apex........................................................................................................................................606 Appendices......................................................................................................................................607 viii
Description: